LeanGuard: A Neuro-Symbolic Reasoning Framework for Vulnerability DetectionNeuro-Symbolic Reasoning for Vulnerability Detection
The authors propose LEANGUARD, a neurosymbolic vulnerability detection framework, and report that F1 exceeds the strongest baseline in all 15 settings across 5 CWE classes and 3 backends.
The defender judges, for a single C/C++ function and without guaranteed full program context, whether a memory safety defect of a specified CWE class (e.g., null pointer dereference, UAF, double free) actually exists; the target class must be fixed in advance, and the authors state that pure LLM and whole-repository-accessible agent baselines systematically misjudge as SAFE.
- When doing vulnerability detection, LLMs use fluent justifications to prematurely discharge safety obligations and judge defective code as SAFE; rule-based static analysis is deterministic and auditable but limited by manual rules, and the authors argue for separating "explaining the code" from "judging that the obligation is satisfied."
- LEANGUARD has six stages: AST extraction of candidate facts, LLM performing only restricted semantic filtering, deterministic fact reconciliation and automatic pairing, Lean 4 kernel verification, at most one round of neuro-symbolic correction, and adjudication graded by evidence quality; the LLM does not directly give the final verdict.
- Across 15 settings (5 CWE classes, 3 backends: pure LLM, Codex, Claude Code), the authors report that F1 exceeds the corresponding baseline in all; on CWE-415 the Claude Code backend's F1 rises from 0.3385 to 0.5432, and 6 of 9 combinations in the repeated-run subset have p<0.05.
- The authors note: each CWE class requires a manually constructed specification and the target classes must be fixed in advance; they do not claim generalization to unseen classes or to vulnerabilities requiring whole-program reasoning; CWE-125 and CWE-415 are single-run only; benchmark labels were not independently re-audited; only one backend model, DeepSeek-V4-Pro, was tested.
- Evaluated models
- DeepSeek-V4-Pro
- Benchmarks
- 自构数据集(合并 PrimeVul、ReposVul、R2Vul,取 CWE-476/120/416/125/415 共 801 样本)
- Metrics
- ACCF1PrecisionRecall
LeanGuard is a neuro-symbolic vulnerability detection framework that attributes unreliable LLM judgments to security obligations being discharged prematurely, separating the component that interprets code from the component that decides obligations. The LLM serves only as a semantic filter, separating true from false among AST candidate facts; surviving facts are compiled into a Lean 4 verification model, and a dangerous operation must have a guard that provably covers it, otherwise the obligation remains undecided. An unproven obligation does not equal a defect; the framework is instantiated on five CWE classes.
Paper analysis
What problem does this paper attempt to solve?
The authors argue that the unreliability of LLM vulnerability detection stems from "premature discharge of safety obligations," and advocate separating the raising of facts from the discharge of obligations.
Core problem: LLMs are unreliable at judging whether dangerous operations in code (dereferences, accesses, frees) will actually trigger memory safety defects, and the authors attribute this failure to "premature discharge" of safety obligations—the model judges code safe as soon as it can fabricate a fluent justification, but a fluent argument is not a proof.
- Problem setting and importance: Memory safety defects (CWE-476 null pointer dereference, CWE-416 UAF, CWE-415 double free, etc.) consistently rank among the most frequently occurring weakness categories; detection requires judging a single function without full program context, and defenders must hold every dangerous operation.
- Shortcomings of existing methods (as stated in the paper): Rule-based static analysis (Infer, Coverity, Cppcheck) is deterministic and auditable but limited by manual rules and lacks semantic understanding; LLMs understand semantics but introduce nonexistent variables, misjudge data-flow direction, draw conclusions when evidence is insufficient, and their judgments are not auditable. The authors also state that when agents such as Codex and Claude Code are placed in the whole repository to retrieve context on their own, they still systematically lean toward judging SAFE, most evidently on lifetime-related defects (§V-C).
- Core observation: The authors argue the problem is not the noise of LLM reasoning but letting the same component both explain the evidence and discharge the obligation; stronger models and more context buy only more fluent justifications, not more discharged obligations.
- Proposed approach: LEANGUARD, a neurosymbolic framework—the LLM acts only as a semantic filter over AST candidate facts (removing false facts, retaining true facts), the symbolic side compiles the surviving facts into a Lean 4 verification model, every dangerous operation must have a protection provably covering it within scope, otherwise the obligation remains open; an evidence-aware adjudicator then fuses the decision according to the evidence quality of both sides.
- Threat model (defender's perspective):
- What is protected: memory safety defects of specified CWE classes in C/C++ function-level code.
- Defender's assumptions: the analyst usually lacks the full program (external callees, macros, cross-file object lifetimes), and the target CWE class must be fixed in advance.
- Defense placement: a deterministic Lean 4 kernel verification layer and evidence-quality adjudication are added beyond the LLM judgment; the LLM has no authority to conclude on its own.
- Failure modes: the authors state that pure LLM and whole-repository agent baselines miss real defects (especially lifetime-related ones) and give the same erroneous justifications across repeated runs.
What related research exists?
Related work falls into four groups: rule-based static analysis, LLM code analysis, formal verification and Lean 4, and neurosymbolic systems.
Rule-based static analysis
- CodeQL [16] lets analysts write vulnerability patterns as logic rules in a declarative query language; Infer [28] uses separation logic to infer pre- and postconditions across functions; Coverity [36] and Cppcheck [26] combine data-flow analysis, taint propagation and pattern matching to flag common CWE classes.
- The paper notes that such tools have high rule-base maintenance costs, require re-adaptation after coding-style changes, and their limited semantic modeling makes cross-function implicit constraints hard to express, often raising false-positive rates [21], [33].
LLMs for code analysis
- Pretrained code models [15] and large-scale generative models such as DeepSeek-Coder [18] have advanced code understanding and generation; in security, agentic systems for autonomous security research have recently appeared [4], [17], [35].
- IRIS [25] uses LLMs to generate taint specifications for static analyzers, QLPro [1] combines LLMs with CodeQL through role division, and fact-aligned template-constrained generation [20] improves rule accuracy. The paper notes that these works all keep model outputs directly serving as rule sources or final conclusions within a probabilistic reasoning framework, with no independent verification barrier, and the authors therefore argue for decoupling probabilistic generation from rigorous logical verification.
Formal verification and Lean 4
- The seL4 microkernel [22] and the CompCert compiler [23] demonstrate the value of formal methods for high-assurance systems; Lean 4 [29] is both a programming language and a proof system, with metaprogramming support [42] and a built-in decision procedure for propositions over finite Boolean domains.
- The paper notes that existing work combining LLMs with provers [7], [34], [46] mostly targets proof-capability evaluation or automated theorem proving itself, and that modeling real code with complex control flow and engineering context into verifiable propositions remains costly.
Neurosymbolic systems
- APOLLO [32] proposes a generate-verify-repair loop, DeepSeek-Prover [45] uses reinforcement learning and Monte Carlo tree search with verifier feedback as the policy signal; Cobbe et al. [9] argue that an independent verifier improves reasoning reliability.
- The paper notes that these neurosymbolic provers place the LLM on the critical generation path (the model produces proofs, the symbolic engine scores or corrects them), whereas LEANGUARD does the reverse: the neural part performs only bounded fact confirmation and constrained semantic review, and formal reasoning runs on an independently constructed model.
Baselines and data: The experimental baselines are a pure LLM (DeepSeek-V4-Pro giving the judgment directly) and two agents with retrievable repository context, Codex [31] and Claude Code [3]; the dataset merges PrimeVul [13], ReposVul [43] and R2Vul [44], which the authors state improve on the labeling noise and entangled-patch quality issues of earlier datasets [6], [8], [14], [24]. The authors position this work as: not letting the LLM discharge obligations, distinguishing it from all the above "model output is the conclusion" lines of work.
How does the paper address this problem?
LEANGUARD uses a six-stage pipeline: the LLM performs only restricted fact filtering, the Lean 4 kernel verifies obligations, and evidence quality adjudicates the final verdict.
Overall approach: LEANGUARD gives "proposing facts" to the neural side and "discharging obligations" to the symbolic side, with no component holding decision authority alone; when the full program is unavailable, unproved obligations are interpreted conservatively rather than treated as proof of safety. The pipeline has six stages (Figure 1).
Unified formal abstraction
- Each CWE class instantiates a verification model M = ⟨E, P, O⟩: E is the entity whose safety state is tracked (e.g., a pointer variable), P is a protection operation that establishes the safety property (e.g., a null check), and O is an obligation operation that, if executed unprotected, constitutes a potential vulnerability.
- An obligation o is paired with its candidate protection set into a claim c = ⟨ o, Po ⟩, where P_o is a protection on the same entity as o and of a compatible type; the obligation is discharged if and only if some protection structurally covers it:
\mathrm{discharged}(o) \iff \exists p \in P_o.\ p \prec_{safe} o. - ≺safe is instantiated per class: spatial classes (CWE-476/120/125) use region containment, lifetime classes (CWE-416/415) use control-flow dominance; the concrete E/P/O mappings for the five classes are in Table I.
Stages 1–2: Candidate extraction and constrained semantic filtering
- Stage 1: tree-sitter parsing plus regex compensation extracts a high-recall candidate fact set F_AST from the AST, each record containing a functional category, entity, physical line number and literal code; a CWE-specific risk lexicon then assigns a syntactic confidence γ ∈ {High, Low}, where γ carries no semantic judgment and serves only as a protection anchor for stage 3.
- Stage 2: the LLM acts only as a structured semantic reviewer, constrained by an immutable JSON output schema, outputting a binary judgment V_LLM, a brief justification, and lists of additions and deletions to guards/operations/entities (∆+, ∆−); in the paper's running example the LLM misjudges SAFE and requests deletion of a critical use site (Listing 4).
Stages 3–4: Fact reconciliation, automatic pairing and kernel verification
- Stage 3: F_final = (F_AST minus ∆− that fail ForceKeep) union ∆+ that pass the Source-Backed check; Source-Backed requires added facts to map to valid line numbers and match literally, and ForceKeep forbids the LLM from deleting candidates with γ = High. Class-specific automatic pairing strategies from Table II then pair dangerous operations with protections into verifiable claims.
- Stage 4: The pairing results are automatically compiled into Lean 4 scripts, and the kernel performs full proof checking; Lean does not re-parse the C/C++ source, only evaluating the structural consistency of the abstract model. Each claim results in proved / unproved / error; if any claim is unproved then V_Lean = VULNERABLE, and only when all are discharged is it SAFE; the full per-claim result vector (rather than an aggregate judgment) is passed to stage 6.
Stages 5–6: Revision and evidence adjudication
- Stage 5: At most one round of revision per sample, with two triggers: when V_Lean and V_LLM conflict, the unproved claims are presented to the LLM for re-review; when the obligation set is empty but the source contains dynamic resource lifetime lexicon markers, retry (CWE-416/415 only).
- Stage 6: The symbolic quality score Q_Lean ∈ {strong, weak, noisy, none} is determined by matching unproved claims against the noise lexicon and high-risk lexicon; the neural quality score Q_LLM ∈ {strong, weak, none} assesses whether the justification lands on literal variable identifiers and correct CWE semantics. The final judgment is given by an asymmetric adjudication matrix (Table III, CWE-416 version) according to (V_Lean, Q_Lean, V_LLM, Q_LLM, |O|): symbolic evidence takes precedence when strong, and yields to neural semantics when the symbolic model is empty or noisy.
- Running example: In CVE-2021-3640 (a UAF in the Linux kernel's sco_sock_sendmsg), the LLM's deletion request is intercepted by ForceKeep, automatic pairing yields a claim with an empty protection set, Lean judges VULNERABLE with Q_Lean = strong, and row 1 of the adjudication matrix overturns the neural miss, outputting VULNERABLE, consistent with the true label.
What experiments did the paper conduct?
5 CWE classes × 3 backends, 15 settings in total; the authors report F1 exceeding the baseline in all of them, plus ablation, stability and cost experiments.
Experimental Setup
- Backends under test: pure LLM (DeepSeek-V4-Pro making the verdict directly), Codex agent, Claude Code agent; all neural components (including those inside LEANGUARD) uniformly use DeepSeek-V4-Pro, temperature 0, and the two agents also use the DeepSeek-V4-Pro API as the underlying model.
- Dataset: PrimeVul, ReposVul, and R2Vul merged; after scope filtering, a 16,384 token length limit, and MD5 deduplication, 5,078 CVEs and 149 CWE classes were obtained; 5 classes were selected from these to form the experimental set: CWE-476 138 entries, CWE-120 116 entries, CWE-416 183 entries, CWE-125 255 entries, CWE-415 109 entries, 801 entries in total (403 vulnerable, 398 non-vulnerable), each class approximately 1:1 balanced; additionally 577 repository versions were cloned for the agents to retrieve context.
- Metrics: ACC, F1, Precision, Recall, with the vulnerable class as the positive class and F1 as the primary metric.
- Number of repetitions: CWE-120/416/476 each run 3 times; Table IV reports the best F1 among the three runs (full statistics in Table VI); CWE-125 and CWE-415 were run only once due to cost.
- Statistical tests: paired t-test on the per-round ∆F1 of the three runs (df = 2), with a sign test also reported.
Main Results
According to Table IV (F1 as the primary metric, Ours is LEANGUARD):
Swipe horizontally to read the table
Dataset Backend Baseline F1 Ours F1 Baseline Rec Ours Rec CWE-120 (N=116) Claude Code 0.6607 0.7080 0.5968 0.6667 CWE-120 Codex 0.6261 0.6957 0.5806 0.6452 CWE-120 Pure LLM 0.6379 0.6929 0.5968 0.7097 CWE-416 (N=183) Codex 0.4727 0.6165 0.3171 0.5062 CWE-416 Pure LLM 0.3652 0.5000 0.2561 0.3902 CWE-415 (N=109) Claude Code 0.3385 0.5432 0.2075 0.4151 CWE-415 Pure LLM 0.4324 0.6237 0.3019 0.5472 CWE-476 (N=138) Pure LLM 0.6509 0.7047 0.7237 0.8947 (The three rows CWE-416/Claude Code, CWE-476/Claude Code and Codex, and CWE-125 are omitted; the F1 improvement across the 15 settings ranges from +0.02 to +0.20, according to the full Table IV.)
- The authors state that F1 exceeds the corresponding baseline in all 15 settings, with the improvement mainly from recall: baselines (especially agents) favor high precision and low recall, e.g., CWE-416/Codex precision 0.9286 but recall 0.3171.
- The authors state that precision pays a small cost (e.g., CWE-476 pure LLM 0.5914→0.5812), and consider the cost of missing a vulnerability higher than reviewing one extra function.
- The authors point out that the cheapest pure LLM backend instead obtains some of the largest improvements (CWE-415 +0.19, CWE-416 +0.13).
RQ2 Ablation (Table V, single run)
- w/o Translation (LLM writes Lean directly): the compile-verification success rate drops, with Claude Code succeeding on only 82/116 for CWE-120; recall of the agent backends drops markedly, with Claude Code under CWE-416 falling from 0.5732 to 0.2754 and Codex from 0.5062 to 0.2368; the authors state that the deterministic translator is indispensable for verifiability.
- w/o AST (LLM identifies guards and dereferences from source code itself): on CWE-476 recall is close to 1 (Codex 1.0000) but precision is low (0.5522); the authors state that the role of the AST stage is to suppress the tendency to "mark everything as vulnerable"; on CWE-416 the AST stage also removed some true positives (Claude Code recall 0.6951→0.5732), but net F1 still improves for each backend.
- Exception for the pure LLM backend: w/o Translation on CWE-416 has both low precision and low recall (0.4412, 0.3750); the authors state that the failure modes of direct generation vary by backend.
RQ3 Stability and RQ4 Cost
- Stability (Table VI, VII): the F1 standard deviation across the three runs for CWE-120/416/476 is below 0.04 in all cases; ∆F1 is positive in all 9 combinations, with 6 reaching p < 0.05 (e.g., CWE-416/Codex +0.149 ± 0.006, t = 41.66, p = 0.0006); the authors attribute the 3 combinations not reaching the threshold to wider intervals with only three runs; sign test p ≈ 0.002.
- Cost (Table VIII): the pure LLM backend takes 37–104 seconds per sample, with input and output tokens both below 1M; Codex input tokens are 5–8.5× those of Claude Code (e.g., CWE-416: 48.28M vs 7.87M); the authors state that the agents' high cost did not buy proportional accuracy, and that the verification mechanism brings bounded overhead.
- Motivating example (§III): on CVE-2021-3640, the pure LLM, Codex, and Claude Code each independently run three times all judge SAFE with essentially the same reasoning; the authors state that they incorrectly assume that releasing the mutex means the pointer is valid.
What are some points that can be further explored?
The authors point out that each CWE class requires manual specification and do not claim generalization; the experiments cover only one backend model, and two classes were run only once.
Limitations and future directions noted by the authors
- Per-class specifications must be built manually (§I, §VI): The current implementation requires a manually constructed specification for each CWE class (dedicated extraction rules and property templates), and target classes must be fixed in advance; the authors state this is an explicit boundary of the study and that, because different weaknesses expose different obligation structures, this per-class customization is an intrinsic property of the current design.
- No claim of generalization (§VI): The authors state they make no generalization claim to unseen CWE classes or to vulnerabilities requiring whole-program reasoning; the five classes span different defect families but are far from exhaustive; LEANGUARD is positioned as an exploratory prototype for validating the feasibility of "separating fact proposal from obligation discharge," not as a deployable tool.
- Future directions (§VI): Removing the per-class specification requirement—including automatic routing to weakness classes and a shared extraction layer—is the core future direction proposed by the authors.
- Labels not independently re-audited (§VI): The main F1 metric inherits the limitations of the benchmark labels; the authors did not independently re-audit the labels.
- Translation reliability (§VI): Judgment confidence is bounded by the Lean encoding; a verified script proves only that the modeled properties hold, not that no other vulnerabilities exist.
- Single-run classes (§V-E, §VI): CWE-125 and CWE-415 are single-run; the authors state their results are indicative.
Scope of experimental coverage
- 3 backends were tested: pure LLM, Codex, Claude Code, with the neural component uniformly DeepSeek-V4-Pro (temperature 0); the paper does not report results on other LLM backends.
- The experimental dataset covers 5 CWE classes with 801 samples in total (C/C++ function-level, roughly 1:1 balanced per class), selected from 149 CWE classes according to three principles.
- The ablation covers only two neurosymbolic stages (w/o AST, w/o Translation) on three classes, CWE-120/416/476, single-run.
- Repeated runs and statistical tests cover only CWE-120/416/476 × 3 backends, 9 combinations in total, each with 3 runs (df = 2).
- The cost data (Table VIII) include time and token consumption only for the three classes CWE-120/416/476.
Summarize the main content of the paper
LEANGUARD lets the LLM perform only fact filtering and Lean 4 discharge safety obligations; the authors report F1 exceeding the baseline in all 15 settings.
A paper on a neurosymbolic method for C/C++ function-level memory safety vulnerability detection.
- Problem: The authors argue that the unreliability of LLM vulnerability detection stems from "premature discharge of safety obligations"—the model judges SAFE as soon as it can fabricate a fluent justification, but a fluent argument is not a proof; stronger models and whole-repository context only yield more fluent justifications, and missed detections are most pronounced on lifetime-related defects.
- Method: LEANGUARD separates responsibilities—the LLM performs only constrained semantic filtering over an AST candidate fact set (additions and deletions constrained by a JSON schema), two rules, ForceKeep and Source-Backed, intercept hallucinated deletions and edits, deterministic automatic pairing pairs dangerous operations with protections into claims, the Lean 4 kernel decides whether obligations are structurally covered, and finally a decision is made via an asymmetric matrix graded by symbolic and neural evidence quality; unproved obligations are handled conservatively, with at most one round of revision.
- Main results: On 801 samples across CWE-476/120/416/125/415 and three backends (pure LLM/Codex/Claude Code), the authors report F1 exceeding the corresponding baseline in all 15 settings (Table IV), with improvements from +0.02 to +0.20.
- Representative numbers: On CWE-415 with the Claude Code backend, F1 rises from 0.3385 to 0.5432 and recall from 0.2075 to 0.4151; on CWE-416 with the Codex backend, recall rises from 0.3171 to 0.5062; the improvements come mainly from recall, with a small decrease in precision (e.g., CWE-476 pure LLM 0.5914→0.5812).
- Stability and cost: On the repeated-run subset (3 classes × 3 backends), all 9 combinations have positive ∆F1, and 6 have p < 0.05; the pure LLM backend is the cheapest (37–104 seconds per sample) and has some of the largest improvements.
- Authors' conclusions and boundaries: The authors consider it feasible to separate "proposing facts" from "discharging obligations" and not let any single component hold decision authority alone; they also state explicitly that each CWE class requires a manual specification and that target classes must be fixed in advance, do not claim generalization to unseen classes, and position the work as an exploratory prototype, with automatic routing and a shared extraction layer as future directions.