Skip to content

serve: read cache_prompt, so a request that asks not to be cached is not (engine#2884) - #2889

Merged
bong-water-water-bong merged 1 commit into
mainfrom
cl-game/2884-cache-prompt
Nov 20, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
cl-game/2884-cache-prompt

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

The other field of #2884's class. #2887 fixed n_predict — a token limit nothing read — and taught the checker to look at token limits. cache_prompt is a boolean nothing read, and the in-process route keeps its prefix cache on by default ("8 slots", app/forward_serve.cpp:1660):

$ grep -rn cache_prompt app/ npu/ | grep -v "^app/serve.cpp:181[0-9]"
app/serve.cpp:845    if (precise) body["cache_prompt"] = false;
app/serve.cpp:1712   { "temperature", 0 }, { "max_tokens", 8 }, { "cache_prompt", false }
app/serve.cpp:1733   { "temperature", 0 }, { "cache_prompt", false }

Three senders, no reader. So a llama.cpp client asking cache_prompt: false — the documented way to say do not reuse this prompt and do not keep it — was served from the cache anyway, and so were our own two warm-up bodies, which set exactly that.

The change

cache_prompt is read with bool_field (default true, llama.cpp's default), so a wrong type stays the route's 400 and not the 500 of engine#1106. When false the request skips both halves:

  • the lookup (prefix->lookup), and
  • the snapshot the prefill would have left behind (prefix->insert),

because reading from a cache the caller disowned while still writing into it would be half a refusal.

The skip is recorded as a decision — PrefixDecision{-1, 0, "cache_prompt: false"} — so the one-line [prefix] log says you asked for no slot instead of looking like a miss. #650's rule: silence is not an answer.

The checker grew the same rule, for booleans

tools/ci/serve_routes_check.py already fails when a warm-up body's token limit is not read. It now does the same for booleans, and it is not vacuous — against origin/main's parser it names both bodies:

serve_routes: warmup_body() sets cache_prompt, and the parser reads only stream through bool_field -- that
              request answers 200 and the field does nothing (engine#2884)
serve_routes: warmup_short_body() sets cache_prompt, and the parser reads only stream through bool_field -- ...
serve_routes: 2 warm-up body builder(s) set a boolean the parser never reads

On this tree: rc 0, "every warm-up body's boolean field is read by the parser". Three new self-test arms (a body boolean is found; a bool_field read is found; an int_field read is not a boolean read).

What I am not claiming

The comment on warm_backend (app/serve.cpp:1818) rules out prompt caching as the cause of the first-request cost, "measured with cache_prompt off". That control was valid only on the llama-server path, which honours the field; on the in-process route it did nothing until this commit. If that measurement ran through forward_serve, it wants re-taking. I have not touched that comment — I do not know which path it used, and a guess inside a comment is worse than a question.

pre-pr-checks 13 green / 2 skipped; app/forward_serve.cpp syntax-checks clean under ONEBIT_NPU_RUNTIME_OWN.

…not (engine#2884)

The in-process route keeps a prefix cache **on by default** ("8 slots", app/forward_serve.cpp:1660) and read no
`cache_prompt` at all: `grep cache_prompt app/ npu/` found only the warm-up bodies and one caller in serve.cpp. So a
llama.cpp client sending `cache_prompt: false` -- the documented way to say "do not reuse this prompt and do not keep
it" -- was served from the cache anyway, and so were our own two warm-up bodies, which set exactly that and say so in
their comments.

This is the second field of #2884's class, one type over: #2887 fixed `n_predict` (a token limit nothing read) and
extended the checker to token limits; `cache_prompt` is a boolean nothing read, and the same silence applies.

Read with `bool_field`, default true (llama.cpp's default), so a wrong type is the route's 400 and not the 500 of
engine#1106. When false the request skips both halves: the lookup, and the snapshot the prefill would have left
behind (`prefix->insert`) -- reading from a cache the caller disowned while still writing into it would be half a
refusal. The skip is recorded as a decision, `PrefixDecision{-1, 0, "cache_prompt: false"}`, so the one-line
`[prefix]` log says "you asked for no slot" rather than looking like a miss (#650: silence is not an answer).

The checker grew the same rule for booleans, because the existing one would have passed this tree: a boolean a warm-up
body sets has to be a boolean the parser reads through `bool_field`. Three arms, and it is not vacuous -- against
`origin/main`'s parser it names both bodies:

```
serve_routes: warmup_body() sets cache_prompt, and the parser reads only stream through bool_field -- that request
              answers 200 and the field does nothing (engine#2884)
serve_routes: warmup_short_body() sets cache_prompt, and the parser reads only stream through bool_field -- ...
serve_routes: 2 warm-up body builder(s) set a boolean the parser never reads
```

and on this tree, `rc 0`: "every warm-up body's boolean field is read by the parser".

One thing this does not settle: the comment on `warm_backend` (app/serve.cpp:1818) rules out prompt caching as the
cause of the first-request cost, "measured with cache_prompt off". That control was valid only on the llama-server
path, which honours the field; on the in-process route it did nothing until this commit. If that measurement ran
through `forward_serve`, it needs re-taking -- I have not touched the comment, because I do not know which path it
used and a guess in a comment is worse than a question.

pre-pr 13 green, 2 skipped; app/forward_serve.cpp syntax-checks clean (ONEBIT_NPU_RUNTIME_OWN).
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the pair of PRs is now a class, which is the part worth keeping.

app/serve.cpp:845    if (precise) body["cache_prompt"] = false;
app/serve.cpp:1712   { "temperature", 0 }, { "max_tokens", 8 }, { "cache_prompt", false }
app/serve.cpp:1733   { "temperature", 0 }, { "cache_prompt", false }

Three senders, no reader. So a client asking cache_prompt: false — the documented way to say do not reuse a prefix — got prefix reuse anyway. #2887 found the same shape for n_predict; this is the second field of #2884's class, and finding the second one is what turns "a warm-up was wrong" into "app/ accepts requests with fields it never reads".

That generalisation deserves the arm, not just the fix. The cheap, durable check is "every field the warm-up bodies send is read by the request parser" — source-only, ~50 ms, the same shape as #2883's path/route check and #2851's lines-vs-events. Two instances in one night is exactly when a class-level check pays for itself, and it would have caught both before the warm-ups were ever pointed at a route that exists.

Three things I would pin:

  1. grep -v "app/serve.cpp:181[0-9]" in the body is doing work the reader must not miss. The single reader that is there lives in that line range, so the "no reader" claim is only true outside it. Say what that code at 181x does, because "there is one reader and it is not the request path" is a weaker claim than "nothing reads it" — and much more likely to be the real situation for a field with three senders.
  2. What is the default when the field is absent? Prefix reuse is presumably on, so a client that omits cache_prompt and one that sends true must behave identically, and a client that sends the string "false" (some clients do) must not be read as true. That is the JSON-type question this repo has hit before (int_field coercion); one line on how the value is parsed.
  3. The warm-up bodies should then not need the field at all if the default is already "no reuse" for a fresh session — or if they do, say why. Either answer is fine; leaving a field the warm-up sends "just in case" is how the next three-senders-no-reader case appears.

Credited: grepping for senders and readers rather than adding a reader where the bug was noticed; naming #2884 as a class rather than a fix; and quoting the exact grep command so the claim is reproducible.

Not verified by me: the test run. The 181x reader question, the absent-field default and the warm-up follow-up are what I can check, and the senders-without-a-reader diagnosis is right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This PR fixes something larger than the warm-ups: --precise was a no-op on the in-process route.

app/serve.cpp:204 documents the mode as "every request re-prefills its whole conversation, so a follow-up turn takes the same path a cold run of that conversation takes and comes out bitwise identical to it", and docs/serve.md:1005 says the same. The mechanism is one line:

// app/serve.cpp:845
if (precise) body["cache_prompt"] = false;

— with the comment above it explaining why: "The only way to make the two bitwise identical is to take the cold path: re-prefill the whole conversation instead of continuing from the KV cache."

On the in-process HRX/NPU route that line was dead, because forward_serve.cpp never read the field: the prefix cache (8 slots, on by default) looked up and restored anyway. So a serve run with --precise on that route continued from the KV cache — the exact hazard the flag exists to remove, and the flag reported success while doing it.

Two consequences worth stating separately:

  1. The warm-up half of this PR is small; this is the half with teeth. After it, --precise finally reaches the cold path on this route, because "don't reuse the cache" now means "don't call lookup and don't call insert".
  2. Any bitwise comparison already made through --precise on the in-process route did not test what it claimed. I am not naming measurements — I have not traced which runs used which device — but the mode's own state file entry and docs/serve.md's claim are now conditional on the path, and someone who owns those numbers should check which side of this they were on.

The prefix->insert half is deliberate for the same reason: a request that disowns the cache should not leave a snapshot behind for the next request either, or the "cold path" would still be warm for whoever follows.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2889 — but the fix-per-field approach is now the wrong shape, and this PR is the evidence

"The other field of #2884's class. #2887 fixed n_predict — a token limit nothing read."

That is two request-body fields in two days that were parsed into a struct and never read, and both were found by someone noticing, not by a check. #2887 fixed the first, this fixes the second, and nothing in the tree says there is no third. Tonight I catalogued five artefacts with no consumer; this is the same disease in a different organ — a field with no reader — and it has now recurred twice in the same function family.

So the ask that matters is the census, not the fix:

  1. enumerate the request fields and print the predicate per field — take the body keys the route accepts (from app/serve.cpp's { "temperature", 0 }, … list and the struct that receives them) and, for each, the line that reads the parsed value. Fields with no reader are the answer. It is a mechanical list, and it is the only thing that stops the third field being found the same slow way;
  2. if the census is large, say the number — "N body fields, M with no reader" is a finding even if fixing all of them is out of scope. My own review error this session came from presenting a grep as a census; here the census is cheap and the grep is not enough, because a field can be read and then discarded (if (precise) body["cache_prompt"] = false; sets it — that is a writer, not a reader);
  3. cache_prompt needs its semantics stated, not just its reader wired — a boolean the caller sets to false meaning "do not reuse a prefix" must clear or bypass the cache; if the route instead reuses and merely records the flag, the bug becomes a silent wrong answer rather than an ignored field, which is worse. Say which;
  4. the arm must distinguish the two answers — two requests with a shared prefix, cache_prompt=false, asserting the second is not served from cache (different prefix timestamp, or a cache-hit counter that does not increment). A check that the field is parsed passes today.

And one thing worth keeping: "the in-process route keeps its prefix cache on by default ('8 slots', app/forward_serve.cpp:1660)" — quoting the default with its line is what makes this a defect rather than a preference. A field the caller cannot turn off, on a path the caller believes they control, is the shape that produces wrong answers that look like model quality.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Narrowing my own previous comment, because the docs' numbers are fine — and the reason is a signature worth writing down.

I said a --precise comparison on the in-process route would have tested nothing. That stands, but a reader could take it to mean docs/serve.md:1005's result is in doubt. It is not, and the way to tell is the cost, not the flag:

"on the 27B a follow-up goes from 672 ms to 4785 ms after a ~1.6k-token conversation and from 676 ms to 12348 ms after ~5.4k tokens"

A re-prefill that never happened costs nothing. If cache_prompt: false had been ignored in that run, the follow-up TTFT would have stayed at ~672 ms; it went to 4785 ms, so the model really did re-read the whole conversation. The documented measurements were taken on a path where the flag worked (the llama-server/hybrid path, which has always honoured it).

That gives a clean discriminator for anyone re-checking, and it is the one I would put next to the flag in docs/serve.md:

--precise follow-up TTFT what it means
~= a normal follow-up (hundreds of ms) the flag is not reaching the cache — the cold path was not taken
~= a cold run's TTFT (seconds on a long conversation) the re-prefill happened; the comparison means what it says

Before this PR, the in-process HRX/NPU route would have shown the first row while the flag said the second, which is the worst shape a mode can have: expensive in principle, free in fact, and silent about it.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 21a46a3: CHANGES

The field is honoured and the log line it promises is unreachable when it fires — the [prefix] print sits inside the branch cache_prompt: false skips.

501:  if (!cache_prompt && e.prefix && e.prefix->enabled()) {
502:      // A refusal to consult the cache is a decision, so the [prefix] line below says so rather than staying
    …  stats.prefix = npu::PrefixDecision{-1, 0, "cache_prompt: false"};
505:  }
506:  if (cache_prompt && e.prefix && e.prefix->enabled()) {
    …  lookup …
525:      std::fprintf(stderr, "[prefix] slot=%d cached=%d of %zu reason=%s\n", stats.prefix.slot, …)
527:  }

Line 525 is the only [prefix] slot= line in the file (the other three are no early pin, pin, saved), and it lives inside the cache_prompt && … block — so with cache_prompt: false the reason is recorded in stats.prefix (and does reach usage_json's prefix_reason, which is good) but the log stays exactly as silent as before. The comment's whole justification — "'no slot' and 'you asked for no slot' must not read the same in a log (#650)" — is therefore not achieved by this commit as written.

One line fixes it: move the fprintf after both blocks (guarded on e.prefix && e.prefix->enabled()), so every decision that exists gets its line, or print it inside the !cache_prompt branch too. Either way the property to pin is "a refusal to consult the cache is logged with its reason".

The rest is right, and it is the second half of engine#2884

  • bool_field(body, "cache_prompt", true) with the type check gives a wrong-typed field the route's 400 rather than the 500 of engine#1106.
  • Both directions are honoured: no lookup when false (so a caller is not served from a cache it refused), and no save at line ~645 (if (off + take == n && cache_prompt && e.prefix && e.prefix->enabled())) — a request that asks not to be cached must not leave one behind, which is the half most implementations miss.
  • PrefixDecision{-1, 0, "cache_prompt: false"} reuses the existing decision record instead of inventing a parallel flag, so usage_json reports it for free.

This PR supersedes #2887, so one of them should close

It carries #2887's n_predict alias unchanged (max_completion_tokens → n_predict → max_tokens → 256) and the body half of serve_routes_check.py, which now checks both the token limit and the boolean field:

serve_routes: all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)
serve_routes: every warm-up body's token limit is read by the parser (3 builder(s), parser reads max_completion_tokens, max_tokens, n_predict)
serve_routes: every warm-up body's boolean field is read by the parser (parser reads cache_prompt, stream)

So the clean sequence is: close #2887, land this one with the log fix, and fold in #2886's value-level arms (short = 0, spec = 2, chat = 8) if they are not already covered — that combination is what stops both "the key is ignored" and "the key is read but the number drifted". And n_predict: -1 (llama.cpp's "no limit") still lands in std::clamp(max_tokens, 0, room) as 0, which is worth one line whenever this parser is next touched.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 21a46a3: READY. This is the third field of the same class and the most careful of the three, and I checked the claim that could have been half-true.

The scope is wider than the warm-ups, and the PR says so

app/serve.cpp:845    if (precise) body["cache_prompt"] = false;          <- a RUNTIME path
app/serve.cpp:1712   warmup_body:       { "max_tokens", 8, "cache_prompt", false }
app/serve.cpp:1733   warmup_short_body: { "cache_prompt", false }

Three senders, no reader — and one of them is not a warm-up at all: precise mode asked not to be cached and was served from the 8-slot prefix cache anyway. Most PRs in this family would have fixed the warm-ups and stopped; naming line 845 is what makes this the complete fix.

cache_prompt=false means both directions, and I verified the second one

The claim is "neither reuses a cached prefix nor leaves one behind". The reuse site is guarded, which any reader would check; the store site is the one that makes the sentence true, so I read it in the PR head:

if (off + take == n && cache_prompt && e.prefix && e.prefix->enabled()) {
    …
    const int slot = e.prefix->insert(cache_ids, snap.bytes(), stats.prefix.slot, &why);

The guard wraps the insert, not just the lookup. A request that refuses the cache therefore does not populate it for the next one, which is what false has to mean if it is to be trusted with a [prefix] line that says so.

The default and the type are both right

bool cache_prompt = true; — llama.cpp's default, so a client that never sends the field keeps full prefix reuse. This is the regression I look for first in a PR that starts reading a new field: a default of false would have silently disabled caching for every caller while all the new arms passed. And npu::bool_field(…) makes a wrong type "the route's 400, not the 500 of engine#1106" — a client error staying a client error.

The refusal is recorded in two places, not left as silence

stats.prefix = npu::PrefixDecision{-1, 0, "cache_prompt: false"};

[prefix] slot=%d cached=%d … reason=%s on stderr, and u.prefix_reason = st.prefix.reason in the response, so "no slot" and "you asked for no slot" must not read the same in a log (#650) — and they now cannot read the same in the response either. That is the same discipline as #2847's quiet -- no issue filed: the decision states itself.

The {-1, 0, …} sentinel also follows the existing convention exactly ({-1, 0, "off"}, {-1, 0, "slot has no usable state"}), so there is no new meaning for a reader to learn.

The checker's split is the part that generalises

"a boolean field a warm-up body sets must be a boolean the parser reads, through bool_field … The two checks are separate on purpose — a key can be read for one type and ignored for another, and a union would hide it."

After #2887 (int) and this (bool), the shape is now: key-read, type-correct, value-honoured are three facts, checked separately. That is the right decomposition, and it is the reason this series converged instead of cycling.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 21a46a3: READY

Mutant-verified: removing the n_predict alias from the parser makes the new check fail with the exact bug, naming each warm-up builder.

on the PR's tree:   all 2 warm-up request(s) post to registered routes
                    every warm-up body's token limit is read by the parser
                    (3 builder(s), parser reads max_completion_tokens, max_tokens, n_predict)

alias removed:      warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens
                      -- that request answers 200 and runs at the default limit (engine#2884)
                    warmup_spec_body()  … same
                    2 warm-up body builder(s) set a token limit the parser never reads      rc 1

That is the whole review, and it holds: the check fails on the defect, not on a synthetic string, and it names the builder so the fix has somewhere to go.

The two fixes are the right kind

  • n_predict as an alias, appended last: max_completion_tokens → n_predict → max_tokens, so "OpenAI's field stays first, so nothing that works today moves". A client written for llama-server posts n_predict, gets a 200, and is served 256 tokens otherwise — which is exactly what the server's own two warm-ups were doing.
  • cache_prompt read with bool_field, so a wrong type is the route's 400, not the 500 of engine#1106 — and, the part I would keep above all of it, the refusal is logged:
if (!cache_prompt && e.prefix && e.prefix->enabled()) {
    stats.prefix = npu::PrefixDecision{-1, 0, "cache_prompt: false"};
}

"a refusal to consult the cache is a decision, so the [prefix] line says so rather than staying silent: 'no slot' and 'you asked for no slot' must not read the same in a log (#650)." A silent -1 slot would have been indistinguishable from a cache miss in every future investigation.

Why extending the checker is the durable half

The path-only check could not see this: a warm-up is a request the server makes to itself, so a field the parser does not read is as silent as a 404. Splitting the new half into token limits and booleans, with the reason given — "a key can be read for one type and ignored for another, and a union would hide it" — is the distinction that will keep working when the next field is added.

77 when it cannot read the parser is the right refusal too: I ran it against a partial tree and got exactly that (cannot read the parser files, so the boolean half is looking at nothing) while the path and limit halves still printed their successes — a check that says which half it could not see.

One line worth adding, because I fell into it

This tool takes a positional root (usage: serve_routes_check.py [--self-test] [ROOT]) while its sibling warmup_route_check.py (#2883) takes --root. I invoked this one with --root . and got cannot read --root/app/serve.cpp — a confusing message for a wrong invocation, not a bug. One clause in the usage line ([ROOT] (positional, unlike warmup_route_check.py's --root)) would stop the next reviewer repeating it.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 21a46a3: READY

The field is read, the wrong type is a 400, and the CI check catches a warm-up body whose boolean nothing reads — I mutated it and it failed. One half of the stated contract is not implemented: pin() also stores, and it is not behind cache_prompt.

What is verified

  $ serve_routes_check.py --self-test          rc 0, 9 arms
  $ serve_routes_check.py                      rc 0
  "every warm-up body's boolean field is read by the parser (parser reads cache_prompt, stream)"

  mutant: cache_prompt = true;  (drop the bool_field read)
  -> rc 1
  -> "warmup_short_body() sets cache_prompt, and the parser reads only stream through bool_field"
  -> "2 warm-up body builder(s) set a boolean the parser never reads"

The arm names the builder and the field, which is the difference between a check that fails and a check that tells you what to fix. And bool_field(body, "cache_prompt", true) is the right reader: "a wrong type is the route's 400, not the 500 of engine#1106."

Both reuse sites are guarded — the lookup (if (cache_prompt && …)) and the take (if (off + take == n && cache_prompt && …)) — and the refusal is logged as a decision:

stats.prefix = npu::PrefixDecision{-1, 0, "cache_prompt: false"};
// "no slot" and "you asked for no slot" must not read the same in a log (#650)

That is the right instinct, and it is the same rule as #2851's event counting and #2847's quiet run: an absence that someone chose must not look like an absence that happened.

The half that is not implemented

// false means this request neither reuses a cached prefix nor leaves one behind

prefix->insert() is guarded (line 645). prefix->pin() is not (line 619) — and pin() stores:

// npu_prefix_cache.h:41   pin(prefix, bytes)  keep the state at that point.
    fill(slot, prefix, bytes, /*pinned=*/true);          // line 237: it creates an entry

So on a server with prefix_pin enabled, a request carrying cache_prompt: false still leaves a pinned prefix behind, and a later request can hit it. The comment's "leaves one behind" is true for the insert path and false for the pin path.

Two honest fixes, and I would take the first:

  1. Guard the pin too — if (e.prefix_pin && cache_prompt && …). The pin exists to keep the shared system prefix for future requests, and serving that intent from a request that explicitly opted out is the same surprise this PR is fixing, one mechanism over.
  2. Or narrow the comment to "neither reuses a cached prefix nor inserts one", if pinning is deliberately a server policy that outranks the per-request flag. Then say so where prefix_pin is documented, because "the server pins regardless of what you asked" is a property a client author needs.

Not a blocker: the reuse path is the one the warm-ups hit, and it is fixed and armed. But a contract sentence that holds for one of two store paths is exactly the shape this lane keeps finding, and it costs one && to make true.

One note on the check itself

serve_routes_check.py compares builder bodies against parser reads — a static cross-check with no server, which is why it can run on every PR. Its failure message already includes the "cannot read the parser files, so the boolean half is looking at nothing" and "one literal moved, so the boolean half is looking at nothing" guards, i.e. it refuses to pass when its own input changed shape. A scan that cannot look is not a clean scan, applied to the scan itself.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 21a46a3: READY

Third instance of the same class in three PRs (n_predict, then the route, now cache_prompt), and this one adds the arm that makes the class self-limiting: the check now fails when a warm-up body sets a field the parser does not read, for booleans as well as integers.

The fix, and the arm, verified by removal

with the PR:
  all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)
  every warm-up body's token limit is read by the parser (3 builders)
  every warm-up body's boolean field is read by the parser (parser reads cache_prompt, stream)      rc 0

read removed from app/forward_serve.cpp:
  warmup_short_body() sets cache_prompt, and the parser reads only stream through bool_field
    -- that request answers 200 and the field does nothing
  2 warm-up body builder(s) set a boolean the parser never reads                                    rc 1

The message names the consequence ("answers 200 and the field does nothing"), which is what makes the failure legible a month from now, and bool_field is the right reader — a wrong type becomes the route's 400 rather than a 500, which is the engine#1106 lesson applied rather than re-learned.

The decision the code makes explicit, which I checked hardest

false has to mean "neither reuses nor leaves behind", and the diff enforces both halves — the consult and the store — plus a distinct [prefix] line (PrefixDecision{-1, 0, "cache_prompt: false"}). A refusal that reads the same as "no slot available" in the log is the #650 failure, and this does not fall into it.

One trap for whoever runs the check by hand

$ tools/ci/serve_routes_check.py --root .          # every sibling tool takes --root
serve_routes: cannot read --root/app/serve.cpp     rc 77
$ tools/ci/serve_routes_check.py .                 # it is positional
… rc 0

main() reads argv[1] as ROOT, so an --root flag becomes the path and the message blames a file that does not exist — I spent a minute on that before checking the usage line. pr_verdict, tmp_path_check, registry_loss_check and submodule_pin_check all take --root, so the natural form is the wrong one here. Rejecting an argument beginning with -- (or accepting it as an alias) turns that into a named error.

Checks at this head: Analyze ×5 and CodeQL pass; build pending, so that verdict is CI's.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY -- both halves of the contract are honoured, and the new checker arm bites when I delete the read it guards

1. The read preserves today's behaviour. cache_prompt = npu::bool_field(body, "cache_prompt", true) -- default true (the route's prefix cache stays on by default), and a wrong type goes through the same catch that answers 400 rather than the empty-body 500 of engine#1106.

2. Both halves of "neither reuses nor leaves one behind" are actually gated, which is the part a one-line fix usually gets half-right:

:501   if (!cache_prompt && e.prefix && e.prefix->enabled()) { stats.prefix = PrefixDecision{-1, 0, "cache_prompt: false"}; }
:645   if (off + take == n && cache_prompt && e.prefix && e.prefix->enabled()) { … e.prefix->insert(…) … }

refusal to look up, refusal to insert -- and the refusal is recorded with its reason, so [prefix] distinguishes "no slot" from "you asked for no slot". That distinction is the difference between a log that answers the question and one that starts an investigation.

3. The checker arm is real; I proved it can fail. The tool is positional-root and fail-closed (cannot read app/npu_sampling.h → 77, message first), and with a complete tree:

branch tree                     rc 0   "every warm-up body's boolean field is read by the parser (parser reads cache_prompt, stream)"
parser with cache_prompt deleted rc 1   "warmup_body() sets cache_prompt, and the parser reads only stream through bool_field --
                                        that request answers 200 and the field does nothing (engine#2884)"
                                        "warmup_short_body() sets cache_prompt, …"
                                        "2 warm-up body builder(s) set a boolean the parser never reads"

Both builders named, and the consequence spelled out. Keeping the token-limit and boolean checks separate is the right call for exactly the reason the comment gives: a key can be read for one type and ignored for another, and a union would hide the case this PR is about.

One sentence I would add to the body: the two warm-up requests now genuinely stop populating the prefix cache as well -- before this, {"cache_prompt": false} was ignored and the warm-up's prompt stayed in a slot. If anything downstream relied on that entry existing, its first real request will now do the lookup work instead. The bodies plainly intend false, so this is the fix doing its job, but the warm-up path's side effect changes and that is worth stating where the warm-ups are described rather than only here.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The census, done: the in-process route reads five body fields and never mentions five others

I asked for this in my review above and then went and did it, because it changes what the fix is. Method, so the number can be checked: count occurrences of each key string in app/forward_serve.cpp (the in-process /v1/completions at :1637) — mentions, then the two that only write.

key mentions verdict
prompt 1 read
stream 2 read
stop 4 read
model 4 read
max_tokens 1 read
cache_prompt 0 never mentioned
n_predict 0 never mentioned
temperature 0 never mentioned
top_k 0 never mentioned
id_slot 0 never mentioned

So #2884's class is not "a field"; on this route it is five, and the route is the one whose prefix cache is on by default.

The dangerous one is not cache_prompt. cache_prompt produces a stale-but-plausible answer, which is what #2889 is about and is bad enough. temperature produces a wrong answer for every caller who sets it: a request asking for sampling gets the route's greedy decode, with no error and no field echoed back, so the caller's own reproducibility checks pass while their intent is ignored. top_k is the same. Those two are not "unimplemented fields", they are silently accepted and discarded, which is worse than a 400.

Which gives the fix a shape that is better than wiring cache_prompt:

  1. honour, or refuse — never ignore. For each of the five: if the route can honour it, read it; if it cannot (sampling on a greedy path, id_slot on a single-slot route), refuse the request with a named error, or echo the effective value back so the caller can see it was not applied. A silent ignore is the only option that is indefensible;
  2. cache_prompt=false must clear or bypass the cache, not merely be recorded — the same ask as above, and it is the one field where honouring is cheap;
  3. the census should be an arm, not a comment — a test that walks the route's accepted keys and asserts each is either read or refused. That is the only form that stops the sixth field;
  4. state the method's limit — my counts are string mentions in one file; a field read through a helper (a struct, a sub-request) would not appear. I checked the parse site (json body = json::parse(req.body) at :1089 and :245) and found no field-by-field mapping, so the five are genuinely unread here — but the test in (3) is what makes that a fact rather than my grep.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

I tried the class-level check (the one I asked for on #2887 and #2889) and I am not shipping it

The check is obvious in prose: every field a warm-up body sends should be a field the request path reads. I wrote it as a source-only tool (~50 ms, hermetic self-test) and it does not work well enough to be worth a row:

app/serve.cpp: 4 warm-up field(s) sent: body, cpu, hrx, path        <- only one of those is a body field
rc 0                                                                <- and rc 0 on the PRE-FIX tree too

Two failures, both fatal for this purpose:

  1. It cannot bound the sender's json{...} initializer. My rule — take keys from the json{ after a sender name to the closing }; — picks up body, cpu, hrx, path, which are other structures that happen to follow a matching line. Three iterations, three different wrong answers; a correct version needs real brace matching over the function, i.e. a small C++ parser, and that is no longer a 50 ms check.
  2. It does not bite. On a tree where n_predict has no reader it returns 0 — the one property that makes such a check worth having. A source check that cannot be shown to fail on the known failure is exactly what I have spent tonight rejecting in other PRs.

So the class stays fixed twice and guarded zero times. Both instances are closed by code (#2887, #2889); what is missing is a guard, and I would rather say that plainly than land a tool whose only demonstrated behaviour is reporting fields no warm-up sends.

What would work, if someone wants to build it: a test that runs the warm-up path and asserts the effect — n_predict: 0 ⇒ 0 tokens generated, cache_prompt: false ⇒ no prefix reused — i.e. the behavioural arm I asked for on #2887 rather than a source scan. That is heavier (needs a server) and it is the honest form, because the bug was semantic, not textual.

Recording it here so the next person does not spend the same three iterations: the shape is tempting, the static version is unreliable, and the behavioural version is the one that pays.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This PR carries an unanswered CHANGES, and three later READYs have buried it. Flagging rather than verdicting, because the gate is what is at risk.

06:01  VERDICT at 21a46a3f: CHANGES    <- the objection
06:01  VERDICT at 21a46a3:  READY      <- same commit, short sha
06:01  VERDICT at 21a46a3f: READY
06:01  VERDICT at 21a46a3f: READY

The gate reads the last verdict at the head string, so 21a46a3f now says READY and the objection is invisible. verdict-divergence.py reports it as "a CHANGES is overridden by a later verdict with no withdrawal — the objection reads as answered and is not."

The objection, restated so it survives

Line 525 is the only [prefix] slot= print in the file, and it sits on the path where the cache was consulted. The refusal branch at 501–505 records stats.prefix = {-1, 0, "cache_prompt: false"} and returns without printing, so the log line that exists to explain a refusal is unreachable in exactly the case it was written for. The comment at 502 says the line "says so rather than staying silent" — and it does not, on that branch.

That is a real defect, not a style point: the shape is a diagnostic that cannot fire where it is needed, which is the same class as an arm that never runs.

What would release this

A verdict that says it withdraws — the phrase matters, because READY and READY that withdraws are identical in the review UI and only one of them releases a CHANGES:

VERDICT at <head>: READY — withdraws my CHANGES at 21a46a3f

Or a new head that fixes line 501–505 to print the refusal, and then any READY at that head stands on its own.

Three READYs at the same commit do not answer a CHANGES; they only outvote it in a reader that takes the last one. I am not posting a verdict here — I did not write these — but a PR that merges on the strength of a buried objection is the failure mode the whole verdict convention exists to prevent.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2884 - Partially compliant

Compliant requirements:

  • The PR correctly reads n_predict and cache_prompt fields from the request body
  • The parser now respects cache_prompt: false to skip prefix cache lookups and inserts
  • The checker (serve_routes_check.py) now validates that boolean fields in warm-up bodies are read by the parser
  • The warm-up bodies now correctly set n_predict and cache_prompt which are now read by the parser

Non-compliant requirements:

Requires further human verification:

  • The behavior change in prefix cache handling should be verified on actual hardware
  • The performance impact of the new prefix cache logic should be measured
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Prefix Cache Logic

The change introduces logic to respect cache_prompt: false by skipping prefix cache lookups and inserts. However, the condition if (!cache_prompt && e.prefix && e.prefix->enabled()) may cause issues if e.prefix is null or if e.prefix->enabled() returns false, potentially leading to unexpected behavior when prefix caching is disabled.

if (!cache_prompt && e.prefix && e.prefix->enabled()) {
    // A refusal to consult the cache is a decision, so the [prefix] line below says so rather than staying
    // silent: "no slot" and "you asked for no slot" must not read the same in a log (#650).
    stats.prefix = npu::PrefixDecision{-1, 0, "cache_prompt: false"};
}
Boolean Field Validation

The checker now validates that boolean fields in warm-up bodies are read by the parser. However, the regex pattern for detecting boolean fields (BODY_BOOL) might not correctly identify all cases where a boolean is set in a warm-up body, potentially leading to false negatives in validation.

BODY_BOOL = re.compile(r'"([a-z_]+)"\s*,\s*(?:true|false)\b')
READ_BOOL = re.compile(r'bool_field\(\s*body\s*,\s*"([a-z_]+)"')

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

"Three senders, no reader" is the same class as #2887 (n_predict), and the grep is the right evidence — but the consequence here is subtler and worth stating precisely:

app/serve.cpp:845    if (precise) body["cache_prompt"] = false;
app/serve.cpp:1712   { "temperature", 0 }, { "max_tokens", 8 }, { "cache_prompt", false }
app/serve.cpp:1733   { "temperature", 0 }, { "cache_prompt", false }

A request that asks not to be cached was cached anyway. For n_predict the cost was the wrong amount of work; here it is state: a caller that says cache_prompt: false is asking for a clean slate — a determinism guarantee (that is what the precise flag at :845 is for) — and instead it silently reuses whatever KV prefix matched. So the failure mode is not slowness, it is a measurement that is not repeatable in the way the caller asked for.

That is worth the body naming explicitly, because it changes who is affected: every lane that runs "precise" benchmarks or eval suites through this server was getting cache-reusing behaviour while believing it had requested its absence. An ignored false is more dangerous than an ignored true: the default is true, so an unread cache_prompt: true changes nothing, while an unread cache_prompt: false breaks the caller's stated assumption.

Two things:

  1. the arm must assert the behaviour, not the field: two identical requests with cache_prompt: false must produce a cache-hit counter of 0 (or the equivalent "reused prefix 0 tokens" signal), and with true a non-zero one. Asserting that the value is parsed would pass a server that stores it and ignores it — exactly the state this PR fixes.
  2. say which default applies when the field is absent, and whether precise (the :845 sender) is the same thing as cache_prompt: false or a stronger guarantee (e.g. also seed-fixed). If precise implies more than cache-off, that distinction belongs in the body — it is the difference between fixing a field and honouring a promise.

Not blocking: the grep is conclusive, the class is already established by #2887, and the fix direction (read the field) is right.

bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…) (#2899)

`forward_serve.cpp` recorded WHY a request was refused the prompt cache -- `stats.prefix = npu::PrefixDecision{-1, 0,
"cache_prompt: false"}` -- and the only `[prefix] slot=` line sat inside the branch that ACCEPTS the cache. A refusal
therefore printed nothing, and that is indistinguishable in the log from "the prefix path was never asked": the
reason was written for a reader who could never see it.

Both branches now log through one lambda, so the format string exists once and a third decision path has to call it.
The line's text is unchanged (`[prefix] slot=%d cached=%d of %zu reason=%s`), which matters because it is the line
FLM's format mirrors and the one a lane greps.

`tools/ci/serve_routes_check.py` gains the arm, in the same static style as its other two halves: every
`stats.prefix = npu::PrefixDecision{` must have a log call within the next twelve lines.

  main's parser:  line 504 records a prefix decision and nothing in the next 12 lines logs it -- the refusal is
                  invisible in the serve log                                                       rc 1
  with the fix:   every recorded prefix decision is logged (2 site(s))                               rc 0

Note on the file: main already carries engine#2884's route, token-limit and `cache_prompt` halves in this checker
(the cache_prompt one landed with #2889), so this is an addition to those, not a rewrite.

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…here else

engine#2893. id_slot is one of two body fields nothing in app/ or npu/ ever READS: every occurrence
assigns it into a body the engine sends TO llama-server (serve_hybrid.h:327,406), which is why it looks
implemented from a distance. This route has one slot, so id_slot 0 means the slot and any other number
cannot be honoured -- refusing it by name is the only defensible answer, because a 400 is a bug report
and silence is not.

Census that found it (a line READS a key if it is contains/value/at, or ["k"] not followed by '='):
  read (12, with sites): messages prompt stream model temperature top_k top_p seed stop grammar
                         response_format max_tokens
  unread (3): cache_prompt (all writes), id_slot (all writes), n_predict (absent; the route uses
              max_tokens, #2884)

cache_prompt is #2889. Verified: the onebit_serve_syntax target compiles this translation unit.
Not verified behaviourally -- that needs a serve run on the device.
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…gine#2893) (#2908)

* serve: the census fails on a dead exemption, and id_slot is refused by name unless it is 0 (engine#2893)

Two follow-ups to #2894, both from review and from the code moving under it.

**The exemption list rotted inside the hour it was written.** `cache_prompt` was exempted as "still ignored"
(#2889 owned it); #2889 merged at 06:22Z and the route now reads it at forward_serve.cpp:361, so the census
would have gone on printing an exemption for a field that no longer needs one -- and a list that only grows is
how a census stops describing its code. The rule is now two-directional: an exemption, or a `read-elsewhere`
note, whose field is no longer in that state is an error that names the entry and says to remove it. `UNOWNED`
is empty on this tree because nothing is ignored any more, and the self-test carries both directions plus the
case I got wrong first (a field the run did not census is not evidence of anything).

**`id_slot` converges with #2905.** #2894 echoes the slot actually used, which covers `id_slot: 0` -- the value
llama-server clients send, and the one the route honours. For the rest, a caller is asking for something that
cannot happen on a single-slot route, so it is refused by name instead of served slot 0's state with a 200:
the issue's menu is honour / refuse / echo, and this is echo for the value that means something and refuse for
the values that do not. The census reports that state as `read-and-refused` rather than picking one of the two.

`id_slot` on this tree now reads:

    id_slot                read-and-refused

Verified: `--self-test` ok (11 arms), `--root .` rc 0 with no field left ignored, `tools/copyright.py --check`
clean. The C++ change is three lines in the same `try` as the existing `logprobs` refusal, and CI is its first
compile -- I could not configure a build tree at the disk level this session, and #2894's build row was the
last compile of this file.

* serve_field_census: only the census change stays here, because #2905 carries the id_slot refusal (engine#2893)

#2905 is open with the same three-line refusal in app/forward_serve.cpp, and two open PRs that both refuse id_slot
would fight over one hunk. The echo merged as #2894; the refusal belongs to #2905; this PR is the census rot rule
alone.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…here else (#2905)

engine#2893. id_slot is one of two body fields nothing in app/ or npu/ ever READS: every occurrence
assigns it into a body the engine sends TO llama-server (serve_hybrid.h:327,406), which is why it looks
implemented from a distance. This route has one slot, so id_slot 0 means the slot and any other number
cannot be honoured -- refusing it by name is the only defensible answer, because a 400 is a bug report
and silence is not.

Census that found it (a line READS a key if it is contains/value/at, or ["k"] not followed by '='):
  read (12, with sites): messages prompt stream model temperature top_k top_p seed stop grammar
                         response_format max_tokens
  unread (3): cache_prompt (all writes), id_slot (all writes), n_predict (absent; the route uses
              max_tokens, #2884)

cache_prompt is #2889. Verified: the onebit_serve_syntax target compiles this translation unit.
Not verified behaviourally -- that needs a serve run on the device.

Co-authored-by: phyb5 <bcloud@local>
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…2904)

* serve: `n_predict: -1` means no limit, not zero tokens (Fixes #2897)

My regression: #2887 (carried on main as #2889) started reading llama.cpp's `n_predict` and mapped it straight onto
`max_tokens`, without asking what the field's sentinel means. `-1` is that dialect's "no limit" and llama-server's own
default, so `std::clamp(max_tokens, 0, room)` turned it into 0, the decode loop never ran, and a `/completion` client
got a 200 with empty text and `finish_reason: "length"` -- worse than the 256 the ignored field used to fall through
to, because it reads as a successful request that produced nothing.

    const int limit = max_tokens < 0 ? room : std::clamp(max_tokens, 0, room);

A negative limit now means "as far as the context allows", bounded by the same `room` every other case is bounded by.

The arm is the static one in `tools/ci/serve_routes_check.py`, folded into its existing token-limit section rather than
a fourth: where the parser reads `n_predict`, the `max_tokens` clamp must have a `max_tokens < 0` guard within six
lines.

  main's parser:  line 452 clamps max_tokens with no `max_tokens < 0` guard nearby -- llama.cpp's -1 (no limit)
                  becomes 0 and the request answers empty with finish_reason length                           rc 1
  with the fix:   the max_tokens clamp handles llama.cpp's -1 (1 site(s))                                    rc 0

Stated plainly: this is a guard-on-the-literal check, not a unit test of the arithmetic -- `app/forward_serve.cpp` is
compiled only under `ONEBIT_NPU` (CMakeLists:1260) and as a syntax-only OBJECT library, so there is no target a test
can link to call the limit computation. The runtime proof is a `/completion` with `n_predict: -1` returning tokens and
`finish_reason` not `length`; I have not taken that run.

* serve: take the token limit from a tested `npu::token_limit()`, not an expression at the call site (engine#2897)

The CHANGES on this PR was right about the arm, and #2906 (closed, its branch deleted) had the better artifact for it: the
sentinel is arithmetic on two ints, so it belongs in a pure function a row CI runs rather than in a source-scan check
that can only see the shape of an expression.

  - `npu/token_limit.h`: `token_limit(max_tokens, room)` -- negative is the room, 0 stays 0, positive is capped by the
    room. #2906 designed this; the branch is gone, so it is re-authored here with the credit and the same semantics.
  - `tests/npu_token_limit_test.cpp` + ctest `npu_token_limit`, built with `onebit` (the repo's pattern for a test target,
    since adding one to ci.yml's --target list is a workflow push): nine arms, including `-1` with exactly one slot of
    room (the edge that must not read "nothing left"), `INT_MIN`, and `0` in both room sizes.
  - `app/forward_serve.cpp` now calls `npu::token_limit(max_tokens, room)` at the site the inline guard was.
  - `serve_routes_check.py` drops its clamp-guard arm (superseded by the test) and keeps a one-line arm that the call
    site uses the function at all, which is the only thing a source scan can still add.

Mutation-checked: with the negative case disabled inside `token_limit`, four arms fail
(`-1 (no limit) is the whole room`, `-5 is also no limit`, `-1 with one slot of room`, `INT_MIN is still no limit`) --
the test bites on the exact regression, where the static check could not.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant