CAT-RAG: Improving Secure Code Generation with Category-Aware Agentic RetrievalCAT-RAG: Improving Secure Code Generation with Category-Aware Agentic Retrieval
On CyberSecEval with functional retrieval added, CAT-RAG's average SR gain is 23.57%, and CodeGuarder's is 12.11%.
The attacker knows the code generation framework, and the target is the functional RACG knowledge base. Scenario I (exposed intents) knows the query and injects the most similar vulnerable examples. Scenario II (intent-agnostic) does not know the query; after clustering, it takes the top 10% representative entries and injects the nearest vulnerable counterparts.
- Injecting security knowledge item by item per CWE lengthens the prompt and dilutes attention when a single query involves multiple related weaknesses, and is also inconsistent with how developers think in terms of programming tasks rather than CWE numbers. CAT-RAG aims to improve the security of generated code with more compact category knowledge without changing the model.
- Offline, related CWEs for C, C++, Python and Java are consolidated by shared security concerns into language-related categories, each containing practice points and secure code examples. At inference time, an LLM classifier identifies the language and adaptively selects categories (dynamic k), and the knowledge is appended to the query; it can also be stacked with functional retrieval or optional summarization.
- On CyberSecEval, with functional RACG added, CAT-RAG's average SR gain is 23.57% and CodeGuarder's is 12.11%, with 41.71% fewer total tokens. Under the two poisoning scenarios, they improve by 17.97% and 17.86% respectively relative to the poisoned baseline.
- The authors note that SR only reflects weaknesses detectable by static rules and cannot determine exploitability; classification errors were not directly measured. The knowledge base does not cover 12/33 CWEs of CyberSecEval and 18/42 CWEs of CodeGuard+. Future work includes expanding languages, updating the knowledge base, and using dynamic analysis or fuzzing.
- Evaluated models
- Qwen2.5-Coder-7BDeepSeek-Coder-V2-16BCodeLlama-13BGPT-5.4-mini
- Benchmarks
- CyberSecEvalCodeGuard+HumanEvalReposVul
- Metrics
- Security Rate (SR)CodeBLEUpass@ksecure-pass@k
CAT-RAG is a category-aware agentic retrieval-augmented code generation framework that uses an LLM as a classifier agent to adaptively select security categories, replacing CWE-level retrieval with language-specific categories; each category integrates best practices and secure code examples to streamline prompts, and it can serve independently as a security layer or plug into the RACG pipeline without modifying the underlying model. On CyberSecEval, its secure code generation improvement is nearly twice that of SOTA (23.57% vs. 12.11%), with token overhead reduced by 41.71%; the evaluation also covers CodeGuard+ and HumanEval.
Paper analysis
What problem does this paper attempt to solve?
Retrieving item by item per CWE lengthens the prompt and dilutes attention; CAT-RAG instead adaptively retrieves security knowledge by programming-domain category.
Retrieving item by item per CWE lengthens the prompt and dilutes attention on multi-weakness queries, and is inconsistent with how developers think about tasks.
- Scenario: The authors state that even when functionally correct, LLM-generated code often still contains security weaknesses. RACG injects external knowledge into the prompt to supplement functionality, but if the knowledge is verbose or poisoned, the risk is amplified.
- Existing shortcomings: Existing security-oriented RACG mostly injects knowledge at the granularity of a single CWE or vulnerability instance. A single query can involve multiple related weaknesses at once; item-by-item retrieval lengthens the prompt, dilutes attention, and may harm generation quality; the authors also state that developers express requirements more in terms of programming tasks and API usage than by CWE number.
- Hypothesis: The authors hypothesize that vulnerability types cluster by programming domain, and that consolidating related CWEs into compact, per-language categories both reduces prompt overhead and better matches how developers describe tasks.
- Method: They propose CAT-RAG. An LLM is used as a categorizer agent to adaptively select categories per query; the underlying model is unchanged, and it can serve as a standalone security layer or be added to existing RACG. Categories cover C, C++, Python and Java.
- Threat model:
- Victim location: The knowledge base of the functionality-oriented RACG; CAT-RAG, as a security layer stacked on top, is evaluated for resilience under this setting.
- Attacker knowledge: Following prior work, the authors assume the attacker knows the code generation framework.
- Scenario I (exposed intents): The user query is known; vulnerable examples most similar to the query are injected so that poisoned code ranks high in retrieval.
- Scenario II (intent-agnostic): The query is unknown; the knowledge base is clustered, the top 10% most representative entries are taken, and the closest vulnerable counterparts are injected.
What related research exists?
Related work is divided into code retrieval, security defects in generated code, model-side hardening, and security-oriented RACG; the main comparison is with CodeGuarder.
Code generation, retrieval and long context
- Code-oriented LLMs (cited in the paper as [21]–[23]) perform strongly on programming tasks, but the authors state that security gaps remain: functionally adequate code often still contains vulnerabilities.
- RACG ([5], [25], [26]) uses external, domain knowledge to mitigate functional limitations. Liu et al. (2024) report that irrelevant content in long contexts interferes with the model and degrades output.
- The authors state that functional knowledge bases often come from public repositories such as GitHub or from internal code without strict security vetting, and that poisoned or vulnerable libraries bias the model toward insecure patterns ([3], [8], [9]).
Weaknesses in generated code and model-side hardening
- Empirical studies ([1], [2], [4]) report frequent weaknesses such as null pointers, buffer overflows and array out-of-bounds. The common practice is to scan with Semgrep, Weggli or CodeQL; the authors state that such tools have false positives and do not address root causes at generation time.
- Hardening without retrieval includes prefix control in SVEN (He and Vechev, 2023) and instruction fine-tuning on curated corpora ([32]–[34]). More recent work uses local preference optimization targeting security-relevant code ([35]).
- The authors state that these methods often require fine-tuning or rely on specialized infrastructure that is not readily available.
Security-oriented RACG
- SecGuide (Tony et al., 2025) retrieves task guidance from MITRE CWE and CodeQL and compares it with recursive self-critique; the authors relay its finding that the two are comparable and that combining them further reduces insecure code. SOSecure (2025) retrieves, after generation, Stack Overflow answers and comments that flag vulnerabilities in similar code, as revision context.
- RESCUE (2025) builds a distilled hierarchical security knowledge base and uses multi-faceted retrieval instead of noisy original text. The authors state that when given only a natural language query, it must first generate a code draft to infer the CWE, adding an extra generation, and that the inference is only as reliable as that draft. SecCoder (Zhang et al., 2024) uses retrieved security demonstrations for in-context learning.
- CodeGuarder (Lin et al., 2025) decomposes the query into subtasks, maps them to specific CWEs and security patterns, then reranks and filters according to the host LLM's susceptibility to the corresponding vulnerability types. The authors state that this per-CWE granularity produces verbose prompts when a query spans multiple concerns and is inconsistent with how developers think in broad domains; they also state that it reports the highest security improvement among the compared prior work, so the comparison focuses on it.
Baselines and benchmarks
- The baseline is generation without retrieval. When comparing with CodeGuarder, both use the same ReposVul functional library; CodeGuarder uses the public default parameters k′=2 and k=5 per subtask. The retrieval strategy comparison is BM25, TF-IDF and jina-embeddings-v3. The authors state that CodeGuarder's results are stronger than SVEN, SafeCoder, SOSecure, CoSec and RCI.
- The benchmarks are CyberSecEval, CodeGuard+ and HumanEval.
The authors position this paper as: replacing per-CWE retrieval with language-related categories organized by shared security concerns, with an agent selecting a variable number of categories according to query complexity, as a security layer that requires no model changes.
How does the paper address this problem?
CAT-RAG uses a classifier agent to adaptively select language-specific safety categories per query, injecting practice points and secure code examples into the prompt.
CAT-RAG turns safety knowledge into language-specific programming-domain categories; a classifier agent selects a variable number of categories per query, and the practice points and secure code examples are then appended to the original prompt. It does not modify the code model and can be used alone or stacked on top of functional RACG.
Category Knowledge Base
- Scope: one library each for C, C++, Python, Java. Table I lists 10 categories per language, such as memory and buffers, input validation and injection, files and paths, cryptography and randomness. Some domains are shared across languages; deserialization, for example, appears only in Python and Java.
- Construction: the authors describe it as manual expert analysis, starting from the MITRE Top 25 and an empirical study of vulnerabilities in LLM-generated code. Experts first define common programming contexts, then assign CWEs to the contexts in which they are most likely to occur; the same CWE can enter multiple contexts.
- Entries: each category has a name and numeric ID, short practice points written from CWEs, and short secure code examples annotated with CWEs. The authors state that the guidelines and examples were drafted with the help of an LLM and kept short. Fig. 2 gives the points for C's File & Path Operations and a truncated secure file-opening example.
- Boundaries: the authors emphasize that the library construction is independent of the evaluation benchmarks, and also state that these categories are only a preliminary exploration and do not cover all CWEs and complex cases. What is being evaluated is the setting of category knowledge plus agentic retrieval.
Adaptive Selection
- Classifier: an LLM acts as the categorizer agent. The prompt gives the category names of all supported languages and asks for the detected language and a ranked list of relevant category IDs.
- dynamic k: top-k is not fixed. The classifier can vary the number per query from about 10 categories per language: a simple query may map to only one category, while a query involving files, memory and strings may map to three or more. The authors state this is to leave context budget for more complex queries.
- Injection: once selected, the practice points and secure code examples of each category are appended to the original query. Path (a) in Fig. 1 is this main path.
Optional Components
- Summarization: path (c) is optional. When enabled, another LLM shortens the retrieved points and examples, at the cost of one more inference. The authors treat it as a variant, not a required step.
- Functional retrieval: path (b) first retrieves code examples from the functional library, and CAT-RAG then injects the safety categories. In the evaluation this library is the fixed code from ReposVul, and the pipeline follows CodeGuarder's implementation.
- Offline preparation: path (d) is CWE analysis, category grouping and per-language library construction, which happens before inference.
Position in the Poisoning Setting
- The authors follow prior work: the attacker knows the code generation framework, and the poisoning target is the functional RACG knowledge base.
- Scenario I (exposed intents) injects the most similar vulnerable examples according to the known query. Scenario II (intent-agnostic) clusters the knowledge base without knowing the query, takes the top 10% representative entries, and injects the nearest vulnerable counterparts. The authors state that both are pessimistic cases in which the functional library contains deliberately misleading safety content, and that they can also extrapolate to unintentional misleading such as outdated or flawed code.
How Success Is Determined
- CyberSecEval safety is determined by ICD, with Semgrep and Weggli as tools. CodeGuard+ uses CodeQL and comes with functional tests. HumanEval tests functionality only, using unit tests.
- SR is the proportion of samples in which no unsafe coding practices are detected. pass@1 requires the single sample to pass all tests; pass@5 is any one of five samples being fully correct. secure-pass@k requires at least one sample to pass both the tests and the static security check.
What experiments did the paper conduct?
The authors report an average SR gain of 23.57% for functional RACG on CyberSecEval, and 12.11% for CodeGuarder.
Experimental Setup
- Code models: Qwen2.5-Coder-7B, DeepSeek-Coder-V2-16B, CodeLlama-13B, referred to below as Qwen-Coder, DS-Coder, CodeLlama. The Discussion additionally uses GPT-5.4-mini for a small generation experiment.
- Classification and summarization: the main classifier is Mistral-7B (Ollama, temperature 0.1); GPT-5-mini serves as the alternative classifier and summarizer.
- Data: CyberSecEval takes C 227, C++ 259, Java 229, Python 351, 1,066 in total, 33 CWEs; CodeGuard+ 103 items, 42 CWEs; HumanEval 164 problems. The functional library is the fixed code from ReposVul.
- Comparisons: generation without retrieval; CodeGuarder (k′=2, k=5 per subtask); BM25, TF-IDF, jina-embeddings-v3 on the same knowledge base.
- Metrics: SR is the proportion of samples in which static tools detect no unsafe coding practices. CyberSecEval uses ICD (Semgrep and Weggli, 189 rules, 50 practice types), CodeGuard+ uses CodeQL. CodeBLEU compares against reference code. pass@k requires at least one of k samples to pass all unit tests; secure-pass@k additionally requires passing the static security check.
- Decoding: generation temperature is generally 0, and 0.8 for HumanEval pass@5. Maximum new tokens are 4096 (CyberSecEval) and 2048 (the other two benchmarks). Hardware is NVIDIA A100. The paper does not report the number of SR repetitions.
Main Results
The table below shows the SR Δ% of Table V. CyberSecEval, the same ReposVul library and the no-retrieval baseline. CAT-RAG uses Mistral, dynamic k=1–3; CodeGuarder uses k′=2, k=5.
Swipe horizontally to read the table
Model / Method C C++ Java Python Qwen-Coder / CAT-RAG +26.18% +15.54% +18.82% +14.11% Qwen-Coder / CodeGuarder +19.83% +10.88% +48.53% +15.35% DS-Coder / CAT-RAG +27.51% +19.46% +47.98% +4.73% DS-Coder / CodeGuarder +15.83% +9.18% +26.55% +4.73% CodeLlama / CAT-RAG +32.13% +23.49% +43.51% +9.41% CodeLlama / CodeGuarder +1.46% +0.54% -6.87% -0.75% - The authors state that the average Δ% across the 12 groups is CAT-RAG +23.57% and CodeGuarder +12.11%; CAT-RAG is higher in 9 groups and tied in 1, and the groups where CodeGuarder is higher are Qwen-Coder's Java and Python.
- The authors state that CodeGuarder is below the no-retrieval baseline on CodeLlama's Java and Python, while CAT-RAG is positive in all.
- Bottom of Table V: average total tokens are CAT-RAG 1839.2 and CodeGuarder 3155.4, a reduction of 41.71%. The authors state that the reduction comes mainly from the input side.
Independent Setting, Summarization and Functionality
- Independent (Table II left, Mistral, k=1–3): the authors state that SR rises in all 12 groups, averaging +22.39%; DS-Coder +25.15%, CodeLlama +24.49%, Qwen-Coder +17.53%; Java +34.87%, C +26.37%, C++ +19.85%, Python +8.46%. CodeBLEU does not decrease in 10/12 groups; the decreases are Qwen-Coder/Java -1.88% and DS-Coder/Java -2.85%.
- Summarization and functional retrieval: the average SR gain in the middle of Table II is 23.57%, of which Java is +36.77%. Negative CodeBLEU values in this panel include Qwen-Coder/Java -1.96%, DS-Coder/Java -2.7%, CodeLlama/Java -10.06%. For the right-hand summarization (GPT-5-mini as both classifier and summarizer, k=1–5), the authors state an average of +24.27%; relative to the independent setting, C goes from +26.37% to +34.92%, C++ from +19.85% to +23.45%, Java from +34.87% to +30.8%, Python from +8.46% to +7.9%. The authors state that summarization is not better for every language.
- Functional correctness: in Table III (CodeGuard+, Mistral, k=1–3, greedy), CodeLlama's secure-pass@1, pass@1, SR are +30.56%, +16.93%, +28.23%; DS-Coder is +27.78%, +3.00%, 0.00; Qwen-Coder is -4.68%, -3.96%, +2.86%. The authors consider Qwen-Coder's trade-off a model-specific phenomenon. In Table IV, HumanEval pass@1 and pass@5 rise for all three models, with Qwen-Coder's pass@1 going from 74.39% to 81.71% (+9.84%).
Poisoning Resilience
Table VI uses GPT-5-mini as classifier and summarizer, k=1–5; Δ% is relative to the poisoned functional RACG.
- Scenario I: the authors state that all 12 groups rise, averaging +17.97%; Java, C, C++, Python average +28.02%, +18.04%, +13.32%, 12.47%.
- Scenario II: the authors state an average of +17.86%, with all 12 groups rising; C and Java average 25.63% and +24.57%. The authors state that explicit safety signals can override the bias of poisoned examples, regardless of whether the attacker knows the query.
Retrieval and Knowledge Base
- Structure (Table VIII, Mistral, k=1–5): the authors state that language-specific with code averages ΔSR +22.36%, highest in 10/12 groups; practice points only +8.99% (the RQ3 summary writes +8.98%); cross-language without code +4.28%; cross-language with code +0.19%, and below the baseline in 5/12 groups. The authors attribute this to idiomatic-style confusion caused by cross-language snippets.
- Strategy (Table IX, k=5): the authors state average ΔSR is CAT-RAG +22.12%, BM25 +18.96%, TF-IDF +18.08%, jina-embeddings-v3 +13.09%. CAT-RAG is non-negative in all 12 groups. Negative values include BM25's DS-Coder/Python -6.69%, TF-IDF's same cell -10.63%, and Jina-V3's DS-Coder/Python -22.83%, CodeLlama/Python -14.66%. The authors state that the latter three match surface forms rather than selecting by programming-domain intent.
Other Ablations and Analysis
- Figure 3 (Mistral, average over 12 groups): the authors recommend dynamic k=1–3 as the default and state that its SR is comparable to the highest among fixed k, and under the same upper bound its input tokens are at most about 45% fewer than fixed k=5. The caption states that dynamic k is no less safe than fixed k and uses fewer tokens, with the gap growing as k increases.
- Table VII (k=1–5): the authors state that GPT classification plus GPT summarization has the highest average SR gain, +24.27%, at about 1,499 tokens/query; Mistral classification plus GPT summarization is +23.56%, about 1,379 tokens/query. The authors state that the two Mistral summarization settings have the lowest average ΔSR, +12.91% and +18.43%.
- Discussion: on CyberSecEval with GPT-5.4-mini, the authors state that the four-language average baseline SR is about 67%, with a gain of +8.85%, an absolute gain smaller than that of the small open-source models. The authors also state that for Python the Cryptography & RNG category is selected most of the time and explicitly states to avoid weak cryptography and weak PRNGs, yet the model still does not avoid them; on Java it does avoid them.
What are some points that can be further explored?
The authors note that static analysis cannot measure exploitability and that classification errors were not directly measured; they plan to expand the knowledge base and languages.
Limitations and future directions noted by the authors
- Static metrics (VI.B.1): SR relies on Semgrep, Weggli or CodeQL. The authors state that these tools cannot determine whether a vulnerability is reachable, exploitable, or impactful in a specific context, and only cover weakness classes within their rule sets; SR should be understood as fewer statically detectable weaknesses, not a direct measure of real-world security. The authors state that stronger verification using dynamic analysis or fuzzing is valuable future work.
- Classification errors (VI.B.1): The authors state that effectiveness depends on the classifier routing queries to the appropriate categories, but this paper does not directly measure misclassification; quantifying classification errors and their downstream impact on SR is left for future work.
- Internal validity (VI.B.2): The authors state that although models, benchmarks and baselines are matched, results may still be affected by model-specific behavior, prompt sensitivity, and the interaction between security guidance and the code generator; the relationship between security and functional correctness is not consistent across all tasks.
- Model and language scope (VI.B.3): The main experiments focus on 7–16B open-weight code models that can run locally. The authors state that extending the category schema to more languages requires experts to construct the corresponding vulnerability groupings.
- Knowledge base curation (VI.A.2, VI.B.3, VII): The authors state that the current library may not cover some programming domains and thus misses some CWEs; 12 of CyberSecEval's 33 CWEs and 18 of CodeGuard+'s 42 are not in the library. Some categories may be too broad. Future work includes improving the knowledge base, systematically covering more CWEs, trying other groupings, automatically updating as new CWEs appear, and validating on larger proprietary models with dynamic analysis or fuzzing. The authors leave strengthening or splitting the Python cryptography category for future work.
Experimental coverage
- The main code generation experiments are Qwen2.5-Coder-7B, DeepSeek-Coder-V2-16B, CodeLlama-13B; the Discussion additionally reports a small experiment with GPT-5.4-mini on CyberSecEval.
- The benchmarks are CyberSecEval with 1,066 entries across four languages, CodeGuard+ with 103 entries (independent setting), and HumanEval with 164 problems; the poisoning experiments are Scenario I and Scenario II, targeting the functional RACG knowledge base (Table VI).
- The design analysis includes retrieval depth (Figure 3), four classifier/summarizer combinations (Table VII), four knowledge base structures (Table VIII), and BM25, TF-IDF and jina-embeddings-v3 on the same knowledge base (Table IX).
- Security determination uses ICD or CodeQL, and functional determination uses unit tests on CodeGuard+ and HumanEval. The paper does not report the number of repetitions for SR, nor the agreement between human judgment and these static tools.
- The knowledge base languages are C, C++, Python and Java, with 10 categories per language in Table I. VI.A.2 states that 12/33 CWEs of CyberSecEval and 18/42 CWEs of CodeGuard+ are not included.
Summarize the main content of the paper
CAT-RAG consolidates related CWEs into language-related categories and retrieves adaptively, improving the Security Rate of generated code without changing the model.
CAT-RAG is a category-retrieval safety layer added on top of code generation; it does not change model weights.
- Problem: when safety knowledge is injected per individual CWE, a single task query often touches multiple related weaknesses at once, making the prompt longer and dispersing the model's attention; this granularity also does not align with how developers describe requirements by programming task. The functional retrieval library may also be poisoned.
- Approach: build categories for C, C++, Python, Java around shared security concerns, each merging practice points and secure code examples. At inference, an LLM classifier identifies the language and selects a variable number of categories according to query complexity, which are then appended to the prompt. This layer can be used alone or placed after functional example retrieval; summarization is another optional call.
- Comparison results: on CyberSecEval, using the same ReposVul library as CodeGuarder, CAT-RAG's average SR gain across the 12 groups is 23.57% and CodeGuarder's is 12.11%, with 41.71% fewer average total tokens. CodeGuarder is higher on Qwen-Coder's Java and Python, and is below the no-retrieval baseline on CodeLlama's Java and Python.
- Other results: the independent setting averages a gain of 22.39%, with SR positive in all 12 groups. On HumanEval, pass@1 and pass@5 are higher than the no-retrieval baseline for all three code models. Under the two functional-library poisoning settings, the average SR gains relative to the poisoned baseline are 17.97% and 17.86%.
- Authors' conclusion: in security-oriented retrieval augmentation, how knowledge is organized matters at least as much as the knowledge content. The authors list a more complete knowledge base, more languages, and validation with dynamic analysis or fuzzing, especially on larger proprietary models, as future work.