WorksComputer Science
SecReason: Vulnerability Detection and In-Stream Self-Repair for LLM Code Generation
Abstract
Large language models (LLMs) may introduce security vulnerabilities into generated code, which can persist into production when verification focuses on functional correctness. Existing defenses act before, during, or after generation, but none inspects the code during generation. Security prompts and retrieved security knowledge act before any code exists, constrained decoding limits token choices but cannot guide repair, and post-hoc repair must regenerate the full response. Reasoning LLMs draft code early in their streamed chain of thought, and in this pre-delivery window the code exists only inside the reasoning stream. We present SecReason, an in-stream defense that monitors this window. Dual-track incremental scanning applies security rules, checking each statement as it is emitted and tracing dataflows across the accumulated code. When a security rule fires, SecReason interrupts generation, inserts an in-stream warning, and resumes decoding, so the model repairs the draft within the same reasoning trace without regenerating the full response. On tasks where unassisted generation introduces vulnerabilities, \system raises the share of runs delivering secure and functionally correct code from below 15% to 72.8%–98.1% on \tool{CWEval} and \tool{SecCodeBench}. \system consumes fewer tokens than post-hoc repair, and when security rules misfire on secure code, it limits the functional regressions from false warnings.
CCS Concepts: • Software and its engineering → Software security engineering; Software testing and debugging; • Computing methodologies → Natural language generation.
Additional Key Words and Phrases: large language models, code generation, vulnerability detection, static analysis, self-repair
Introduction
Developers increasingly delegate implementation tasks to code assistants and coding agents built on large language models (LLMs), but the generated code can introduce security vulnerabilities such as injection and weak cryptography [8, 25, 31]. Because developers primarily verify functionality and rarely screen for security, they tend to trust code that executes correctly [15, 28], so functionally correct but vulnerable code persists in software repositories. In automated environments, agents write and execute code without intermediate human inspection [40, 41, 47, 49], so such code reaches execution undetected.
Existing defenses act before, during, or after generation, but none inspects the code during generation. Security fine-tuning [13], security prompts [33], and retrieved security knowledge [19] act before any code exists, so they cannot verify whether the delivered code is secure or name the flaw in a specific draft. Constrained decoding methods act during generation, enforcing grammar [39], conditioning on execution feedback [16], or blocking completions matching known weakness patterns [35], but none can guide the model to repair its code. Post-generation defenses, such as
Authors’ Contact Information: Ruidong Han, Singapore Management University, Singapore, [email protected]; Zhensu Sun, Singapore Management University, Singapore, [email protected]; Chengyan Ma, Singapore Management University, Singapore, [email protected]; Yuqing Niu, Singapore Management University, Singapore, [email protected]; Zhou Yang, University of Alberta, Edmonton, Canada, [email protected]; Siqi Ma, University of Wollongong, Wollongong, Australia, [email protected]; David Lo, Singapore Management University, Singapore, [email protected]. static scanners [18, 36] and automated program repair [1, 26, 46], inspect code precisely but only after generation completes. Static analyzers raise many false alarms [14, 32], so a checker that inspects every generation often flags code that is in fact secure. Repairing a flagged vulnerability then requires regenerating the full response, which increases token consumption and risks breaking working code, and this cost recurs even when the alarm was false.
Reasoning LLMs [11, 12, 23] make the code inspectable during generation. Before producing a final answer, these models emit an extended chain of thought [42], and the implementation is typically drafted inside this trace, not after it (Figure 1, left). We measure how often the models deliver insecure code, how much of the delivered code the reasoning drafts already contain, and how early these drafts finish. The study covers six open-weight models, which expose complete reasoning streams, and 173 tasks from two security benchmarks, CWEval [27] and SecCodeBench [4]. § 2.1 narrates the example behind the figure, and § 2.2 details the protocol and reports the per-model results.

Figure 1. Unassisted generation (left) delivers flawed code vulnerable to SSRF (CWE-918), whereas SecReason (right) intercepts the flawed check and enables in-stream self-repair before delivery.
Across the six models, 13.2% to 35.6% of functionally valid generations on CWEval and 42.6% to 61.3% on SecCodeBench fail security tests. Security terms do appear in these traces, but among runs whose reasoning mentions them, 5.4% to 61.1% still deliver insecure code.
In these same traces, 52.4% to 99.8% of delivered lines appear verbatim in a fenced code block of the reasoning, and five of the six models exceed 73% on both benchmarks. The best-matching draft closes at 45.2% to 89.1% of the trace, leaving 203 to 6,028 reasoning tokens on average before delivery. The interval between drafting and delivery is therefore a pre-delivery window in which the code that will be delivered already exists.
We build on this observation and introduce in-stream detection, which runs the checker during generation, not after it. The checker scans the draft as it is generated, statement by statement. When it reports a potential vulnerability, a short warning is inserted into the ongoing reasoning. The model then decides how to respond, fixing the draft before the final code if the alarm is real and verifying the flagged code if it is false, so no extra turn is needed. Handling an alarm costs a few reasoning tokens, so false alarms become cheap, not costly.
Applying static analysis inside the reasoning stream is not straightforward. Static analyzers expect complete, syntactically valid files, whereas reasoning streams interleave partial code with natural-language text. An in-stream defense must recognize statements as they complete and translate structured analyzer findings into feedback that the model can act on within the ongoing trace.
To address these challenges (§ 2.3), we present SecReason, an in-stream defense system that intercepts vulnerable code drafts during reasoning and guides the model to repair them before delivery (Figure 1, right). Operating at the inference serving layer without modifying model weights, SecReason parses the streaming reasoning trace incrementally to recognize completed statements. To balance latency against detection depth, it scans a security ruleset on two tracks. A statement-local track checks each completed statement as it is emitted, and a context-dependent track catches dataflows spanning the accumulated code.
We evaluate SecReason on the same 173 tasks in five programming languages. Streaming detection replays the generations of all six models, and in-stream self-repair runs on two locally deployed models over the tasks where unassisted generation introduces vulnerabilities. On these tasks, in-stream self-repair matches or exceeds post-hoc repair in every benchmark and model combination, raising the share of runs delivering secure and functionally correct code from below 15% to 72.8%–98.1% under a corpus-calibrated ruleset while consuming fewer tokens. When security rules misfire on secure code, SecReason also shows smaller functional regressions than post-hoc repair.
This paper makes the following contributions.
An empirical study of six reasoning models on 173 tasks, showing that implementations are drafted early in the reasoning stream, while security-term mentions do not reliably prevent insecure delivery.
SecReason, an in-stream defense at the inference serving layer that recognizes completed statements in the streaming reasoning trace and inserts warnings prompting the model to repair vulnerable drafts before delivery.
An evaluation on CWEval and SecCodeBench showing that in-stream self-repair matches or exceeds post-hoc repair while consuming fewer tokens.
Motivation
Motivating Example
Reasoning models (e.g., the GPT, Qwen, and GLM families) reason [42] by default when generating code, and some (such as GLM-5.3) offer no option to disable it. Figure 1 in the introduction shows this task side by side, unassisted on the left and under SecReason on the right. The left trace is a run of Qwen3.6-35B-A3B. Prompted to build a URL from a trusted domain and a user-supplied subdomain prefix, the model streams its reasoning before delivering the final code. During this trace, the model interleaves natural-language reasoning with drafted code, evaluating edge cases for “empty or invalid” input before writing a preliminary implementation inside a markdown code fence. After the fenced block, the model reviews the draft and concludes that the validation is sufficient (e.g., “This covers empty...”). Finally, the model delivers this drafted code as its final response, unchanged.
However, the delivered code is vulnerable to Server-Side Request Forgery (SSRF, CWE-918 in the Common Weakness Enumeration). Earlier in the same trace, before drafting the implementation, the model had explicitly identified # and ? as characters that render the prefix invalid, but the drafted validation checks only for slashes and empty strings. Because # and ? begin the fragment or query component in URL syntax, they terminate the host. A payload such as evil.com# bypasses the check and directs requests to the untrusted evil.com domain. In this trace, unassisted self-review provides no diagnostic feedback on the drafted validation. Re-reading the draft does not bring back the # and ? cases that the model’s earlier reasoning had identified. The right trace of Figure 1 previews the corresponding trajectory under SecReason, where an in-stream warning inserted at the flawed check is repaired within the same reasoning (§ 3).
Empirical Analysis on Reasoning Models
While the motivating example illustrates that unassisted self-review can fail on an individual task, a single trace cannot answer how often models deliver insecure code, how often their reasoning mentions security, and how early code drafts form. We ask how frequently models leave vulnerabilities in delivered code, how often their reasoning mentions security terms, and how early they draft code in their reasoning traces.
To examine these questions, we evaluate six open-weight models that expose complete reasoning streams, Qwen3.6-35B-A3B [30], Gemma-4-26B-A4B [9], DeepSeek-V4-Flash [6], MiniMax-M3 [20], GLM-5.3-Flash [48], and Kimi-K3 [21]. Closed APIs such as GPT and Gemini are excluded because they return only thought summaries [10, 24].
We evaluate these models on two code generation benchmarks, CWEval [27] and SecCodeBench [4]. We include every task written in Python, JavaScript, Java, C, or C++. This yields 173 tasks in total, 97 from CWEval and 76 from SecCodeBench. To evaluate the delivered code, we execute each benchmark’s functional and security test suites, labeling a generation as insecure if it passes functional verification but fails at least one security test. We scan reasoning traces for the security term stems secur- and vulnerab-. Verbatim line recall denotes the fraction of delivered lines (non-empty, non-comment) that appear verbatim in some fenced block. High values indicate that the final code was already written during reasoning. Draft completion denotes the trace position at which the best-matching fenced block, the block sharing the most delivered lines, closes. Post-draft tokens denote the number of reasoning tokens generated after that position.
Table 1 reports the full per-model results. Three observations follow.
| Qwen | Gemma | DeepSeek | MiniMax | GLM | Kimi | |
| CWEval ( per model) | ||||||
| Insecure delivery (%) | 35.6 | 34.9 | 20.5 | 26.1 | 13.2 | 19.1 |
| Security-term mention among insecure (%) | 22.6 | 16.7 | 66.7 | 26.1 | 16.7 | 23.5 |
| Security-term mention among secure (%) | 12.5 | 33.9 | 78.6 | 33.8 | 44.3 | 28.2 |
| Verbatim line recall (%) | 98.6 | 88.5 | 78.9 | 78.5 | 79.5 | 52.4 |
| Draft completion (% of trace) | 45.2 | 81.2 | 76.2 | 77.5 | 87.5 | 82.0 |
| Post-draft tokens (mean) | 1,472 | 627 | 6,028 | 343 | 217 | 229 |
| SecCodeBench ( per model) | ||||||
| Insecure delivery (%) | 61.0 | 61.3 | 52.4 | 61.1 | 42.6 | 44.3 |
| Security-term mention among insecure (%) | 50.0 | 28.9 | 54.5 | 33.3 | 23.1 | 29.6 |
| Security-term mention among secure (%) | 52.2 | 41.7 | 66.7 | 33.3 | 51.4 | 58.8 |
| Verbatim line recall (%) | 99.8 | 95.2 | 73.5 | 85.3 | 86.8 | 68.8 |
| Draft completion (% of trace) | 51.3 | 67.7 | 76.5 | 83.1 | 89.1 | 84.3 |
| Post-draft tokens (mean) | 1,811 | 708 | 5,147 | 325 | 253 | 203 |
Table 1. Insecure code appears in every model and is drafted early during reasoning.
Models deliver insecure code. On CWEval, between 13.2% and 35.6% of functionally valid generations fail security tests. On SecCodeBench, between 42.6% and 61.3% fail.
Security-term mentions do not ensure secure code. Among insecure generations, 16.7% to 66.7% of reasoning traces on CWEval and 23.1% to 54.5% on SecCodeBench mention security terms. Mention rates among secure generations are equal or higher in 11 of the 12 model-benchmark cells, by up to 29 points. Among generations whose traces do mention security terms, 5.4% to 61.1% still fail security tests. These mention statistics rely on lexicon matching, and we treat them purely as correlational observations.
The delivered code is drafted during reasoning, well before delivery. On both benchmarks, 52.4% to 99.8% of delivered lines appear verbatim inside fenced blocks of the reasoning trace. Five of the six models exceed 73% on both, and the exception, Kimi-K3, still reaches 52.4% and 68.8%. Draft completion ranges from 45.2% to 89.1% of the trace, leaving 203 to 6,028 post-draft tokens on average before delivery.
In automated environments, coding agents write and execute code without intermediate human inspection [40, 41, 47, 49], so any vulnerability in the generated code reaches execution without review. Because vulnerable code often passes the functional tests used in such environments, it crosses the delivery boundary undetected. This boundary is the point at which code is written to disk or executed and thereby leaves the generation loop. Crossing it closes the pre-delivery window.
In standard generation pipelines, post-generation defenses, such as scanners that inspect completed code [29, 34], operate only after the boundary has been crossed.
Security-term mentions do not reliably prevent insecure delivery. Unassisted self-review receives no external feedback, and in the motivating example it left the omission undetected. These findings point to an opportunity to intercept the vulnerability during generation, through in-stream analysis. Because the delivered code is drafted well before delivery, an analyzer can inspect the draft as the trace unfolds and insert warnings into the stream. A warning supplies the feedback that self-review lacks. It names the flaw in the draft while generation is still underway, so the model can repair it within the ongoing reasoning trace, before the code is delivered. The warning is inserted into the ongoing stream, and the task prompt itself remains unchanged.
Practical Challenges of In-Stream Defense
An analyzer built on static analysis fits this role, but applying it to streaming reasoning traces presents three practical challenges.
C1. Triggering Scans on Incomplete Token Streams. Standard static analyzers (such as Semgrep [34] and Bandit [29]) parse complete, syntactically valid code, so triggering analysis at arbitrary token boundaries yields fragments that AST parsers reject. At the other extreme, waiting for a markdown code fence to close delays interception. By then, later statements in the draft may already depend on the flawed statements, and less of the trace remains in which the model can respond to a warning.
C2. Balancing Analysis Latency with Cross-Statement Dataflow Context. Triggering scans on completed statements inside the open code fence avoids both extremes. The analyzer must then decide what to rescan. Rescanning all accumulated code on every newly completed statement introduces cumulative latency that can stall the stream. In contrast, scanning only the new statement in isolation misses cross-statement taint flows, causing dataflow vulnerabilities (such as command or SQL injection) to go undetected.
C3. Feeding Structured Diagnostics Back into Natural-Language Reasoning. Communicating analyzer findings back into the generation loop raises two requirements. First, static analyzers
output structured findings (e.g., rule identifiers and line coordinates), whereas reasoning traces proceed in free-form natural language. Raw findings must therefore be converted into actionable guidance. Second, the intervention must preserve generation continuity so that repair stays within the ongoing trace. Aborting the stream to prompt repair in a new conversational turn discards the partially generated reasoning trace and forces full-response regeneration. Section 3 presents SecReason, designed to address each of these challenges.
Methodology of SecReason
Pre-delivery interception requires reconciling static analysis with streaming generation.
Overview
Figure 2 illustrates the overall architecture of SecReason, which operates as an in-stream monitor situated between the LLM inference engine and downstream clients. As the engine streams response tokens during reasoning, SecReason inspects the stream and processes it through two main stages, streaming detection and in-stream self-repair.

Figure 2. Overview of SecReason. Code drafted in the reasoning stream (left) is scanned on two tracks (right). A finding routes to warning insertion, and generation resumes into the same stream (bottom).
During streaming detection, SecReason parses the code drafts that reasoning models write within code fences (e.g., ```py) as tokens arrive and applies a dual-track scanning strategy. When a rule triggers, SecReason inserts an in-stream warning that prompts the model to repair the draft within the ongoing reasoning trace.
Streaming Detection
SecReason performs rule-based static analysis over the streamed tokens. Tree-sitter re-parses the code draft as tokens arrive [37], and semgrep-core, which covers the five evaluated languages, matches security rules against it [34].
3.2.1 Statement-Unit Extraction. The finest unit SecReason scans is the completed statement. In a token stream a statement’s end is not marked, so SecReason recognizes completion by parsing. The code to parse is the token sequence inside a markdown fence, a line that starts with ``` whose tag (e.g., py for Python) selects the grammar. Each parse round builds an Abstract Syntax Tree (AST) over these tokens, and a statement is complete when it parses cleanly. Partial trailing syntax sits in a localized ERROR node, while every completed statement keeps a valid subtree.
Because completed statements reappear in every parse round, SecReason records already-extracted end positions in a set . On each parse round it walks the AST and visits statement-level nodes such as expression statements and variable declarations. A node that parses without error () and whose end position is not in becomes a new statement unit , and its position is then added to . Figure 3 traces this extraction across three consecutive parse rounds. Round 1 extracts the cleanly parsed import os as . In Round 2, the appended os.system( sits in an ERROR node (the call lacks arguments and a closing parenthesis) and is skipped, as is , whose end position is already in . In Round 3, the completed call os.system(f"ping {host}") parses at an unseen end position and is extracted as .

Figure 3. Statement-unit extraction across three consecutive parse rounds.
Clean parsing does not mean the enclosing construct is finished. The body of a function definition is syntactically complete after a single line, but the model may append further statements to it. Such appends are not missed, since each appended statement completes at an unseen end position and is extracted on a later round. Whether the enclosing definition is finished matters only to rules whose evidence spans statements. The dual-track design below defers exactly these rules to definition-closing boundaries.
Dual-Track Scanning via Rule Partitioning
A scan examines either a single statement or the full code so far. Rules differ in the scope of evidence they need to match, so SecReason partitions the ruleset into two tracks by scope.
Statement-local track (). This track contains rules whose matching evidence resides entirely within a single statement, such as weak cryptographic primitives (hashlib.md5() in CWE-327) and disabled SSL verification (verify=False in CWE-295). SecReason evaluates on each statement unit upon emission.
Context-dependent track (). This track contains the remaining rules, whose matching evidence or scoping context spans statements. Examples include taint rules tracing untrusted inputs into SQL queries (CWE-89) or system commands (CWE-78) and structural constraints such as sensitive operations inside public API routes. SecReason retains code emitted across statements and fences in an accumulation buffer . SecReason evaluates over at three boundaries, the closing of an enclosing function or class definition containing sink identifiers, the closing of a code fence, and the termination of generation. At the first boundary the definition’s variable scopes are complete. The final scan covers unclosed fences and the delivered code.
Figure 4 traces this routing on a streamed example. Statement contains a self-contained vulnerability and triggers an intervention upon emission via . In contrast, detects the cross-statement taint flow from to when evaluating buffer at the first boundary. Checkmarks () denote passed local checks, and dotted lines link context-dependent triggers to their firing positions in the stream.
Figure 4. Dual-track scanning on a streamed example.
When a rule matches in either track, SecReason outputs a structured finding containing the rule identifier, a diagnostic summary naming the CWE category, the offending code snippet, and a remediation guideline.
In-Stream Self-Repair
Upon receiving a finding , SecReason guides the model to revise the code without discarding its ongoing reasoning.
Mid-Stream Interception and Warning Insertion
When a rule triggers, SecReason interrupts token production and retains the ongoing reasoning trace as . From finding , SecReason synthesizes an in-stream warning and inserts it into the ongoing stream. The warning is addressed to the model in the second person. It pairs the rule’s diagnostic summary () and remediation guidance () with the offending code snippet (), and closes with a constraint to eliminate the vulnerability while preserving functionality. When the same rule triggers a second time, the header escalates to state that the issue persists. Listing 1 shows the warning instantiated for a CWE-78 finding.
A security check found a potential OS command injection (CWE-78) issue in your code:
f"last | grep {username}"
Suggested fix: Avoid the shell entirely: pass the command as an argument list with shell=False
(subprocess.run([...], shell=False)); quote any unavoidable fragment with shlex.quote.
Fix it while keeping the functionality.
Listing 1. The in-stream warning , instantiated for a CWE-78 finding. Gray labels mark the slots of finding .
After generation resumes, a rule can fire again, either because the rewritten code still contains the flaw or because a dataflow begins in the pre-warning draft and ends in the newly generated code. To prevent infinite repair loops, SecReason enforces a configurable interruption cap per rule. Once interventions for rule reach , SecReason suppresses further interruptions for that rule and allows generation to continue, while still monitoring for other rule violations.
Resuming Generation
After inserting the warning, SecReason resumes decoding within the active stream, so the model can revise its draft in place. SecReason constructs a continuation request , where is the task prompt, is the generated token sequence prior to interception, and denotes token concatenation. On serving engines with prefix caching, resuming from an exact token prefix reuses previously computed KV caches, requiring the engine to process only the newly appended warning tokens.
After each intervention, SecReason rebuilds the detection state. is re-derived by replaying through statement-unit extraction, so remains a deterministic function of the surviving token sequence. Before the warning is appended, SecReason closes the interrupted fence with a synthetic marker, so its partial code is replayed as well. Replayed fences enter without being scanned, so earlier taint sources stay visible to later scans over the repaired draft. Matches that end inside the replayed region are discarded. The replay therefore never re-triggers the finding that prompted the intervention.
Evaluation
We organize the evaluation around four research questions, following the pipeline from detection to repair.
RQ1 (Detection accuracy). Does incremental in-stream scanning retain the detection accuracy of batch static analysis?
RQ2 (In-stream detection). How reliably, how early, and at what runtime overhead does in-stream detection fire in live reasoning streams?
RQ3 (Self-repair efficacy). How effectively do in-stream warnings guide the model to repair drafted vulnerabilities before delivery, relative to prompt-based and post-generation alternatives?
RQ4 (Robustness to rule false positives). How does SecReason behave when security rules misfire on secure code?
Experimental Setup
Implementation and Environment. We implement SecReason on top of the SGLang framework [50] with incremental Tree-sitter parsers and a semgrep-core backend, natively supporting Python, JavaScript, Java, C, and C++. All experiments are executed on a server equipped with an NVIDIA RTX PRO 5000 and an AMD Ryzen 9 9950X3D CPU, running Ubuntu 24.04.
Benchmarks and Corpora. To evaluate detection accuracy on static code (§ 4.2), we construct the Multi-Language Static Corpus. It comprises 2,878 samples balanced equally between vulnerable code from Purple Llama [3] and benign solutions from Rosetta Code [22] across four languages (Python, JavaScript, Java, and C). The corpus contains both syntactically complete programs and incomplete snippets to mirror the intermediate code states produced during LLM generation. We omit C++ because the official Semgrep registry provides no default security rules for it. To evaluate in-stream detection, self-repair, and robustness, we use 173 tasks from two executable security benchmarks, CWEval [27] (97 tasks) and SecCodeBench [4] (76 tasks), covering five languages with sandboxed functional tests and dynamic exploit payloads.
Large Language Models. For the streaming detection evaluation (§ 4.3), we query the six open-weight models evaluated in § 2.2 through OpenRouter APIs to collect their complete reasoning streams. Because in-stream intervention requires mid-generation control that remote APIs do not support, we locally deploy two representative models on SGLang for the self-repair and robustness experiments (§ 4.4 and § 4.5), Qwen3-6-35B-A3B [30] and Gemma-4-26B-A4B [9].
Compared Methods. We benchmark SecReason against four alternative methods under identical prompts. First, Hardened Prompt is a static baseline whose system prompt tells the model that its code will run in production under strict security requirements, and directs it to re-read its draft and fix any weaknesses before finishing. Second, Post-Hoc Repair scans each completed response. When a rule fires, the model receives the warning and regenerates the entire response, up to three attempts in total, the initial generation plus at most two repairs. Post-Hoc Repair applies the same warning template and ruleset as SecReason with a comparable attempt budget, so the two methods differ mainly in when the warning arrives, after delivery versus mid-stream. Third, INDICT [17] is a critique-repair method that also acts after generation. On each flagged response, it critiques the delivery twice, once as a safety critic and once as a helpfulness critic, and synthesizes both opinions into one repair directive that drives regeneration. It runs under the same ruleset, warning template, and three-attempt budget as Post-Hoc Repair. Fourth, RAG-Guided Prompt adapts Security Course [19] by prepending a CWE knowledge block to the Hardened Prompt. The block is rendered from a knowledge base distilled from the same rule corpus SecReason’s detector uses, with weakness descriptions, mitigations, and secure reference patterns. The block is keyed to each task’s ground-truth CWE, an oracle retrieval that upper-bounds what the query-decomposition retriever of the original system fetches. RAG-Guided Prompt completes in a single pass with no detection, so the comparison with SecReason varies only in where the same security guidance enters, the prompt before generation or the reasoning stream during generation.
RQ1: Detection Accuracy
To answer RQ1, we compare whole-file batch scanning (full) against SecReason (stream) on the Multi-Language Static Corpus using official Semgrep registry rules (425 Python, 252 JavaScript, 132 Java, and 17 C).
P, R, and F1 denote Precision, Recall, and F1 score (%), respectively. Sample counts per split (): Python (456+108 = 564), JavaScript (696 + 706 = 1, 402), Java (252 + 206 = 458), C (282 + 172 = 454).
Table 2 reports the detection results across complete code, incomplete snippets, and the overall corpus across the four languages. On syntactically complete code, SecReason performs on par with batch scanning, with F1 differences within 2.0 points in all four languages. On incomplete snippets, where syntax errors prevent the batch parser from parsing files and discovering vulnerabilities, SecReason analyzes valid subtrees to raise recall by 12.5 to 15.2 percentage points at 95.6% to 100% precision. This advantage on partial code raises the overall F1 of SecReason over batch scanning by +1.5 to +17.4 points under official registry rules. The low absolute F1 on JavaScript and Java stems from limited rule coverage, as the registry rules recall only about 10% of vulnerable samples in these languages under batch scanning and at most 23.5% under SecReason.
| Language | Scan | Complete Code P | Complete Code R | Complete Code F1 | Incomplete Snippets P | Incomplete Snippets R | Incomplete Snippets F1 | Overall Corpus P | Overall Corpus R | Overall Corpus F1 |
| Python | Full | 82.5 | 78.8 | 80.6 | 93.9 | 39.2 | 55.4 | 84.1 | 67.7 | 75.0 |
| Python | Stream | 78.4 | 78.8 | 78.6 | 95.6 | 54.4 | 69.4 | 81.5 | 72.0 | 76.5 |
| JavaScript | Full | 12.2 | 22.2 | 15.7 | 92.1 | 9.1 | 16.5 | 40.4 | 10.3 | 16.4 |
| JavaScript | Stream | 12.0 | 22.2 | 15.6 | 96.2 | 23.7 | 38.0 | 60.2 | 23.5 | 33.8 |
| Java | Full | 58.3 | 24.1 | 34.1 | 100.0 | 8.5 | 15.7 | 82.8 | 10.5 | 18.6 |
| Java | Stream | 50.0 | 24.1 | 32.6 | 100.0 | 21.0 | 34.7 | 87.5 | 21.4 | 34.4 |
| C | Full | 44.4 | 36.4 | 40.0 | 93.9 | 20.7 | 33.9 | 61.5 | 26.0 | 36.5 |
| C | Stream | 44.6 | 37.7 | 40.8 | 96.2 | 34.0 | 50.2 | 67.8 | 35.2 | 46.4 |
Table 2. Detection accuracy across complete code, incomplete snippets, and the overall corpus in the Multi-Language Static Corpus.
RQ2: In-Stream Detection
4.3.1 Rule Coverage and Synthesis. To answer RQ2, we examine rule coverage on delivered code offline to establish the ruleset under which streams are monitored. Across the six models, the 173 tasks produce 888 functionally valid generations, of which 324 contain vulnerabilities across 20 CWE categories. Benchmark execution verdicts provide the ground truth. The official Semgrep registry rules cover only 13 of the 20 categories at 59.8% precision, 36.7% recall, and a 45.5% F1 score, so most insecure generations go undetected. We therefore calibrate the ruleset with an LLM agent built on GLM-5.3. The synthesis corpus is the unassisted generations of the two locally deployed models over the full task pool. The other four models’ generations are held out from synthesis. The corpus-calibrated rules cover all 20 categories at 98.2% precision, 99.7% recall, and a 98.9% F1 score over all 888 generations (Table 3).
| Ruleset | CWEs | Precision | Recall | F1 |
| Official registry rules | 13/20 | 59.8 | 36.7 | 45.5 |
| Corpus-calibrated rules | 20/20 | 98.2 | 99.7 | 98.9 |
Table 3. Rule coverage of off-the-shelf and corpus-calibrated rulesets on functionally valid generations.
A task-level split probes how far the rules generalize beyond the synthesis corpus, since the synthesis corpus and the replay cohort draw on the same 173 tasks. Synthesizing rules on a random half of the tasks and replaying the same cohort yields 97.0% recall on the synthesis half but only 7.0% on the held-out half, indicating that the synthesized rules detect the corpus they were calibrated on, not general vulnerability patterns.
4.3.2 Detection Rate and Lead Time. We replay all 173 collected generations per model through SecReason without intervention under the corpus-calibrated ruleset and compute the detection statistics over the 888 functionally valid streams, asking whether detection inside the live stream attains the rules’ offline recall (Table 3) and how early it fires. For each insecure generation, we measure lead time as the percentage of the stream still remaining (and the corresponding token distance) when the first finding fires. For each secure generation, we record whether any finding fires inside the reasoning trace. Table 4 reports these metrics.
| Metric | Qwena | Gemmab | DeepSeekc | MiniMaxd | GLMe | Kimif |
| Insecure Streams () | ||||||
| Total insecure streams | 67 | 68 | 51 | 56 | 38 | 44 |
| Detected in-stream | 67 | 68 | 50 | 56 | 38 | 44 |
| Median lead time (% (tok)) | 82 (2433) | 75 (1599) | 69 (4274) | 62 (682) | 61 (860) | 54 (372) |
| Secure Streams () | ||||||
| Total secure streams | 79 | 80 | 100 | 86 | 114 | 105 |
| In-reasoning findings | 8 | 2 | 35 | 6 | 11 | 8 |
| ↳ Genuine draft vulnerabilities | 5 | 2 | 25 | 4 | 5 | 4 |
| ↳ False positives | 3 | 0 | 10 | 2 | 6 | 4 |
Table 4. In-stream vulnerability detection performance on live reasoning streams.
aQwen3.6-35B-A3B, bGemma-4-26B-A4B, cDeepSeek-V4-Flash, dMiniMax-M3, eGLM-5.3-Flash, fKimi-K3.
SecReason flagged 323 of the 324 insecure generations (99.7%, matching the offline recall), 299 inside the reasoning trace and 24 only while writing the final response. Detection is also early, a median of 54% to 82% of the stream still remaining at the first finding, computed over all flagged generations. The single missed insecure generation stems from insufficient pattern coverage in the calibrated rules. A manual audit of the 70 in-reasoning findings on secure generations produces two observations. First, reasoning models already repair some vulnerabilities during generation without intervention. 45 of the 70 findings fired on intermediate drafts that were genuinely vulnerable if run as-is and were repaired in later reasoning steps. Second, the remaining 25 findings were false positives, where rule patterns misfired on partial code across separate draft fences.
Runtime Overhead
We track the cumulative scan time and number of scans of the detection backend over every replayed generation, including broken or uncompilable deliveries excluded from the detection metrics above. In continuous serving the monitor inspects every stream. The monitoring load, the ratio of cumulative scan time to total generation latency (), averages 0.9% across models and never exceeds 3.2% (Table 5).
| Model | TPS (tok/s) | Load (%) | Scans per gen. |
| Qwen3.6-35B-A3B | 98 | 0.3 | 107 |
| Gemma-4-26B-A4B | 65 | 0.1 | 73 |
| DeepSeek-V4-Flash | 123 | 3.2 | 196 |
| MiniMax-M3 | 111 | 0.7 | 58 |
| GLM-5.3-Flash | 60 | 0.8 | 68 |
| Kimi-K3 | 36 | 0.2 | 42 |
Table 5. Runtime monitoring overhead on live reasoning streams. Monitoring load is cumulative scan time over total generation latency () across all replayed generations per model.
Scans are frequent, 42 to 196 per generation on average, but each scan is short. Even on the fastest model, at 123 tokens per second, a single scan costs on average the generation time of a few tokens, so even fully serialized scanning would add at most 3.2% to generation time.
RQ3: Self-Repair Efficacy
Unless stated otherwise, the self-repair and robustness experiments run under a corpus-calibrated ruleset, with SecReason using an interruption cap of per rule. The ruleset is synthesized by an LLM agent from the unassisted generations of the two locally deployed models while holding out the other four models (Section 4.3.1 details the protocol). The calibrated rules cover all 20 CWE categories among the insecure generations at 98.2% precision and 99.7% recall over all 888 valid generations, so the evaluations below are not limited by rule coverage.
Because repair can only be measured on tasks where the models actually introduce vulnerabilities, we screen all 173 tasks with five repetitions of unassisted generation (RAW) per model and retain tasks with at least one Insecure & Func. run. Tasks whose five runs all fail functional verification provide no working baseline and are excluded as well. After screening, 78 tasks remain for Qwen and 75 for Gemma. The excluded tasks contribute no insecure RAW deliveries by construction.
Delivered code is evaluated against both functional and security test suites. Each run is categorized into one of three exclusive outcomes. Secure & Func. passes both tests, Insecure & Func. passes functional tests but fails security tests, and Func. Failure fails compilation, execution, or functional assertions. Within Secure & Func., we distinguish runs that were safe in their initial generation (Initially Secure) from those successfully corrected through self-repair (Repaired).
In-Stream Self-Repair
Without guidance (RAW), 79.0% to 92.3% of runs deliver insecure code, with fewer than 15% achieving Secure & Func. (Table 6). SecReason raises Secure & Func. deliveries to between 72.8% and 98.1%, while suppressing Insecure & Func. completions to at most 3.1%. Within these deliveries, Repaired accounts for 67.2% to 93.5% of runs, whereas at most 12.8% were safe on their initial attempt (Initially Secure).
| Metric | CWEval | SecCodeBench | ||||||||||
| RAW | Hard. | Post. | IND. | RAG | SecReason | RAW | Hard. | Post. | IND. | RAG | SecReason | |
| Qwen3.6-35B-A3B (CWEval: 39 Prompts × 5 Runs; SecCodeBench: 39 Prompts × 5 Runs) | ||||||||||||
| Secure & Func. (%) | 14.4 | 66.2 | 84.6 | 79.5 | 87.7 | 88.2 | 10.8 | 57.4 | 67.2 | 63.1 | 64.6 | 72.8 |
| ⊲ Initially Secure (%) | 14.4 | 66.2 | 17.4 | 16.9 | 87.7 | 12.8 | 10.8 | 57.4 | 9.2 | 9.7 | 64.6 | 5.6 |
| ⊲ Repaired (%) | — | — | 67.2 | 62.6 | — | 75.4 | — | — | 57.9 | 53.3 | — | 67.2 |
| Insecure & Func. (%) | 79.0 | 22.6 | 1.5 | 2.1 | 0.0 | 1.0 | 80.0 | 18.5 | 4.6 | 3.6 | 8.7 | 3.1 |
| Func. Failure (%) | 6.7 | 11.3 | 13.8 | 18.5 | 12.3 | 10.8 | 9.2 | 24.1 | 28.2 | 33.3 | 26.7 | 24.1 |
| Mean Repairs | — | — | 0.84 | 0.87 | — | 0.98 | — | — | 1.07 | 1.11 | — | 1.19 |
| Mean Tokens | 3,868 | 5,144 | 8,222 | 13,218 | 4,965 | 4,381 | 5,771 | 5,704 | 15,491 | 16,114 | 5,385 | 6,361 |
| Gemma-4-26B-A4B (CWEval: 31 Prompts × 5 Runs; SecCodeBench: 44 Prompts × 5 Runs) | ||||||||||||
| Secure & Func. (%) | 4.5 | 63.9 | 96.1 | 94.8 | 91.0 | 98.1 | 8.6 | 55.5 | 77.3 | 71.8 | 67.7 | 81.4 |
| ⊲ Initially Secure (%) | 4.5 | 63.9 | 4.5 | 3.9 | 91.0 | 4.5 | 8.6 | 55.5 | 5.0 | 7.3 | 67.7 | 3.2 |
| ⊲ Repaired (%) | — | — | 91.6 | 91.0 | — | 93.5 | — | — | 72.3 | 64.5 | — | 78.2 |
| Insecure & Func. (%) | 92.3 | 29.7 | 0.6 | 0.0 | 0.0 | 0.0 | 89.1 | 27.7 | 0.9 | 2.7 | 8.6 | 0.9 |
| Func. Failure (%) | 3.2 | 6.5 | 3.2 | 5.2 | 9.0 | 1.9 | 2.3 | 16.8 | 21.8 | 25.5 | 23.6 | 17.7 |
| Mean Repairs | — | — | 1.03 | 1.04 | — | 1.08 | — | — | 1.08 | 1.05 | — | 1.18 |
| Mean Tokens | 3,556 | 5,372 | 7,414 | 10,928 | 4,952 | 4,569 | 3,118 | 5,464 | 7,259 | 10,765 | 5,457 | 4,981 |
Table 6. End-to-end self-repair performance of SecReason against baselines and deployable alternatives.
Hard.: Hardened Prompt; Post.: Post-Hoc Repair; IND.: INDICT; RAG: RAG-Guided Prompt.
Self-repair may introduce functional regressions. For SecReason, Func. Failure rates remain low in CWEval (), but rise to 17.7% on Gemma and 24.1% on Qwen in SecCodeBench, primarily because models call out-of-task or version-incompatible APIs during repair, which causes compilation failures. SecReason averages 0.98 to 1.19 repairs per run, which increases mean token consumption by 10% to 60% over RAW generation.
Comparison with Alternatives
In every cell of Table 6, SecReason reaches the highest Secure & Func. rate among the compared methods. The closest competitor is Post-Hoc Repair, which delivers the same warnings after generation, not during it. It falls at most six points below SecReason. It consumes the tokens per run of SecReason, and in SecCodeBench its functional failure rate also exceeds SecReason’s on both models. SecReason instead resumes from the retained prefix within the same reasoning trace.
Hardened Prompt improves over the RAW baseline, but up to 29.7% of its runs remain Insecure & Func., and its Secure & Func. rate never exceeds 66.2%. A manual audit of all 187 insecure Hardened Prompt runs finds that in 72% of them the model identifies the potential vulnerability in the trace but still delivers insecure code. It either declines the mitigation outright, on the grounds that the prompt did not request it or that an external layer is responsible, or targets the correct vulnerability class but incompletely, such as an SSRF check that filters private IP addresses while leaving automatic redirects enabled. In the remaining 28%, the self-review addresses unrelated risks and the vulnerability is missed entirely.
INDICT falls below Post-Hoc Repair in every cell of Table 6 at the highest token cost in the table, up to 16,114 mean tokens per run. Its Func. Failure rate exceeds Post-Hoc Repair’s in every cell, up to 33.3% on Qwen in SecCodeBench against 28.2%.
RAG-Guided Prompt improves over Hardened Prompt in every benchmark cell, so corpus-distilled knowledge does help once it reaches the prompt. On CWEval the knowledge block removes Insecure & Func. deliveries entirely at a cost of up to 12.3% Func. Failure, while on SecCodeBench insecurity persists on both models and functional failure climbs to a level comparable to Post-Hoc Repair’s. Prompt-carried knowledge is never checked against the delivered code, whereas an in-stream warning names the flaw in the drafted code and guides the repair before delivery.
Ablation Studies
To separate the intervention mechanism from rule coverage, we re-run SecReason with the official registry rules (Table 3) on the same screened tasks, holding the warning template and fixed. Pooled over both benchmarks, SecReason delivers Secure & Func. code in 27.7% of runs on Qwen and 23.2% on Gemma under these rules, up from 12.6% and 6.9% under RAW and far below the calibrated ruleset’s 80.5% and 88.3%. Across tasks, 8 on Qwen and 6 on Gemma turn from never secure under RAW to always secure under the official rules, and no task turns the other way (exact McNemar test, and ).
The gap to the calibrated ruleset traces to rule coverage, not the mechanism. Most insecure deliveries never trigger a warning, 180 of 222 on Qwen and 212 of 239 on Gemma, and the warnings that do fire still interrupt generation, raising the Func. Failure rate above RAW to 15.4% and 13.1%. Across the two rulesets, the secure-delivery share tracks the ruleset’s recall.
Table 7 ablates three further design choices of SecReason, holding the tasks, ruleset, and outcome definitions fixed. Reducing the cap to lowers the Secure & Func. rate on both models. Raising the cap to brings no benefit. The rate does not change significantly on Qwen and falls on Gemma, while Gemma’s mean tokens rise. The default cap thus sits between a budget too small to finish repairs and one that only adds interruption cost. The rollback prefix policy trims the stream to the last fence boundary before warning insertion. It shows no significant difference from SecReason on Qwen but falls below on Gemma, with higher functional failure, so keeping the drafted code in context supports in-place repair better than evicting it. Dropping the remediation guidance line from the warning, while keeping the vulnerability type and the matched code, produces the largest degradation. The rate falls by 20.2 points on Qwen and 25.9 on Gemma, and insecure deliveries rise.
| Design Variant | Qwen3.6-35B-A3B | Gemma-4-26B-A4B | ||||
| Sec. & Func. | Fail | Tokens | Sec. & Func. | Fail | Tokens | |
| SecReason (default, ) | 80.5 | 17.4 | 5,371 | 88.3 | 11.2 | 4,811 |
| Cap | 73.6* | 23.3 | 5,165 | 77.3* | 22.4 | 6,726 |
| Cap | 75.4 | 21.5 | 5,130 | 79.7* | 19.2 | 7,042 |
| Rollback prefix | 77.2 | 21.0 | 5,562 | 79.7* | 20.3 | 7,609 |
| No remediation line | 60.3* | 21.8 | 6,006 | 62.4* | 25.1 | 7,516 |
marks Sec. & Func. cells significant against the SecReason row (two-sided Wilcoxon signed-rank on per-task rates, ). Unmarked cells are not significant. Rates and functional failures are shown in %.
Statistical Significance on Main Self-Repair Results (Table 6). Two-sided Wilcoxon signed-rank tests on per-task Secure & Func. rates over the five repetitions place SecReason above RAW, Hardened, and INDICT on both models (all ), above Post-Hoc on Qwen () but not on Gemma (), and above RAG on Gemma () but not on Qwen (). On per-task mean tokens, SecReason is below Post-Hoc on both models ().
Failure Analysis
We manually audited all SecReason runs that did not reach Secure & Func. Only 10 runs remain insecure, while 110 fail functionally.
Insecure Runs (). Three of the ten stem from detection misses. In two, the vulnerable construct matches no active rule. In one, an unbalanced code fence in the reasoning prefix suppressed the matches that fire on the delivered code in offline replay. These misses do not contradict the detection rate reported in § 4.3, which is measured on streams generated without intervention. Code rewritten after a warning can contain constructs that the calibrated rules, synthesized from unassisted generations, do not cover. The remaining seven go unresolved. In five, the model follows the recommended hardening but implements it incompletely or incorrectly. One still triggers the rule after reaching the interruption cap (). In one, the model delivers secure code that blocks the malicious request by raising an exception, which the benchmark security test misjudges as a failure.
Functional Failures (). Most (67 runs, 61%) fail to compile. Of these, 58 call APIs missing from the available library versions or with unsupported method signatures (47 on SecCodeBench Java tasks), and 9 contain syntax or type errors in the model’s own code. Another 31 runs (28%) compile successfully but fail functional tests because the hardened code is defective, either logic bugs or overly aggressive validation that rejects legitimate inputs required by the functional tests. The remaining 12 runs (11%) hit the token limit during reasoning and never produce the final response.
Warning placement also correlates with repair outcomes. In 228 of the 765 SecReason runs (29.8%), at least one in-stream warning landed inside an unclosed code fence in the reasoning draft. These runs reached Secure & Func. in 72.4% of cases versus 89.4% when no warning landed inside a fence, with a higher functional failure rate (26.3% versus 9.3%) and the same insecure rate (1.3%). The cost of a warning inside a fence is therefore functional, not a security regression.
RQ4: Robustness to Rule False Positives
Static security rules may raise false positives in deployment. To answer RQ4, we isolate false-positive handling from genuine vulnerability remediation by sampling fifteen vulnerability-free tasks and constructing weakened rules in two false-positive settings. (1) Essential FP matches a construct that no correct solution omits (e.g., any hashlib call in a hashing task). (2) Incidental FP matches a construct that has a semantically equivalent alternative (e.g., replacing malloc(n) with calloc(n, 1)). For each task, we execute five independent runs of Post-Hoc Repair, INDICT, and SecReason under each setting and model, the only methods that act on rule warnings. Hardened Prompt and RAG-Guided Prompt run no detection, so false positives cannot reach them. The fifteen tasks are sampled from CWEval and SecCodeBench, three per language (C, C++, Java, JavaScript, and Python), disjoint from the self-repair task pool. We rank the pool of tasks whose RAW runs are all secure on both models in a fixed random order per language and take the top three, skipping three candidates whose synthesized rules never fire. Table 8 lists the fifteen sampled tasks and their weakened rules.
| Task | Original Target | Essential Match | Incidental Match |
| C: cwe_327_0 | Weak Cryptography (CWE-327) | OpenSSL digest calls | malloc() allocation |
| C: cwe_787_2 | Out-of-Bounds Write (CWE-787) | str[k]=’\0’ write | str == NULL check |
| C: cwe_119_0 | Buffer Overflow (CWE-119) | strncpy() call | (size_t) cast |
| C++: cwe_020_0 | Open Redirect (CWE-601) | .find() / .rfind() calls | size_t type usage |
| C++: BufOverflowStrcpy | Buffer Overflow (CWE-120) | strncpy() call | DJB2 shift form |
| C++: cwe_918_0 | SSRF (CWE-918) | "https://" concatenation | .empty() check |
| Java: MyBatisOrderBy | SQL Injection (CWE-89) | .getUsersByOrder() | getAllUsers() delegation |
| Java: JDBCExecuteUpd. | SQL Injection (CWE-89) | .executeUpdate() | 3-arg getConnection() |
| Java: PathTraversalWrite | Path Traversal (CWE-22) | .resolve() call | createDirectories() |
| JS: cwe_020_0 | Open Redirect (CWE-601) | return target statement | https://${domain} literal |
| JS: cwe_078_0 | OS Command Injection (CWE-78) | ’-l’ string literal | require('child_process') |
| JS: cwe_327_2 | Weak Cryptography (CWE-327) | createCipheriv() call | randomBytes() call |
| Py: cwe_327_0 | Weak Cryptography (CWE-327) | Any hashlib call | .encode('utf-8') call |
| Py: cwe_377_0 | Insecure Temp File (CWE-377) | NamedTemporaryFile() call | .write(results) call |
| Py: SSTIJinja2Template | Template Injection (CWE-1336) | .render() call | jinja2 import form |
Table 8. The fifteen sampled tasks and their weakened rules for false-positive evaluation.
At baseline (No FP), functional failure is rare in every cell (Table 9). False positives impose functional regressions and token overhead on Post-Hoc Repair. Relative to its own baseline, its functional failure rate rises by 5.3 to 9.3 points on Qwen and 5.3 to 10.7 on Gemma, and its median token consumption grows to 2.8× to 4.4×. INDICT’s functional failure stays above Post-Hoc Repair’s on Qwen under both settings and at or below it on Gemma. INDICT is also the most expensive method under false positives on both models, at 1.4× to 1.5× the consumption of Post-Hoc Repair. False positives affect SecReason least. Its functional failure rate rises by at most 4.0 points, less than half of Post-Hoc Repair’s worst increase on the same model, while its median token consumption stays between 0.9× and 1.6× its baseline. Insecure delivery remains negligible throughout.
| Setting | Qwen3.6-35B-A3B Post-Hoc | Qwen3.6-35B-A3B INDICT | Qwen3.6-35B-A3B SecReason | Gemma-4-26B-A4B Post-Hoc | Gemma-4-26B-A4B INDICT | Gemma-4-26B-A4B SecReason |
| Functional Failure, (%) | ||||||
| Baseline (No FP) | 4 (5.3%) | 5 (6.7%) | 2 (2.7%) | 0 (0.0%) | 0 (0.0%) | 1 (1.3%) |
| Incidental FP | 8 (10.7%) | 14 (18.7%) | 5 (6.7%) | 4 (5.3%) | 0 (0.0%) | 4 (5.3%) |
| Essential FP | 11 (14.7%) | 13 (17.3%) | 2 (2.7%) | 8 (10.7%) | 5 (6.7%) | 4 (5.3%) |
| Median Tokens | ||||||
| Baseline (No FP) | 3,763 | 3,909 | 3,638 | 2,998 | 3,318 | 3,088 |
| Incidental FP | 10,633 | 16,056 | 3,383 | 13,049 | 18,282 | 4,849 |
| Essential FP | 10,507 | 15,319 | 3,452 | 11,203 | 17,125 | 4,218 |
Table 9. Robustness to rule false positives across the two weakened-rule settings ( runs per cell).
Model responses to false positives. When SecReason intercepts generation mid-stream, the warning enters the active reasoning context alongside the preceding reasoning trace and drafted code prefix. The model can thus compare the finding with its ongoing plan. Post-warning traces fall into three patterns across the 93 triggered runs of the five audited tasks, the top-ranked candidate of each language. In 45% of them the model explicitly refutes the warning as spurious. In 38% it accepts the warning but verifies the suggested fix against the ongoing plan before acting. In 17% it resumes its reasoning without addressing it. For Post-Hoc Repair, the warning arrives as a new instruction (“A security check found an issue in your code … Fix it”). In 75% of the 92 fired rounds the model accepts the warning (53% from the outset, 22% before questioning it mid-reasoning) and treats it as an instruction to satisfy, and attempts to eliminate benign constructs. These attempts alter surrounding logic during full response regeneration and cause compilation errors and runtime failures.
Threats to Validity
Our evaluation covers six models and 173 tasks in five languages. The following threats to validity bound the interpretation of our findings.
Qualitative evidence. Several qualitative analyses (e.g., classifying defense failures) rely on manual inspection. Interpreting reasoning traces is further subject to chain-of-thought unfaithfulness [38], which leaves the executable primary metrics unaffected.
Rule calibration. The corpus-calibrated ruleset is synthesized and evaluated on the same task pool. Model-level overfitting is bounded, since the four remote models are held out from synthesis. Detection on their insecure generations remains at 99.5%, against perfect detection for the two locally deployed models (Table 4). Task-level overfitting is not bounded, since the synthesis corpus and the evaluation streams draw on the same 173 tasks. A task-level split confirms that the rules recall their calibration corpus far better than held-out tasks, so the ruleset is corpus-specific rather than a transferable vulnerability detector (Section 4.3.1). The intervention results therefore measure the mechanism under near-ideal rule coverage.
Model coverage. In-stream interception requires raw reasoning tokens, excluding serving APIs that withhold them. The intervention experiments run on only two of the six models, leaving self-repair efficacy on the remaining four untested. Detection is evaluated on all six models (Table 4), so the gap is confined to the intervention stage.
Task and code scope. The tasks cover unit-level generation, leaving repository-scale development and multi-step agentic pipelines untested. Extraction anchors on markdown code fences, so code drafted outside them is not analyzed.
Baselines. The evaluated alternatives are prompt hardening and post-generation repair. Decoding-time defenses such as vulnerability-constrained decoding [35] are not compared empirically, since they block completions that match known weakness patterns and cannot guide repair. A stacked comparison with such defenses is left to future work.
Execution oracles. Pre-built test suites serve as execution oracles and may misclassify defensive behaviors (e.g., unhandled security exceptions). All methods run against the same suites, so such discrepancies apply equally across comparisons.
Related Work
Table 10 positions SecReason relative to related approaches in generation-time control, vulnerability detection, and program repair.
Table 10. Positioning of SecReason relative to related generation-time, detection, and repair paradigms.
✓ Yes; ✗ No; ± Partial; – Not Applicable.
Vulnerability Detection for LLM-Generated Code. Prior defenses during generation primarily enforce syntactic validity via token masking on formal grammars [39, 43] or condition lines on execution feedback [16], monitor reasoning traces for alignment risks [2], or suppress jailbreak continuations at decoding time [45]. However, these mechanisms rely on local token-level constraints, execution-state consistency, or pure text matching, leaving semantic security vulnerabilities (e.g., taint-style injections) that span multiple statements unexamined. Conversely, post-generation checkers such as GPTScan [36] and IRIS [18] analyze code logic with static rules or LLMs. While capable of semantic analysis, they operate only after code generation completes, decoupling detection from the model’s internal generation process.
Feedback-Driven Code Repair and Prompt Defenses. Feedback-driven repair refines LLM-generated code via external execution signals or compiler errors [5]. For security remediation, existing approaches fine-tune specialized repair models on historical vulnerability commits [7], edit lines zero-shot [44], or feed static analysis alarms back into the LLM for patching [1]. Similarly, dual-critique frameworks like INDICT [17] synthesize safety and helpfulness critiques into multi-turn revisions. However, such multi-turn loops incur high token overhead from regenerating entire responses, and false static alarms can rewrite correct code (§ 4.5 quantifies both costs). Beyond these repair loops, prompt defenses such as Security Course [19] prepend retrieved vulnerability fixes to the prompt before generation begins, but cannot verify the delivered code. We adapt these representative paradigms as baselines in § 4.4.
Conclusion
This paper presents SecReason, an in-stream defense system that monitors reasoning streams to detect vulnerable code drafts and guides the model to repair them before delivery. Evaluations on CWEval and SecCodeBench show that, on the tasks where unassisted generation introduces vulnerabilities, SecReason raises the share of secure and functionally correct code from below 15% to 72.8%–98.1% under a corpus-calibrated ruleset. Repairing within the same reasoning trace costs fewer tokens and leaves smaller functional regressions from rule false positives than post-hoc repair.
References
- [1]Kamel Alrashedy, Abdullah Aljasser, Pradyumna Tambwekar, and Matthew Gombolay. 2025. Leveraging Static Analysis for Feedback-Driven Security Patching in LLM-Generated Code. Journal of Cybersecurity and Privacy 5, 4 (2025), 110.DOI
- [2]Bowen Baker, Joost Huizinga, Leo Gao, et al. 2025. Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation. arXiv preprint arXiv:2503.11926 (2025).arxiv.org/abs/2503.11926
- [3]Manish Bhatt, Sahana Chennabasappa, Cyrus Nikolaidis, Shengye Wan, Ivan Evtimov, Dominik Gabi, Daniel Song, Faizan Ahmad, Cornelius Aschermann, Lorenzo Fontana, Sasha Frolov, Ravi Prakash Giri, Dhaval Kapil, Yiannis Kozyrakis, David LeBlanc, James Milazzo, Aleksandar Straumann, Gabriel Synnaeve, Varun Vontimitta, Spencer Whitman, and Joshua Saxe. 2023. Purple Llama CyberSecEval: A Secure Coding Benchmark for Language Models. arXiv preprint arXiv:2312.04724 (2023).arxiv.org/abs/2312.04724
- [4]Longfei Chen, Ji Zhao, Lanxiao Cui, Tong Su, Xingbo Pan, Ziyang Li, Yongxing Wu, Qijiang Cao, Qiyao Cai, Jing Zhang, Yuandong Ni, Junyao He, Zeyu Zhang, Chao Ge, Xuhui Lu, Zeyu Gao, Yuxin Cui, Weisen Chen, Yuxuan Peng, Shengping Wang, Qi Li, Yukai Huang, Yukun Liu, Tuo Zhou, Terry Yue Zhuo, Junyang Lin, and Chao Zhang. 2026. SecCodeBench-V2 Technical Report. arXiv preprint arXiv:2602.15485 (2026).arxiv.org/abs/2602.15485
- [5]Xinyun Chen, Maxwell Lin, Nathanael Schäli, and Denny Zhou. 2024. Teaching Large Language Models to Self-Debug. In International Conference on Learning Representations (ICLR).
- [6]DeepSeek AI. 2026. DeepSeek-V4-Flash. https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash. Accessed 2026-09-24.
- [7]Michael Fu, Chakkrit Tantithamthavorn, Trung Le, Van Nguyen, and Dinh Phung. 2022. VulRepair: A T5-Based Automated Software Vulnerability Repair. In Proceedings of the 30th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering (ESEC/FSE), 935–947.DOI
- [8]Yujia Fu, Peng Liang, Amjed Tahir, Zengyang Li, Mojtaba Shahin, Jiaxin Yu, and Jinfju Chen. 2025. Security Weaknesses of Copilot-Generated Code in GitHub Projects: An Empirical Study. ACM Transactions on Software Engineering and Methodology 34, 8 (2025), 2181–21834.
- [9]Gemma Team. 2026. Gemma 4 Technical Report. arXiv:2607.02770.arxiv.org/abs/2607.02770
- [10]Google. 2026. Gemini Thinking. https://ai.google.dev/gemini-api/docs/thinking. Gemini API documentation. Accessed 2026-09-18.
- [11]Google DeepMind. 2025. Gemini 3 Pro Model Card. https://deepmind.google/models/model-cards/gemini-3-pro/. Accessed 2026-09-01.
- [12]Daya Guo, Dejian Yang, Haowei Zhang, Junxiao Song, et al. 2025. DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning. Nature 645, 8081 (2025), 633–638.DOI
- [13]Jingxuan He, Mark Vero, Gabriela Krasnopolska, and Martin Vechev. 2024. Instruction Tuning for Secure Code Generation. In International Conference on Machine Learning (ICML), Vol. 235. 18043–18062.arxiv.org/abs/2402.09497
- [14]Brittany Johnson, Yoonki Song, Emerson Murphy-Hill, and Robert Bowdidge. 2013. Why Don’t Software Developers Use Static Analysis Tools to Find Bugs?. In Proceedings of the 35th International Conference on Software Engineering (ICSE). 672–681.
- [15]Hamza Khalid, Ronald E. Thompson III, Alejandra Sabater, Perucy Mussiba, Kelsey R. Fulton, and Daniel Votpika. 2027. (Don’t) Trust, but (Don’t) Verify: Developers’ Attention to Security in AI-Generated Code. In Proceedings of the IEEE Symposium on Security and Privacy (S&P). To appear. arXiv:2609.21020.arxiv.org/abs/2609.21020
- [16]Boaz Lavon, Shahar Katz, and Lior Wolf. 2025. Execution Guided Line-by-Line Code Generation. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 38. 163877–163902.arxiv.org/abs/2506.10948
- [17]Hunge Le, Yingbo Zhou, Caiming Xiong, Silvio Savarese, and Doyen Sahoo. 2024. INDICT: Code Generation with Internal Dialogues of Critiques for Both Security and Helpfulness. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 37.
- [18]Ziyang Li, Saikat Dutta, and Mayur Naik. 2025. IRIS: LLM-Assisted Static Analysis for Detecting Security Vulnerabilities. In International Conference on Learning Representations (ICLR).arxiv.org/abs/2405.17238
- [19]Bo Lin, Shangwen Wang, Yihao Qin, Liqian Chen, and Xiaoguang Mao. 2025. Give LLMs a Security Course: Securing Retrieval-Augmented Code Generation via Knowledge Injection. In Proceedings of the 2025 ACM SIGSAC Conference on Computer and Communications Security (CCS). ACM, 3356–3370. doi:10.1145/3719027.3765049DOI
- [20]MiniMaxAI. 2026. MiniMax-M3. https://huggingface.co/MiniMaxAI/MiniMax-M3. Accessed 2026-09-24.
- [21]Moonshot AI. 2026. Kimi-K3. https://huggingface.co/moonshotai/Kimi-K3. Accessed 2026-09-24.
- [22]Sebastian Nanz and Carlo A. Furia. 2015. A Comparative Study of Programming Languages in Rosetta Code. In Proceedings of the 37th IEEE/ACM International Conference on Software Engineering (ICSE). 778–788.
- [23]OpenAI. 2024. OpenAI o1 System Card. arXiv preprint arXiv:2412.16720 (2024).
- [24]OpenAI. 2026. OpenAI Reasoning Models. https://developers.openai.com/api/docs/guides/reasoning. OpenAI API documentation. Accessed 2026-09-18.
- [25]Hammond Pearce, Bale egh Ahmad, Benjamin Tan, Brendan Dolan-Gavitt, and Ramesh Karri. 2022. Asleep at the Keyboard? Assessing the Security of GitHub Copilot’s Code Contributions. In Proceedings of the IEEE Symposium on Security and Privacy (S&P). 754–768.
- [26]Hammond Pearce, Benjamin Tan, Baleegh Ahmad, Ramesh Karri, and Brendan Dolan-Gavitt. 2023. Examining Zero-Shot Vulnerability Repair with Large Language Models. In Proceedings of the IEEE Symposium on Security and Privacy (S&P). 2339–2356.
- [27]Jinjun Peng, Leyi Cui, Kele Huang, Junfeng Yang, and Baishakhi Ray. 2025. CWEval: Outcome-driven Evaluation on Functionality and Security of LLM Code Generation. In Proceedings of the 2025 IEEE/ACM International Workshop on Large Language Models for Code (LLM4Code). 33–40.arxiv.org/abs/2501.08200
- [28]Neil Perry, Megha Srivastava, Deepak Kumar, and Dan Boneh. 2023. Do Users Write More Insecure Code with AI Assistants?. In Proceedings of the 2023 ACM SIGSAC Conference on Computer and Communications Security (CCS). 2785–2799.DOI
- [29]PyCQA. 2026. Bandit: Security Linter for Python Code. https://github.com/PyCQA/bandit. Accessed 2026-09-18.
- [30]Qwen Team. 2026. Qwen3.6-Plus: Towards Real World Agents. https://qwen.ai/blog?id=qwen3.6. Accessed 2026-09-01.
- [31]Leonardo Criollo Ramirez, Xavier Limón, Ángel J. Sánchez-García, and Juan Carlos Pérez-Arriaga. 2025. State of the Art of the Security of Code Generated by LLMs: A Multivocal Literature Review. Programming and Computer Software 51, 8 (2025), 587–604.
- [32]Caitlin Sadowski, Edward Aftandilian, Alex Eagle, Liam Miller-Cushon, and Ciera Jaspan. 2018. Lessons from Building Static Analysis Tools at Google. Commun. ACM 61, 4 (2018), 58–66.DOI
- [33]Amirali Sajadi, Binh Le, Anh Nguyen, Kostadin Damevski, and Preetha Chatterjee. 2025. Do LLMs Consider Security? An Empirical Study on Responses to Programming Questions. Empirical Software Engineering 30, 4 (2025), 101.
- [34]Semgrep, Inc. 2026. Semgrep. https://semgrep.dev/. Lightweight static analysis for many languages. Accessed 2026-09-18.
- [35]André Storhaug, Jingyue Li, and Tianyuan Hu. 2023. Efficient Avoidance of Vulnerabilities in Auto-completed Smart Contract Code Using Vulnerability-constrained Decoding. In Proceedings of the 34th IEEE International Symposium on Software Reliability Engineering (ISSRE). 683–693.
- [36]Yuqiang Sun, Daoyuan Wu, Yue Xue, Han Liu, Haijun Wang, Zhengzi Xu, Xiaofei Xie, and Yang Liu. 2024. GPTScan: Detecting Logic Vulnerabilities in Smart Contracts by Combining GPT with Program Analysis. In Proceedings of the 46th IEEE/ACM International Conference on Software Engineering (ICSE). 1–13.DOI
- [37]Tree-sitter Project. 2026. Tree-sitter: An Incremental Parsing System for Programming Tools. https://github.com/tree-sitter/tree-sitter. Accessed 2026-09-18.
- [38]Miles Turpin, Julian Michael, Ethan Perez, and Samuel R. Bowman. 2023. Language Models Don’t Always Say What They Think: Unfaithful Explanations in Chain-of-Thought Prompting. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 36. 74952–74965.arxiv.org/abs/2305.04388
- [39]Shubham Ugare, Tarun Suresh, Hangoo Kang, Sasa Misailovic, and Gagandeep Singh. 2025. SynCode: LLM Generation with Grammar Augmentation. Transactions on Machine Learning Research (2025).arxiv.org/abs/2403.01632
- [40]Xingyao Wang, Yangyi Chen, Lifan Yuan, Yizhe Zhang, Yunzhu Li, Hao Peng, and Heng Ji. 2024. Executable Code Actions Elicit Better LLM Agents. In International Conference on Machine Learning (ICML). 50208–50232.arxiv.org/abs/2402.01030
- [41]Xingyao Wang, Boxuan Li, Yufan Song, Frank F. Xu, Xiangru Tang, Mingchen Zhuge, Jiayi Pan, Yueqi Song, Bowen Li, Jaskirat Singh, Hoang H. Tran, Fuqiang Li, Ren Ma, Mingzhang Zheng, Bill Qian, Daniel Shao, Niklas Muennighoff, Yizhe Zhang, Binyuan Hui, Junyang Lin, Robert Brennan, Hao Peng, Heng Ji, and Graham Neubig. 2025. OpenHands: An Open Platform for AI Software Developers as Generalist Agents. In International Conference on Learning Representations (ICLR).arxiv.org/abs/2407.16741
- [42]Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Brian Ichter, Fei Xia, Ed Chi, Quoc V. Le, and Denny Zhou. 2022. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 35. 24824–24837.arxiv.org/abs/2201.11903
- [43]Brandon T. Willard and Rémi Louf. 2023. Efficient Guided Generation for Large Language Models. arXiv preprint arXiv:2307.09702 (2023).arxiv.org/abs/2307.09702
- [44]Chunqiu Steven Xia and Lingming Zhang. 2022. Less Training, More Repairing Please: Revisiting Automated Program Repair via Zero-shot Learning. In Proceedings of the 30th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering (ESEC/FSE). 959–971.DOI
- [45]Zhangchen Xu, Fengqing Jiang, Luyao Niu, Jinyuan Jia, Bill Yuchen Lin, and Radha Poovendran. 2024. SafeDecoding: Defending against Jailbreak Attacks via Safely-Wored Decoding. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (ACL). 5587–5605.
- [46]Chengran Yang, Ting Zhang, Jinfeng Jiang, Xin Zhou, Haoye Tian, Mingzhe Du, Jieke Shi, Junkai Chen, Yikun Li, Eng Lieh Ouh, Lwin Khin Shar, and David Lo. 2024. SecuRepair: Semantics-Aligned, Curriculum-Driven, and Reasoning-Enhanced Vulnerability Repair Framework. In Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics (ACL). 32108–32123.
- [47]John Yang, Carlos E. Jimenez, Alexander Wettig, Kilian Lieret, Shunyu Yao, Karthik Narasimhan, and Ofir Press. 2024. SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 37. 50528–50652.
- [48]Z.ai. 2026. GLM-5.3-Flash. https://huggingface.co/z-ai-org/GLM-5.3-Flash. Accessed 2026-09-24.
- [49]Yuntong Zhang, Haifeng Ruan, Zhiyu Fan, and Abhik Roychoudhury. 2024. AutoCodeRover: Autonomous Program Improvement. In Proceedings of the 33rd ACM SIGSOFT International Symposium on Software Testing and Analysis (ISSTA). 1592–1604.arxiv.org/abs/2404.05427
- [50]Lianmin Zheng, Liangsheng Yin, Zhiqiang Xie, Chuyue Sun, Jeff Huang, Cody Hao Yu, Shiyi Cao, Christos Koyzrakis, Ion Stoica, Joseph E. Gonzalez, Clark Barrett, and Ying Sheng. 2024. SGLang: Efficient Execution of Structured Language Model Programs. In Advances in Neural Information Processing Systems (NeurIPS), Vol. 37. 62557–62583.arxiv.org/abs/2312.07104
AI tools statement
No AI-use declaration is available for this version in Valency.
The available record does not establish whether AI systems or models contributed to this work.
