Editor’s introduction
The study focuses on Secure-Miner, a multi-agent system that mines real-world secure coding practices from open-source repositories. It uses a RegEx Agent to generate security patterns from CWE descriptions, a Verification Agent to identify actual secure functions, and a Refinement Agent to isolate core secure patterns by removing dependencies. This approach shifts from relying on vulnerability reports to capturing naturally occurring secure implementations. The researchers evaluated the framework using CWEvallow, a benchmark with 74 executable scenarios. The study demonstrates improved performance in generating secure code by leveraging authentic, real-world practices.
Introduction
Large language models (LLMs) have significantly advanced software engineering tasks such as code review, code generation, program repair, and bug detection. In code generation specifically, GPT-4 Turbo has achieved a Pass@1 score of 85.4% on the widely recognized HumanEval benchmark, while a recent open-source model, MagicoderS-CL, has reached a Pass@1 of 70.7% on the same benchmark. However, because LLMs are trained on vast corpora that may contain insecure code, the security of their generated outputs remains a significant concern. Researchers have found that 40% of code snippets generated by Copilot in a curated benchmark are vulnerable, and a related study shows that developers using Copilot often push generated code containing vulnerabilities into open-source repositories. These findings suggest that despite rapid advances in functional correctness, vulnerabilities continue to pose a substantial challenge for LLM-based code generation.
To improve the secure code generation capabilities of LLMs, researchers have pursued several directions. One line of work leverages fine-tuning techniques to enhance LLMs’ ability to generate secure code, typically relying on datasets of vulnerable-to-fixed code pairs or synthetically generated secure code examples. Another line of work focuses on automatically optimizing prompts to improve security, by injecting security-relevant knowledge or constraints into the model’s input context. However, both directions are fundamentally constrained by the same underlying data challenge. They depend on disclosed vulnerability reports or fix commits that are skewed toward well-documented CWEs, leaving low-resource vulnerability classes severely underrepresented and limiting their ability to scale and generalize across the wide variety of Common Weakness Enumerations (CWEs).
Refinement Agent. Isolates core secure patterns by simplifying external dependencies to compile a high-quality dataset. By using Secure-Miner, we extracted 1,411 secure code snippets of 56 low-resource CWE-Language pairs, where we define low-resource CWE-Language pairs as those associated with 10 or fewer publicly recorded CVE instances under a specific language, from the top 500 starred repositories per language across five programming languages (C, C++, Python, JavaScript, and Go), yielding 2,500 repositories in total. To evaluate our approach, we constructed a novel benchmark, CWEvallow, consisting of 74 executable scenarios covering 56 unique low-resource CWE-language pairs across 20 distinct CWEs, each equipped with both security test cases and functionality test cases. Unlike prior benchmarks that rely on static analysis without functionality testing, CWEvallow is the first to provide dynamic, execution-based evaluation specifically targeting low-resource CWEs across five languages.
Secure Code Data Mining
A major line of work constructs vulnerability datasets by mining open-source repositories and mapping discovered issues to CWE categories. BigVul mines 3,754 vulnerabilities spanning 91 CWE types from GitHub projects, and DiverseVul scales this to roughly 349,000 functions across 150 CWEs by parsing security-issue sites and National Vulnerability Database (NVD) records. CVEfixes and related efforts similarly mine NVD-linked commits and CVE-details pages to assemble thousands of patches across many languages, while VulDeePecker mines a more narrowly scoped Code Gadget Database from NVD and Software Assurance Reference Dataset (SARD), targeting buffer-error (CWE-119) and resource-management (CWE-399) weaknesses specifically. Devign and ReVeal further contribute manually labeled function-level corpora from FFmpeg/Qemu and Debian/Chromium, respectively, and are now standard benchmarks for CWE-style vulnerability detection. Zhou et al. shift the mining target from vulnerable code to the commits that fix it, proposing SPI, a system that automatically distinguishes security patches from the much larger pool of ordinary bug-fix commits in open-source repositories. SPI mines two complementary signal sources directly from commit history, a natural-language model over commit messages and a code-revision neural network that learns statement-level differences between pre- and post-patch code by training on commits mined across many heterogeneous OSS projects rather than a single codebase.
These studies illustrate two dominant mining targets, vulnerable code itself, and the fix commits that follow disclosure. Both directions are fundamentally anchored to known vulnerability references, depending on NVD records, CVE identifiers, or static analysis tools to identify what constitutes insecure code before any mining can begin. This dependence introduces a limitation: only vulnerability classes that are publicly disclosed and tool-detectable can be represented in the resulting datasets. Mining secure coding practices, by contrast, requires no such vulnerability reference. Rather than starting from a known flaw and tracing its fix, we identify code that is proactively written to be secure. This allows our approach to surface security knowledge that is invisible to prior methods: namely, secure implementations that have never been associated with a CVE, never triggered a static analysis alert, and never appeared in a fix commit, yet nonetheless embody correct and principled security behavior in production software.
Security Challenges in LLM-Generated Code
Ensuring software security remains a persistent challenge across both industry and academia. Although Large Language Models (LLMs) have demonstrated remarkable potential in automating code generation, their reliance on unsanitized training data from open-source repositories frequently leads to the propagation of insecure coding practices. The prevalence of such security flaws in LLM-generated code has been extensively documented in recent literature. In an evaluation of GitHub Copilot, which is powered by the OpenAI Codex model, Pearce et al. found that approximately 40% of the generated outputs contained security vulnerabilities. These vulnerabilities are systematically categorized using the Common Weakness Enumeration (CWE) framework, a widely adopted standard for identifying software security flaws. Further investigations by Khoury et al. into ChatGPT’s performance on security-critical tasks revealed that the model initially produced insecure code in 16 test cases, successfully correcting only 7 even after iterative prompting. Compounding these risks, Perry et al. observed that developers relying on AI coding assistants are statistically more likely to introduce security vulnerabilities into their software projects.
Improving Security via Prompting and Fine-Tuning
Fine-tuning-based approaches. A number of works adapt LLMs to secure coding behavior by updating model parameters on curated security data. Li et al. fine-tuned an LLM directly on vulnerability-fixing commits so that the model internalizes patterns of insecure-to-secure code transformations. Hajipour et al. instead synthesized secure code examples under the guidance of the CodeQL static analysis oracle, using its vulnerability detection signal to construct training data. Complementing these data-construction strategies, Li et al. conducted an exploratory study on how parameter-efficient fine-tuning techniques affect the security of generated code, offering practical guidance on tuning-method selection. He et al. proposed SVEN, which performs property-specific prefix-tuning: continuous prefix vectors are optimized over a carefully curated, high-quality dataset and prepended to LLM inputs to steer generation toward secure code while suppressing vulnerable patterns. Building on instruction tuning, He et al. presented SafeCoder, a security-focused instruction-tuning method trained on 465 high-quality vulnerable-to-fixed code pairs mined from 145 million real-world commits. Most recently, Secure-Instruct introduced an automated pipeline that leverages LLMs themselves to synthesize instruction-tuning datasets for secure code generation, removing the dependence on manually curated commit data and enabling scalable generation of high-quality, security-oriented instruction pairs.
Prompting-based approaches. Rather than modifying model weights, a second line of work improves code security by optimizing or guiding the prompts fed to LLMs at inference time, which avoids the cost of retraining and is often more readily applicable across different models. Li et al. proposed attribution-guided adversarial code prompt generation, which uses attribution analysis to identify which parts of a prompt most influence insecure generations and crafts adversarial prompts to probe and subsequently harden LLM code generation behavior. Nazzal et al. introduced PromSec, a prompt optimization framework that iteratively refines the input prompt using feedback from a vulnerability detector and a generative adversarial graph network, jointly optimizing for code correctness and security without touching model parameters. In the context of retrieval-augmented code generation, Lin et al. proposed a knowledge-injection technique that effectively gives the LLM a “security course” by injecting security-relevant knowledge into the retrieval pipeline, securing the retrieved context before it is used for generation. Together, these prompting-based methods demonstrate that meaningful security gains can be achieved purely through input-side interventions, offering a lightweight alternative or complement to fine-tuning-based defenses.
Experiment Setup
Low-Resource CWE Identification. We define low-resource Common Weakness Enumerations (CWEs) as those associated with 10 or fewer publicly recorded Common Vulnerabilities and Exposures (CVE) instances. The CVE catalog, maintained by MITRE, is a standardized repository of publicly disclosed cybersecurity flaws in software and hardware. Each CVE instance provides a universal tracking ID that links to a specific type of CWE. To identify these low-resource CWEs, we leverage two distinct datasets that record released CVE instances and their corresponding fixes. The dataset is a curated collection of 4,900 vulnerability-fixing commits across 580 open-source projects, which consolidates information from the BigVul, CVEfixes, and AndroidCVEfixes databases. Another dataset, MoreFixes, is a large-scale collection containing 26,617 unique CVEs mined from 6,945 GitHub projects, mapped to 31,883 unique fix commits. After merging these sources and removing duplicate CVE entries, we count the unique CVEs under each CWE and classify those with 10 or fewer as low-resource. In this paper, we evaluate five programming languages (C, C++, Python, Go, and JavaScript) and map out the specific low-resource CWE-Language pairs relevant to each language.
Evaluation Benchmarks. We aim to evaluate our approach on low-resource CWE-Language pairs. To compile this benchmark, we extract the low-resource CWE-Language pair scenarios from a benchmark for secure code generation, CWEval, which provides 64 low-resource CWE-Language scenarios. Additionally, we incorporate CyberSecEval, a security benchmark developed by Meta that covers real-world vulnerability scenarios. However, CyberSecEval evaluates security exclusively through static analysis and does not provide executable test cases, making it incompatible with our dynamic, execution-based evaluation protocol. To address this, we extended a subset of CyberSecEval with dynamic execution tests. For each selected scenario, one author implemented paired security and functionality test cases along with both secure and insecure reference implementations to validate the test suite’s discriminative power. The implemented test cases were then reviewed and validated through discussion with other co-authors until consensus on correctness was reached. Through this process, we successfully constructed executable test suites for ten CyberSecEval scenarios. Combined with the 64 low-resource scenarios drawn from CWEval, our final benchmark, CWEvallow, comprises 74 executable scenarios spanning 56 unique CWE-Language pairs across 20 distinct low-resource CWEs, each evaluated on both security correctness and functional correctness.
RQ1: How effective is Secure-Miner in extracting and refining high-quality secure coding practices from open-source repositories?
Motivation. We employ Secure-Miner with three agents to extract the secure coding practices from GitHub repositories. Within this pipeline, the verification agent is responsible for identifying secure code snippets, while the refinement agent focuses on cleaning and optimizing those secure snippets. However, it remains unclear whether the verification agent accurately identifies the code relevant to specific CWEs, and whether the refinement agent preserves the underlying security patterns without altering the original functionality. Therefore, in this RQ, we evaluate the performance and reliability of both the verification and refinement agents.
Approach. To answer this RQ, we conducted a rigorous manual inspection of both the raw extracted code and the agent-refined snippets. From our initial dataset of 1,411 extracted snippets, we established a statistically significant sample size of 149 snippets, achieving a 99% confidence level with a 10% margin of error.
Results. Based on our manual inspection of the 149 sampled snippets, the verification agent demonstrated strong precision in identifying relevant secure practices. In the first phase, we found that 95.3% (142/149) of the extracted snippets were labeled as Secure and Relevant, successfully demonstrating a mitigation practice for the target CWE. The remaining 4.7% (7/149) were classified as Not Secure/Irrelevant. Of these seven instances, five were classified as such because the code remained vulnerable despite the presence of some preventative measures, while the remaining two consisted of extracted code that was entirely unrelated to the specified CWE.
RQ2: Can the secure coding practices mined by Secure-Miner contribute to fine-tuning LLMs for secure code generation?
Approach. To evaluate the performance of Secure-Miner, we selected three open-source models: CodeLlama-7B, DeepSeek-Coder-7B, and Qwen2.5-Coder-7B. We fine-tuned these models using the secure code dataset extracted by Secure-Miner. All fine-tuning experiments of Secure-Miner are conducted on five Nvidia RTX A6000 GPUs with 48GB of memory, and we applied LoRA fine-tuning technique with a learning rate 3e-4. Each model is fine-tuned in two epochs. In LoRA fine-tuning, we configure the LoRA alpha to 16 to control the scaling of LoRA layers and set the dropout rate to 0.05.
To benchmark against recent advancements in secure code generation, we selected three state-of-the-art baselines: Li et al., SafeCoder, and Secure-Instruct. Li et al. fine-tune LLMs on vulnerability-fixing data from CVE records to generate secure code. SafeCoder introduces a specialized fine-tuning technique that leverages pairs of vulnerable and fixed code mined from open-source software repositories. Secure-Instruct synthesizes secure code using LLMs guided by CWE descriptions. Because Secure-Instruct relies on data synthesis, we followed its methodology to generate a low-resource CWE dataset to ensure a fair comparison. For Li et al. and SafeCoder, we directly utilized their publicly released fine-tuning datasets to adapt and fine-tune three selected base models.
Crucially, our proposed approach (Secure-Miner) outperforms all evaluated baselines by significant margins across every model. Our method achieves the highest overall results when applied to Qwen-Coder-7B, reaching 33.3% on Sec@1 and 25.5% on Func-Sec@1. Notably, this represents an absolute improvement of 6.2% on Func-Sec@1 compared to the state-of-the-art baseline, Secure-Instruct. Furthermore, our approach boosts DeepSeek-Coder-7B to 29.5% on Sec@1 and 20.1% on Func-Sec@1, and elevates CodeLlama-7B to 27.7% on Sec@1 and 17.8% on Func-Sec@1. This consistent performance gain across all three models highlights the robustness and generalizability of our approach in effectively balancing functional correctness with security on low-resource CWEs.
External Threats
Generalizability across Languages and CWEs. Our findings are evaluated on five programming languages and 20 low-resource CWEs, and may not transfer to other languages or higher-resource vulnerability categories. The low-resource threshold of 10 or fewer CVEs is also a design choice that could be set differently, altering which CWEs are studied.
Benchmark Construction Limitation. CWEvallow draws 64 of its 74 scenarios from CWEval and the remaining 10 from manually extended CyberSecEval scenarios. The limited number of CyberSecEval scenarios is due to the inherent difficulty of constructing executable test cases from real-world repository contexts, i.e., many scenarios lack the self-contained structure needed to support both security and functionality testing, making only a small subset suitable for dynamic evaluation.
Corpus and Data Source Coverage. Our secure code corpus is mined exclusively from the top 500 highest-starred GitHub repositories per language and does not consider other potential sources of secure coding practices, such as StackOverflow or curated security documentation. While GitHub favors high-quality, widely used codebases, the resulting dataset may not fully represent secure practices in less popular projects or other development communities.
Conclusion
In this paper, we proposed Secure-Miner, a novel multi-agent framework designed to automatically extract, verify, and refine real-world secure coding practices from open-source repositories. By shifting the focus from disclosed vulnerability reports to naturally emerging secure implementations, Secure-Miner effectively addresses the critical training data scarcity for low-resource CWEs. The framework effectively addresses the critical training data scarcity for low-resource CWEs, providing a diverse, high-quality dataset for model optimization. To evaluate our approach, we introduced CWEvallow, a comprehensive benchmark comprising 74 executable scenarios across 56 unique low-resource CWE-language pairs. Our extensive evaluations demonstrate that fine-tuning medium-sized LLMs on our mined dataset consistently outperforms existing state-of-the-art secure code generation baselines, achieving up to a 6.2% absolute improvement on the Func-Sec@1 metric. Furthermore, integrating our refined secure practices into RAG frameworks substantially elevates both the security and functional correctness of leading commercial models. Secure-Miner provides a robust, scalable, and highly effective pathway to enhancing LLM-driven secure code generation for low-resource vulnerabilities without sacrificing functional integrity.


