Commit 82dd97047 for llama.cpp

commit 82dd9704742e8514088914b61d61fbcd35d599ee
Author: Aircg <64237451+cgair@users.noreply.github.com>
Date:   Tue Nov 24 17:54:31 2026 +0800

    server : fix skipped prompt cache lookups (#28992)

    * server : fix skipped prompt cache lookups

    Assisted-by: Claude Opus 5

    * server : let the slot scheduler ask the prompt cache

    Move the prompt cache lookup into server_slot_sched::select() so the
    plan alone decides whether the cache is updated, and the caller only
    applies it.

    find_better() and has_better() are now const, and find_better() also
    returns the common prefix, so load() no longer recomputes it.

    ---------

    Co-authored-by: Pascal <admin@serveurperso.com>

diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp
index 89f884e65..932d08bc7 100644
--- a/tools/server/server-context.cpp
+++ b/tools/server/server-context.cpp
@@ -2973,7 +2973,7 @@ private:

                     const int id_task = task.id;

-                    const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task));
+                    const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task), prompt_cache.get());

                     server_slot * slot = plan.id_slot == -1 ? nullptr : get_slot_by_id(plan.id_slot);

diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp
index fccfb709a..526a144c3 100644
--- a/tools/server/server-slot-sched.cpp
+++ b/tools/server/server-slot-sched.cpp
@@ -164,21 +164,21 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro
     return &states.back();
 }

-bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) {
+std::list<server_prompt_cache_state>::const_iterator server_prompt_cache::find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new, int & lcp) const {
     // a prompt made with another lora config is cleared before the new one starts, so it counts as empty
     const bool is_empty = prompt.tokens.empty() || lora_should_clear_cache(prompt.lora, lora_new);

-    int lcp_best = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new);
+    lcp = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new);

-    float f_keep_best = is_empty ? -1.0f : float(lcp_best) / prompt.tokens.size(); // empty slot: any cache entry wins
-    float f_sim_best  = float(lcp_best) / tokens_new.size();
+    float f_keep_best = is_empty ? -1.0f : float(lcp) / prompt.tokens.size(); // empty slot: any cache entry wins
+    float f_sim_best  = float(lcp) / tokens_new.size();

     SRV_TRC(" - looking for better prompt, base f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best);

-    auto it_best = states.end();
+    auto it_best = states.cend();

     // find the most similar cached prompt, that would also preserve the most context
-    for (auto it = states.begin(); it != states.end(); ++it) {
+    for (auto it = states.cbegin(); it != states.cend(); ++it) {
         if (lora_should_clear_cache(it->prompt.lora, lora_new)) {
             SRV_TRC("   - prompt with length %7zu, skipping, other lora config\n", it->prompt.tokens.size());
             continue;
@@ -199,15 +199,34 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok
         if (f_keep_best < f_keep_cur && f_sim_best < f_sim_cur) {
             f_keep_best = f_keep_cur;
             f_sim_best  = f_sim_cur;
-            lcp_best    = lcp_cur;
+            lcp         = lcp_cur;

             it_best = it;
         }
     }

-    if (it_best != states.end()) {
+    if (it_best != states.cend()) {
         SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best);
+    }
+
+    return it_best;
+}
+
+bool server_prompt_cache::has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new) const {
+    int lcp = 0;
+
+    return find_better(prompt, tokens_new, lora_new, lcp) != states.cend();
+}
+
+bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) {
+    int lcp_best = 0;
+
+    const auto it_found = find_better(prompt, tokens_new, lora_new, lcp_best);

+    // an empty erase gives a mutable iterator to the same entry, its prompt is moved out below
+    const auto it_best = states.erase(it_found, it_found);
+
+    if (it_best != states.end()) {
         const int64_t t_start = ggml_time_us();

         {
@@ -321,7 +340,7 @@ std::vector<int> server_slot_sched::get_free_slots(const std::vector<server_slot
     return res;
 }

-server_slot_plan server_slot_sched::select(const std::vector<server_slot_info> & slots, const server_task & task, const std::vector<common_adapter_lora_info> & lora) const {
+server_slot_plan server_slot_sched::select(const std::vector<server_slot_info> & slots, const server_task & task, const std::vector<common_adapter_lora_info> & lora, const server_prompt_cache * prompt_cache) const {
     const server_slot_info * ret = nullptr;

     bool update_cache = false;
@@ -392,7 +411,9 @@ server_slot_plan server_slot_sched::select(const std::vector<server_slot_info> &
         }

         if (ret != nullptr) {
-            const float f_keep = (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size();
+            // empty slot: nothing to keep, avoid 0/0
+            const float f_keep = ret->prompt->tokens.size() > 0 ?
+                (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size() : 0.0f;

             if (task.id_slot == -1) {
                 SLT_INF(*ret, "selected slot by LCP similarity, f_sim_best = %.3f (> %.3f thold), f_keep = %.3f\n",
@@ -424,7 +445,13 @@ server_slot_plan server_slot_sched::select(const std::vector<server_slot_info> &
     }

     // cache prompts only for the tasks that reuse them
-    update_cache = update_cache && !task.is_stateless();
+    if (prompt_cache == nullptr || task.is_stateless()) {
+        return { ret->id, false };
+    }
+
+    // the checks above only tell if the outgoing state is worth saving
+    // the cache can still hold a better start for this task, so ask it
+    update_cache = update_cache || prompt_cache->has_better(*ret->prompt, task.tokens, lora);

     return { ret->id, update_cache };
 }
diff --git a/tools/server/server-slot-sched.h b/tools/server/server-slot-sched.h
index fc0099dc0..f1be0fe2f 100644
--- a/tools/server/server-slot-sched.h
+++ b/tools/server/server-slot-sched.h
@@ -97,7 +97,14 @@ struct server_prompt_cache {

     server_prompt_cache_state * alloc(const server_prompt & prompt, size_t state_size_main, size_t state_size_drft);

+    // the cached state that is a better starting point than `prompt` for `tokens_new`, states.end() if none
+    // lcp: the common prefix of that state with `tokens_new`
     // lora_new: the lora config of the new prompt, the states made with another config are skipped
+    std::list<server_prompt_cache_state>::const_iterator find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new, int & lcp) const;
+
+    bool has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new) const;
+
+    // restore the result of find_better into the slot `id_slot`
     bool load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector<common_adapter_lora_info> & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot);

     void update();
@@ -130,5 +137,6 @@ struct server_slot_sched {
     std::vector<int> get_free_slots(const std::vector<server_slot_info> & slots, size_t n_slots_needed, int exclude_id_slot) const;

     // lora: the lora config of the task
-    server_slot_plan select(const std::vector<server_slot_info> & slots, const server_task & task, const std::vector<common_adapter_lora_info> & lora) const;
+    // prompt_cache: nullptr if disabled
+    server_slot_plan select(const std::vector<server_slot_info> & slots, const server_task & task, const std::vector<common_adapter_lora_info> & lora, const server_prompt_cache * prompt_cache) const;
 };
diff --git a/tools/server/tests/unit/test_completion.py b/tools/server/tests/unit/test_completion.py
index aa29454b1..1d58f9e2b 100644
--- a/tools/server/tests/unit/test_completion.py
+++ b/tools/server/tests/unit/test_completion.py
@@ -865,3 +865,68 @@ def test_completion_checkpoint_hybrid_swa():
     assert actual["timings"]["cache_n"] == len(prefix) + len(first["tokens"]) - 1
     assert actual["timings"]["prompt_n"] == len(suffix) + 1
     assert_same_output(actual, expected)
+
+
+# the prompt cache has to be consulted even when the selected slot already holds a usable prefix, and even when the slot was picked by id
+# ref: https://github.com/ggml-org/llama.cpp/issues/28139
+# ref: https://github.com/ggml-org/llama.cpp/issues/28276
+PROMPT_HEAD = "The capital of France is Paris. " * 2
+PROMPT_TAIL = "The river Seine runs slowly through the middle of the old stone city. "
+
+# PROMPT_SHORT is a strict prefix of PROMPT_LONG and covers more of it than the default --slot-prompt-similarity, so the slot is selected by the LCP loop
+PROMPT_SHORT = PROMPT_HEAD + PROMPT_TAIL*6
+PROMPT_LONG  = PROMPT_SHORT + PROMPT_TAIL*18
+PROMPT_OTHER = "Whiskers the cat climbed the tall oak tree behind the red barn. " * 12
+
+
+def prompt_cache_server():
+    global server
+    server.n_slots = 2
+    server.n_ctx = 2048
+    server.n_batch = 512
+    server.cache_ram = 512
+    server.start()
+
+
+def completion_cached(prompt: str, id_slot: int | None = None):
+    data = {"prompt": prompt, "cache_prompt": True, "n_predict": 0, "temperature": 0.0}
+    if id_slot is not None:
+        data["id_slot"] = id_slot
+    res = server.make_request("POST", "/completion", data=data)
+    assert res.status_code == 200
+    return res.body["timings"]["prompt_n"], res.body["timings"]["cache_n"]
+
+
+def test_prompt_cache_used_when_slot_pinned_by_id_is_empty():
+    global server
+    prompt_cache_server()
+
+    n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0)
+    assert n_cold > 100
+
+    # push the state of slot 0 into the prompt cache
+    completion_cached(PROMPT_OTHER, id_slot=0)
+
+    # slot 1 is empty, so f_keep has no meaning here - the cache still holds the exact state for this prompt and has to be used
+    n_pinned, n_cached = completion_cached(PROMPT_LONG, id_slot=1)
+    assert n_cached == n_cold - n_pinned
+    assert n_pinned < n_cold
+
+
+def test_prompt_cache_used_when_slot_holds_a_shorter_prefix():
+    global server
+    prompt_cache_server()
+
+    # warm slot 1 before the long state reaches the cache, otherwise this request would consume the cached entry itself
+    n_short, _ = completion_cached(PROMPT_SHORT, id_slot=1)
+
+    n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0)
+    assert n_cold > n_short
+
+    # push the long state of slot 0 into the prompt cache
+    completion_cached(PROMPT_OTHER, id_slot=0)
+
+    # slot 1 holds a prefix of PROMPT_LONG and would be reused as is, but the cache holds the whole state and is the better start
+    n_reuse, n_cached = completion_cached(PROMPT_LONG, id_slot=1)
+    assert n_cached == n_cold - n_reuse
+    assert n_reuse < n_cold - n_short