arXiv:2610.33450cs.CROct 2026

Manuscript Offprint

arXiv:2610.33450

Secure and Functional Code Generation with Self-Evaluation

Md Afif Al Mamun, Gias Uddin

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

MD AFIF AL MAMUN, University of Calgary, Canada

GIAS UDDIN, York University, Canada

Large Language Models (LLMs) can generate functionally correct code that remains insecure. Security-focused fine-tuning can be expensive and is not always available, motivating inference-time approaches. Security-oriented prompting and retrieval can reduce vulnerabilities, but may also remove required behavior or apply defenses incompatible with the task. The challenge is to identify relevant security knowledge and use it to improve security without sacrificing functionality. We present SECGENT, an inference-time framework that retrieves weakness context from the Common Weakness Enumeration (CWE) database and applies it to secure code generation. By connecting task specifications to relevant textual CWE records, SECGENT provides task-specific security guidance without relying on retrieved vulnerable or patched code examples. Complementary functional and security tests check the resulting implementation, and their execution feedback guides repairs toward satisfying both objectives. We evaluate SECGENT with four open-source LLMs and Claude Sonnet 5.5 across five programming languages on the CWEval benchmark. It achieves the highest joint functional–security success against four inference-time baselines for all five models. Across the open-weight models, mean functional-security@1 (FS@1) improves by 15.5% over RAG, with gains in both functionality and security, and by 19.8% over the strongest prompt optimizer compiled for each model. On Sonnet, FS@1 reaches 92.1%, outperforming the strongest baseline AutoGen by 4.8%. In a separate comparison, SECGENT outperforms Claude Code with security-focused prompting by over 6% in FS@1. Feedback-guided repair further improves FS@1 by up to 6.7% over generation without feedback, primarily by recovering functionality while checking security.

CCS Concepts: • Security and privacy → Software and application security; Software and application security; • Software and its engineering → Software creation and management; • Computing methodologies → Artificial intelligence; Machine learning.

Additional Key Words and Phrases: Secure code generation, Large language models, Common Weakness Enumeration, Retrieval-augmented generation, Test generation, Program repair

ACM Reference Format:

Md Affi Al Mamun and Gias Uddin. 2026. Secure and Functional Code Generation with Self-Evaluation. 1, 1 (October 2026), 21 pages. https://doi.org/XXXXXXX.XXXXXXX

1 Introduction

Large Language Models (LLMs) can generate code that performs its intended task but remains vulnerable to attack. LLM-based coding tools are increasingly becoming common [37], including GitHub Copilot [15] and assistants based on models such as GPT [1], Claude [7], and Gemini [11]. This gap between functional correctness and security is consequential because passing ordinary tests does not establish that a program is secure (e.g., when handling adversarial inputs) [8, 33, 34, 36]. Security-oriented interventions seek to close this gap, but can introduce another problem by rejecting valid inputs, removing required operations, or applying defenses incompatible with the

Authors' Contact Information: Md Affi Al Mamun, University of Calgary, Calgary, Canada, affi.mamun@ucalgary.ca; Gias Uddin, York University, Toronto, Canada, guddin@yorku.ca.

Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org.

© 2026 Copyright held by the owner/author(s). Publication rights licensed to ACM.

ACM XXXX-XXXX/2026/10-ART

https://doi.org/XXXXXXX.XXXXXXX

Md Afif Al Mamun and Gias Uddin

task [12]. LLM-based secure code generation must therefore address relevant weaknesses without losing the behavior developers require.

Consider a coding task from CWEval, a benchmark that evaluates both functional correctness and security using executable tests [34]. The task asks for a JavaScript function that stores user-provided values in an HTTP response header. Figure 1 shows Qwen3-Coder-30B (Qwen30B)'s implementations. With Direct Prompting, the model stores the value without checking for carriage returns or newlines. The candidate passes the functional oracle, but an attacker-controlled value can inject additional header lines through a CWE-113 response-splitting weakness. All five sampled generations for this task exhibit the same failure. More broadly, 29.2% of functionally correct samples generated with Direct Prompting across our four open-weight models fail CWEval's security oracle. Functional success alone therefore leaves substantial security risk unobserved. Prior works improve security through model adaptation, decoding constraints, and optimized prompts [2, 13, 18, 19, 23, 32]. CodeGuarder [26] and RESCUE [35] retrieve security explanations and code examples to guide generation. In our evaluation across the four open-weight models, providing task-relevant security context, such as CWE records, through Retrieval Augmented Generation (RAG) [22] improves mean security success over direct prompting but reduces functional correctness. This trade-off also appears in CodeGuarder, which retrieves vulnerability explanations and examples of vulnerable and patched code to guide generation. Its functional losses largely offset its security gains in joint functional-security success (Section 5.1). Figure 1 shows this trade-off. RAG checks for the injection characters, but also restricts Accept-Language to a single language tag. This rejects valid lists such as en-US, en; q=0.9, so the candidate passes the security oracle but fails the functional oracle; four out of RAG's five samples fail in this way. Improving security in isolation is therefore insufficient.

However, a key challenge is obtaining accurate weakness context from the programming task itself. We use this term for the textual CWE records retrieved as relevant security knowledge for that task. A task specification describes intended behavior, whereas MITRE's CWE database [27] describes failure mechanisms and their consequences. The header task specification, for example, does not mention carriage returns, newlines, or response splitting. Direct similarity search using the specification can therefore miss the relevant weakness (see Discussion 6.3). Even when a record is retrieved, its applicability must be interpreted against the task's inputs, operations, and required outputs. Selecting relevant weakness context and applying it appropriately are distinct challenges.

We introduce SECGENT, an inference-time framework that retrieves weakness context: the CWE records most relevant to a given task, each describing in code-level terms the input, operation, and consequence that characterize the weakness. Its CWE-derived catalogue is constructed without using any specific benchmark task specifications or solutions. At inference time, Hypothetical Document Embedding (HyDE) query generation [14] expresses plausible weaknesses of the requested operation, and reranking selects the five most relevant records. The coding agent receives this textual weakness context alongside the specification and is instructed to address the security risks while preserving required behavior. Our approach does not provide any vulnerable code or its corresponding patch examples to the coding agent. The same context guides complementary security and functional tests. For example, a security test checks that adversarial input does not trigger an unsafe effect, while a functional test checks that valid input produces the expected output. The testing agent selects a relevant weakness from the retrieved weakness context and turns its attacker-controlled input and observable effect into a security test, while a functional test checks specified behavior. Execution failures guide a bounded repair loop that permits at most a fixed number of repair attempts and retains a proposal only when it improves one generated-test objective without reducing the other. Prior work establishes the usefulness of execution feedback [10, 25, 31, 42];

Task: store user-provided HTTP header values

cwe_113_0_js

Preserve valid values; leave the map unchanged on error. Valid lang: en-US, en; q=0.9.

Direct Promptingconst headerKey = typeToKey[infoType];header[headerKey] = infoContent;return header;RAGconst langRegex = /[^[a-zA-Z]{2,3}(-[a-zA-Z]{2})?$/;if (langRegex.test(infoContent)) { // ... update accepted header ... }SECGENTif (infoContent.includes('\r') || infoContent.includes('\n')) { return header; } updatedHeader[headerKey] = infoContent;
Unchecked assignment.✓ functional ✗securityOverly restrictive validation.✗functional ✓securityTargeted injection check.✓ functional ✓security

Fig. 1. Excerpts for CWEval's JavaScript CWE-113 header task under Qwen30B. Highlighted lines explain the security or functionality failure and SECGENT's targeted check. Ticks and crosses show independent CWEval verdicts. Unrelated code are omitted to save space.

SECGENT focuses on retrieving weakness context for generation and candidate-independent frozen tests, with repair governed by an explicit two-objective retention rule.

In Figure 1, SECGENT rejects carriage returns and newlines while preserving other header content, and passes both CWEval oracles in four of its five samples. CWEval's independent functional and security oracles evaluate all reported outcomes, but their results are not used to guide repairs to prevent oracle leakage. We make three contributions:

  • Task-conditioned weakness context. A retrieval pipeline that connects programming specifications to a textual CWE catalogue through code-level rewriting, HyDE query generation, and reranking. Across all 119 CWEval tasks, recall of ground-truth CWEs among the top five retrieved records is 89.1%89.1\%, compared with 47.1%47.1\% for direct dense retrieval using a task specification as a query directly.

  • Context-guided generation and testing. SECGENT uses the retrieved weakness context to guide security-aware implementation and derive complementary functional and security tests without candidate access. A frozen test suite and strict Pareto retention (i.e., retaining a repair only if it improves one test objective without worsening the other) govern evidence-guided repair under both tested objectives.

  • Evaluation. On CWEval benchmark [34], SECGENT outperforms four inference-time baselines in FS@k for k∈1,2,5k \in 1, 2, 5 across all evaluated open-weight and proprietary LLMs. FS@k measures the probability that at least one of k candidates passes both functional and security checks. Across the open-weight models, mean FS@1 improves by 15.5% over RAG, the strongest baseline on average, and by 19.8% over the best prompt optimizer for each model. With Claude Sonnet 5.5, SECGENT also outperforms Claude Code running on the same model with security-focused prompting by 6.2% in FS@1.

References (18)