LLM Security Testing in Practice: Recall, Consistency, and Cost Analysis

    As large language models (LLMs) increasingly enter code auditing and vulnerability detection, their real-world performance matters more than benchmark numbers. This article analyzes three core dimensions—recall rate, consistency, and cost efficiency—based on large-scale security testing involving billions of tokens. Key findings include the gap between single-pass and multi-run aggregated recall, the business impact of inconsistent scan results, and practical engineering strategies such as structured output constraints, tiered model routing, and RAG-based context trimming to balance detection effectiveness against cost.

    With recent breakthroughs of large language models (LLMs) in code generation and natural language processing, applying them to security vulnerability detection and code auditing has become an industry trend. Traditional static application security testing (SAST) tools offer explicit rules but suffer from high false-positive rates and weak contextual understanding. LLM-based security auditing, by contrast, can understand code logic at the semantic level and uncover complex business logic vulnerabilities. However, in large-scale audits consuming tens of billions of tokens, actual model performance falls short of what specification sheets suggest. This article, setting aside specific brands and products, examines how security-focused LLMs perform in practice across three core dimensions: recall rate, consistency, and cost efficiency.

    1. Recall Rate Deep Dive: Single-Pass Detection vs. Multi-Run Aggregation

    In vulnerability discovery, recall measures how many real vulnerabilities a model can find. Recent industry-scale testing reveals a common pattern: models achieve strong recall under multi-run aggregation, but single-pass detection is far less impressive.

    Specifically, when the same security test set (for example, 32 known high-severity vulnerability samples) is scanned multiple times independently, a “union” strategy—taking the union of results across runs—can yield very high theoretical recall (e.g., 28/32 hits). But a single first-pass scan often sees recall drop dramatically (e.g., only 17/32).

    The root cause lies in the probabilistic sampling mechanism of LLM generation. Locating security vulnerabilities is fundamentally a complex reasoning task; a single generation may miss certain patterns because the reasoning path drifts. Multi-run aggregation effectively expands the search space, covering more vulnerability trigger paths through repeated sampling.

    In engineering practice, however, multi-run aggregation implies high compute costs and latency. To approximate aggregated recall with one or few calls, developers need more refined prompt engineering, for example:

    • Divide and conquer: Split large code files by function or module to avoid attention degradation caused by overly long contexts.
    • Chain-of-thought prompting: Force the model to analyze data flow and control flow step by step before drawing conclusions, reducing false negatives from jump-style reasoning.

    2. The Consistency Problem: Why Variance Is Fatal for Security Auditing

    Beyond absolute recall, consistency determines whether a model can actually be deployed in enterprise CI/CD pipelines. Testing data exposes a serious issue: across multiple runs, the number of vulnerabilities “stably detected” (found in every run) may be only about one third of the total (e.g., 10/32).

    High variance is fatal for security operations. In a continuous integration environment, if the same code yields inconsistent scan results at different times, developers face “ghost alerts”—yesterday’s build reported no vulnerabilities, today’s build suddenly blocks the pipeline. This drains security teams’ triage capacity and seriously erodes trust in the security tool.

    Common causes of poor consistency include:

    1. Improper temperature settings: High Temperature values increase creativity at the expense of determinism.
    2. Context window pollution: When processing massive logs or code, critical vulnerability signals can be drowned out by redundant information, causing the model’s probability of capturing key features to drift across runs.

    Fixing consistency requires hard constraints. The following illustrative pseudocode shows how to improve stability through forced structured output and low-temperature sampling:

    1. import json
    2. import requests
    3. def analyze_security_vulnerability(code_snippet, model_endpoint):
    4. headers = {"Content-Type": "application/json"}
    5. payload = {
    6. "model": "industry-standard-sec-llm",
    7. "messages": [
    8. {"role": "system", "content": "You are a strict code security auditor. Output JSON only: {\"is_vulnerable\": bool, \"vuln_type\": str, \"reason\": str}"},
    9. {"role": "user", "content": f"Analyze the following code for security vulnerabilities:\n{code_snippet}"}
    10. ],
    11. "temperature": 0.0, # Force greedy decoding for maximum determinism
    12. "top_p": 1.0,
    13. "response_format": {"type": "json_object"} # Force JSON output
    14. }
    15. response = requests.post(model_endpoint, headers=headers, json=payload)
    16. result = json.loads(response.text)
    17. return result

    3. The Cost-Efficiency Trade-off: How Emerging Models Break the Barrier

    Security auditing is a heavy token consumer. A full scan of a large microservice architecture can involve millions of lines of code, translating into billions—or tens of billions—of tokens. As a result, inference cost is a core selection criterion, provided recall is maintained.

    Testing shows that while frontier models perform excellently, their moat in the security auditing vertical is eroding quickly. Some emerging, or specially optimized, general-purpose models can now achieve recall close to frontier models at drastically lower cost (e.g., roughly 70% cheaper while detecting only one fewer vulnerability).

    This reversal in value-for-money gives enterprise security architects new options:

    • Tiered scanning architecture: During daily CI/CD commits, use low-cost, high-throughput models for initial filtering; invoke expensive frontier models for deep review only before releases or for core assets.
    • RAG (Retrieval-Augmented Generation) for cost reduction: Instead of stuffing the entire codebase into the context window, use a vector database to pre-retrieve security-sensitive functions and external input points, and feed only relevant fragments to the LLM. This can cut token consumption by more than 80%.

    4. Enterprise-Grade Practices on Cloud-Native Infrastructure

    Turning these strategies into reality requires robust cloud-native infrastructure. Enterprises can build an automated security auditing system balancing high recall, high consistency, and low cost on mature cloud platforms such as Baidu AI Cloud.

    1. Task scheduling and containerized execution: Deploy scanning microservices on a container platform (e.g., CCE), scaling elastically based on commit volume to handle large-scale concurrent scans.
    2. Logging and monitoring/alerting: Deliver all LLM call logs, token consumption, and vulnerability recall details to a logging service (e.g., BLS). Monitor “stable hit rate” and “aggregated recall” in real time to dynamically adjust model routing. When a model’s consistency drops on a specific codebase, automatically trigger fallback or human-intervention alerts.
    3. Object storage and vector retrieval integration: Store code slices and vulnerability features from historical scans in object storage and build vector indexes. Before scanning, run similarity comparisons and reuse historical results for unchanged code blocks, significantly saving compute costs.

    5. Conclusion

    LLMs hold broad promise in security vulnerability detection, but “parameter worship” cannot guide real engineering practice. Test data shows that high multi-run aggregated recall masks weak single-pass detection and poor consistency. When adopting LLMs for security auditing, enterprises must establish a comprehensive evaluation matrix covering recall, variance stability, and per-token cost.

    Only through tiered model scheduling, structured output constraints, RAG-based context trimming, and tight integration with cloud-native infrastructure can enterprises achieve an optimal balance between detection effectiveness and cost in complex scenarios consuming billions of tokens.