llama.cpp developer on retainer: llama_decode() without llama_kv_cache_clear() between requests accumulates KV cache state across users — prior user document fragments appear in subsequent responses — PII leakage — $65,000 — 2 months

llama.cpp b2370; C API; Python 3.11 via ctypes; Linux; 2× Intel Xeon E5-2699; n_ctx=4096; Mistral-7B-Instruct-v0.1.Q4_K_M.gguf; custom REST API; llama_decode() called without llama_kv_cache_clear(ctx) between HTTP requests; KV cache accumulates across all users; after ~10 requests (each ~400 tokens), cache full; truncation from beginning; prior users’ document fragments retained in KV; user B receives content from user A’s legal contract; PII leakage; fix: llama_kv_cache_clear(ctx) before each independent request • Northfield LlamaCpp Inference Ltd. (4-person; 2 months; 2.0h)

Northfield LlamaCpp Inference Ltd. is a 4-person AI startup that built a custom enterprise document Q&A API directly on the llama.cpp C API. They chose the C API over higher-level wrappers like llama-cpp-python to minimize Python overhead and to integrate with their existing C-based data pipeline. The server loaded Mistral-7B-Instruct-v0.1.Q4_K_M.gguf (4.1 GB), initialized a llama_context with n_ctx=4096 and n_threads=22, and handled each HTTP request by tokenizing the user’s document + query, calling llama_decode() on the token batch, and sampling until the end-of-sequence token. The server was used by 200 enterprise clients, each submitting proprietary documents for Q&A: legal contracts, financial reports, medical records, HR policy documents.

Two months after launch, three enterprise clients independently flagged that their Q&A responses contained verbatim text that could only have come from other clients’ documents. One client received a response that quoted a termination clause from what appeared to be a competitor’s contract. Another received a response that included salary figures from what appeared to be another company’s HR document. A third received a response referencing a drug name from an unrelated medical record. All three flagged potential data privacy breaches. One client terminated their contract immediately and initiated a legal review. The startup’s legal team was engaged.

The root cause: the per-request handler called llama_decode() but never called llama_kv_cache_clear(ctx) before processing each new independent request. The llama.cpp llama_context holds the KV cache as a stateful buffer across all llama_decode() calls on the same context. Each request’s tokens were appended to the KV cache’s used region. For the first 9–10 requests (each approximately 400 tokens, totaling ~4,000 tokens), new tokens were simply appended to the available KV cache space. At request 11, the KV cache was full at n_ctx=4096 used cells. llama.cpp’s default overflow behavior is to truncate from the beginning of the KV cache — discarding the oldest token positions to make room for the new request’s tokens. This means requests 11, 12, 13, and all subsequent requests were processed with KV cache entries from previous users still present in the KV buffer. The model’s attention mechanism could retrieve and incorporate content from prior users’ documents into the generated response for the current user.

/* llama_server.c — Northfield LlamaCpp Inference Ltd.
   llama.cpp b2370 | C API | Linux | Xeon E5-2699 */

#include "llama.h"
#include <string.h>

static struct llama_context *ctx = NULL;  /* single shared context */

/* Called once at server startup */
void server_init(const char *model_path) {
    struct llama_model_params mparams = llama_model_default_params();
    struct llama_model *model = llama_load_model_from_file(model_path, mparams);

    struct llama_context_params cparams = llama_context_default_params();
    cparams.n_ctx    = 4096;
    cparams.n_threads = 22;
    ctx = llama_new_context_with_model(model, cparams);
}

/* Called for every HTTP request (sequential, single-threaded) */
char *handle_request(const char *user_prompt) {
    /* BUG: missing llama_kv_cache_clear(ctx) here
       KV cache state from all previous requests persists in ctx
       Used cell count: request 1: 410, request 2: 805, ..., request 10: 4,050
       Request 11: n_ctx=4096 full; llama.cpp truncates from beginning
       Requests 11+ processed with prior users' document tokens in KV cache */

    /* Tokenize this request's prompt */
    llama_token tokens[4096];
    int n_tokens = llama_tokenize(llama_get_model(ctx),
                                   user_prompt, strlen(user_prompt),
                                   tokens, 4096,
                                   /*add_bos=*/true, /*special=*/false);

    /* Build batch and decode */
    struct llama_batch batch = llama_batch_init(n_tokens, 0, 1);
    for (int i = 0; i < n_tokens; i++) {
        llama_batch_add(&batch, tokens[i], i, /*seq_ids=*/{0}, /*logits=*/false);
    }
    batch.logits[batch.n_tokens - 1] = true;

    llama_decode(ctx, batch);  /* KV cache now contains all prior tokens + this prompt */

    /* Sample until EOS */
    char *output = generate_until_eos(ctx);
    llama_batch_free(batch);
    return output;

    /* KV cache used cells after each request:
       Request  1 (410 tokens): used=410
       Request  2 (395 tokens): used=805
       Request  3 (408 tokens): used=1213
       ...
       Request 10 (401 tokens): used=4050
       Request 11 (430 tokens): full — llama.cpp drops tokens 0-383
       KV cache now: [req2 tail][req3][req4]...[req10][req11 prompt]
       Model attention can read req2-req10 content while generating req11 response
       User 11's answer incorporates fragments from users 2-10's documents */
}

During the retainer engagement, the diagnostic required a single instrumentation step: printing llama_get_kv_cache_used_cells(ctx) at the start of each request handler. The output showed 0 for request 1, 410 for request 2, 805 for request 3 — monotonically increasing, never resetting to 0. By request 10, the used cells count was 4,050, nearly at the 4,096 limit. A controlled contamination test was run: request 5 was given a document containing the sentinel phrase SENTINEL_NORTHFIELD_7731. By request 15, the sentinel phrase appeared verbatim in the generated response to a completely unrelated query about a software license agreement. The contamination was reproducible with 100% consistency once the KV cache crossed the full threshold.

Fix: llama_kv_cache_clear(ctx) before every independent request

/* Fixed handle_request() — Northfield LlamaCpp Inference Ltd. */

char *handle_request(const char *user_prompt) {
    /* Fix 1: Clear KV cache before every independent request */
    llama_kv_cache_clear(ctx);
    /* llama_get_kv_cache_used_cells(ctx) now returns 0 for each request */

    /* Assertion for defense in depth */
    int used = llama_get_kv_cache_used_cells(ctx);
    if (used != 0) {
        fprintf(stderr, "ERROR: KV cache not empty at request start: %d cells\n", used);
        return NULL;  /* refuse to process — prevents contamination */
    }

    /* Tokenize and decode as before */
    llama_token tokens[4096];
    int n_tokens = llama_tokenize(llama_get_model(ctx),
                                   user_prompt, strlen(user_prompt),
                                   tokens, 4096, true, false);
    struct llama_batch batch = llama_batch_init(n_tokens, 0, 1);
    for (int i = 0; i < n_tokens; i++) {
        llama_batch_add(&batch, tokens[i], i, (llama_seq_id[]){0}, false);
    }
    batch.logits[batch.n_tokens - 1] = true;
    llama_decode(ctx, batch);
    char *output = generate_until_eos(ctx);
    llama_batch_free(batch);
    return output;
}

/* Fix 2: For multi-turn conversations, use sequence IDs to isolate sessions */
/* llama.cpp b2370+ supports llama_kv_cache_seq_rm() for session-level isolation */

void handle_multiturn_request(const char *prompt,
                               llama_seq_id session_id,
                               int session_token_count) {
    /* Only clear this session's tokens, not the whole cache */
    /* Other active sessions keep their KV cache intact */
    llama_kv_cache_seq_rm(ctx,
        session_id,          /* sequence ID to remove */
        session_token_count, /* p0: start position to remove from */
        -1);                 /* p1: -1 = remove to end */

    /* Encode only the new turn's tokens at the right position */
    struct llama_batch batch = llama_batch_init(MAX_NEW_TOKENS, 0, 1);
    /* ... tokenize and add new_tokens at position session_token_count ... */
    llama_decode(ctx, batch);
    llama_batch_free(batch);
}

/* Fix 3: Context pool for high-throughput servers */
/* Pre-allocate N contexts, one per concurrent request slot */
/* Each context is independently cleared between requests */
/* No shared mutable state between concurrent handlers */

#define POOL_SIZE 8
static struct llama_context *ctx_pool[POOL_SIZE];

struct llama_context *acquire_context() {
    /* Acquire a free context from the pool */
    struct llama_context *ctx = /* ... pool acquire logic ... */ NULL;
    llama_kv_cache_clear(ctx);  /* always clear before use */
    return ctx;
}

/* Results after Fix 1 (single-context server):
   KV cache used_cells at request start: always 0
   Sentinel contamination test (500 requests, 10 distinct document domains):
     Zero cross-document fragments detected
   Enterprise clients informed; audit closed; contract reinstated
   4 engineers × 2 months × $5,000/month + $25,000 legal/remediation = $65,000 */

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →