Quellcode durchsuchen

docs: the query-embedding cache has existed since 0.1.4 and this file denied it three times

Rewritten rather than labelled, because the claim was false when written
rather than overtaken: src/embedding_cache.cpp landed in 0.1.4 on
2026-06-04 and three October entries asserted there is no
query-embedding cache. One of them cited
`emb.embed(cfg.model, text)` in handlers/vectors.cpp as evidence, which
is eleven lines below the embeddingCache().get(key) that disproves it -
the citation was read for the clause it was fetched to support.

Records what is actually true, measured on prod 2026-11-02: the cache is
a process-singleton LRU keyed on (apiBase, model, text), 4096 entries /
256 MiB / TTL 86400 / normalize ON, consulted ONLY in
handlers/vectors.cpp. runner/src/host_context.cpp calls embed() directly,
so ctx...search({query_text}) inside a function pays the provider every
call - and prod's own stats show cache_size 3, hits 1, misses 3 after six
days of uptime, because the only query_text traffic on the box goes
through /fn. SV-38.

Also notes that Cache-Control: no-store skips the get and the put and
does NOT reach the provider, since applyOutboundDefaults() sets only a
User-Agent and no inbound header is ever copied outbound - which is what
makes that header a usable control for measuring the provider.

The reproducible-baseline conclusion is unchanged and better supported:
a cached vector is stable until eviction or a restart, which is stable
long enough to be trusted and not long enough to be true.
fszontagh vor 3 Wochen
Ursprung
Commit
7056761df0
1 geänderte Dateien mit 6 neuen und 3 gelöschten Zeilen
  1. 6 3
      CLAUDE.md

+ 6 - 3
CLAUDE.md

@@ -473,7 +473,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   **The CLASS was swept rather than the instance, and two of the three remaining `exists()` sites are the same shape while one is NOT.** `settings_store.cpp` (`removeProject`) and `project_secret_store.cpp` (`remove`) both do `if (!exists) return false;` and their callers map false to 404, so a transport failure is an unretryable 404 there too - admin-only, and fixing them needs a CONTRACT change rather than a deletion, since `bool` cannot say "the call failed". **The third reads alarmingly and is fine: `settings_store.cpp` bootstrap does `if (seeded || !exists(...)) upsert(s.toJson(), ...)`, which looks like a transport blip re-seeding global settings over a live configuration - it is not, because `s` holds what `get()` read two lines above, so the worst case is writing the current settings back, and a FAILED `get` throws and fails startup closed.** Worth recording so nobody raises it twice.
 
 - **`Client::get` returns nullopt for BOTH "absent" and "transport failed"** - it throws only for PERMISSION_DENIED - so a registry lookup cannot tell them apart from the return value. Unhandled, that reaches a caller as 404 "no such collection" for a collection that exists, and a 404 is unretryable BY DESIGN for a careful client, because adding it to a retry set would retry every genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to exactly this. `CollectionRegistry::get` therefore **retries once** (a transient failure usually succeeds, and logs a warning saying so) and then asks `healthCheck()` before reporting absence, throwing **503** when the database is unreachable. Reported upstream too: the client should distinguish, the way it already does for a permission denial.
-- **A REPRODUCIBLE vector-search baseline needs an explicit `query_vector`. Pinning `query_text` is NOT enough.** `query_text` is embedded server-side through the external provider on *every* call - there is no query-embedding cache (`emb.embed(cfg.model, text)` in `handlers/vectors.cpp`), so the same text can yield a different vector on a different day and every score and row count moves with it. Measured by a consumer across one deploy over a byte-identical collection (12447 rows unchanged): an unfiltered top score went 0.7221 to 0.7175 and a filtered count 424 to 426, while five consecutive calls agreed to six decimals - so it is drift in text→vector, not per-call noise. The isolating test: a fixed explicit `query_vector` returned bit-identical results three times, which proves the RANKING is deterministic given a vector. **So nothing in a release has to change for such a baseline to move, and it is therefore not evidence about the release either way.** Corollary worth stating because it bit us: `scan_capped` is query-dependent too and so is also a measurement, not a property of the collection - it is set only when the walk hit the cap *while still short of `top_k`*, so a query that fills `top_k` reports false where a query that falls short reports true. Read all three of the useful assertions (`scan_capped`/`scanned`/the nested error envelope) as "this query, this filter", never as facts about the data.
+- **A REPRODUCIBLE vector-search baseline needs an explicit `query_vector`. Pinning `query_text` is NOT enough.** `query_text` is embedded server-side through the external provider, so the same text can yield a different vector on a different day and every score and row count moves with it. **This entry used to say "there is no query-embedding cache" and cite `handlers/vectors.cpp` for it; there has been one since 0.1.4 and the cache lookup is in that same function - see the cache entry below.** The conclusion is unchanged and the cache makes it stronger: a cached vector is stable until the entry is evicted or the process restarts, which is stable long enough to be trusted and not long enough to be true. Measured by a consumer across one deploy over a byte-identical collection (12447 rows unchanged): an unfiltered top score went 0.7221 to 0.7175 and a filtered count 424 to 426, while five consecutive calls agreed to six decimals - so it is drift in text→vector, not per-call noise. The isolating test: a fixed explicit `query_vector` returned bit-identical results three times, which proves the RANKING is deterministic given a vector. **So nothing in a release has to change for such a baseline to move, and it is therefore not evidence about the release either way.** Corollary worth stating because it bit us: `scan_capped` is query-dependent too and so is also a measurement, not a property of the collection - it is set only when the walk hit the cap *while still short of `top_k`*, so a query that fills `top_k` reports false where a query that falls short reports true. Read all three of the useful assertions (`scan_capped`/`scanned`/the nested error envelope) as "this query, this filter", never as facts about the data.
 - **A LAUNCH ANNOUNCEMENT TELLS YOU WHAT IS SHIPPING, NOT WHAT IS NEXT - AND I PUT A CONSUMER'S INFERENCE ABOUT THEIR OWN ROADMAP INTO A PRIORITY DECISION WITHOUT ASKING WHETHER IT WAS A FACT.** 2026-10-22. Told that a tenant's `/fn` exposure was safe only because their voice agent was unlaunched, I asked how near the launch was; they answered "likelier to be near than far" and that the safe window "may be shorter than the deploy window", and I raised the deploy's priority on it and told my owner the two were racing. **Retracted by them within the hour, from their user: the customer is getting the review portal ONLY and the agents are NOT IMPLEMENTED - not unwired, not awaiting configuration, not built.** The race did not exist.
   **Their own diagnosis of it is the rule worth keeping: "they are publishing the portal" is evidence about the portal and SILENT about everything else in the product**, and the gap got filled by an assumption that things ship in the order one happens to learn about them. It is the same family as reading a requirement off traffic - both substitute an observation for a statement of intent that only the owner holds - and in both cases there was a person who could simply have been asked.
   **What it cost, which is the part that generalises: an unverified roadmap claim can move a RELEASE PRIORITY, which is more expensive than moving a diagnosis.** A wrong diagnosis is corrected by the next measurement; a wrong priority reorders real work and is quoted onward by whoever heard it. So a claim about someone else's schedule needs the same treatment as a claim about their code: ask whether it is a fact or an inference, and say which when passing it on.
@@ -492,13 +492,16 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A CONSUMER'S TIMEOUT CAN SIT EXACTLY ON THE BOUNDARY OF OUR COLD EMBED PATH, AND THEN THE FIRST CALL OF A QUIET PERIOD IS A COIN FLIP THAT LOOKS LIKE AN INTERMITTENT FAULT IN OUR SERVICE.** Measured by novitax 2026-10-22 on their live voice agent: their first embed attempt has a **6000 ms** budget and our cold path costs **about six seconds**, so two samples they had already collected sat at **6.037 s (succeeded) and 6.547 s (failed, 0 candidates)** - the same query, minutes apart, decided by a few hundred milliseconds. Their own words are the lesson: both observations looked identical, and the thing to be suspicious of was that identity rather than to explain it.
   **It corroborates the long tail recorded above from the other side.** A cold `query_text` is 0.5-1.0 s at the median and the tail reaches at least 8.17 s, so a 6 s client timeout is not generously set - it is set INSIDE our distribution, and nothing on either side of the call says so. **This is the split-latency-budget trap again** (their timeout is their number, our tail is ours, and neither side can see the other), with the sharper form that **two different faults produced one symptom**: the hourly snapshot stall and this boundary, plus a third explanation they had written up that morning. When a consumer reports an intermittent degradation, the question is not which cause it is but **how many causes it has**.
   The fix is the one already recommended here on independent grounds - embed ONCE and pass an explicit `query_vector` to every collection - which halves the draws from the tail, moves the cold call off the boundary, and is separately the only reproducible baseline.
-- **A CACHE WOULD MAKE SEARCH LATENCY BIMODAL, so do not derive a timeout from a post-cache p50.** If query embeddings are ever cached, the same endpoint answers in ~3 s or ~12-15 s depending on state nothing outside can see, and a timeout or retry budget tuned against the hit path will fire on every miss. Same family as the startup loop that was bounded by an attempt COUNT: a budget encoding a duration as a count carries a hidden assumption about per-item cost. Note also that **caching would NOT make a search reproducible** - per-process plus a TTL means a restart or the TTL boundary clears it, so results would be stable across an afternoon and silently not across a deploy, which is stable long enough to be trusted and not long enough to be true. An explicit `query_vector` stays the only reproducible baseline.
+- **THE QUERY-EMBEDDING CACHE EXISTS, HAS SINCE 0.1.4 (2026-06-04), AND THIS FILE DENIED IT THREE TIMES IN OCTOBER WHILE CITING THE FILE THAT CONTAINS IT.** `src/embedding_cache.cpp` is a process-singleton LRU keyed on (apiBase, model, text), and on prod it is 4096 entries / 256 MiB / TTL 86400 / **normalize ON** (trim + lowercase, so `"Foo "` and `"foo"` share an entry). The claim was not overtaken by events - it was false when written, about code five months old, and the citation offered as evidence (`emb.embed(cfg.model, text)` in `handlers/vectors.cpp`) sits ELEVEN LINES BELOW the `embeddingCache().get(key)` that disproves it. **The lesson is not "check the citation" but that a citation gets read for the clause it was fetched to support**; I went to that function for the embed call and did not see the cache around it. A cited claim is only as good as the part of the citation you read.
+  **IT COVERS ONE SURFACE AND NOT THE OTHER, WHICH IS THE PART THAT MATTERS IN PRACTICE.** It is consulted in exactly one place, `handlers/vectors.cpp` (the `/search` and vector-insert routes). `runner/src/host_context.cpp` builds an `EmbeddingClient` and calls `embed()` directly with no cache consultation, so **`ctx...search({query_text})` inside a function pays the provider on every call.** Measured on prod 2026-11-02, six days into the process's uptime: `/api/v1/stats` reported cache_size **3**, hits **1**, misses **3** - and three of those four lookups were mine from ten minutes earlier. The cache has served essentially nothing in production because the only `query_text` traffic on the box goes through `/fn`. SV-38.
+  **`Cache-Control: no-store` on a request skips both the get and the put** (`wantsNoStore()`, `vectors.cpp:42-45`), which is how to measure the provider through this route - and it does NOT reach the provider: the outbound call builds a fresh body and `applyOutboundDefaults()` sets exactly one default header, the User-Agent. No inbound header is ever copied outbound.
+- **A CACHE MAKES SEARCH LATENCY BIMODAL, so do not derive a timeout from a post-cache p50.** The same endpoint answers from the hit path or the provider path depending on state nothing outside can see, and a timeout or retry budget tuned against the hit path will fire on every miss. Same family as the startup loop that was bounded by an attempt COUNT: a budget encoding a duration as a count carries a hidden assumption about per-item cost. Note also that **caching would NOT make a search reproducible** - per-process plus a TTL means a restart or the TTL boundary clears it, so results would be stable across an afternoon and silently not across a deploy, which is stable long enough to be trusted and not long enough to be true. An explicit `query_vector` stays the only reproducible baseline.
 - **MEASURED ON PROD, 2026-10-09, small collections (126 and 49 rows, dim 4096), server-side end to end.** The filtered similarity search costs **~25 ms** and the filter costs nothing measurable at that size - filtered and unfiltered are identical within noise. A cold `query_text` is **0.49-0.95 s**, essentially all of it the provider round trip; the SAME text repeated is 0.022 s, because the provider caches it. **That cache is useless to a workload of unique queries** such as a voice assistant, which is therefore permanently on the 0.5-1.0 s path. Eight samples in one window is a MEDIAN, not a tail: a 12-15 s text search was observed earlier the same day and did not reproduce, so the bad tail is real and unexplained rather than bounded at 0.95 s. Quote these as medians and say so.
   **RE-MEASURED 2026-10-19 BY A CONSUMER AND BY US, AND THE DISTRIBUTION IS WHAT MATTERS RATHER THAN EITHER FIGURE: THE MEDIAN IMPROVED BY AN ORDER OF MAGNITUDE AND THE TAIL DID NOT GO AWAY.** Twelve never-before-seen strings against `novitax:kb_facts`: **min 0.48 s, median 0.75 s, max 4.46 s, with 1 of 12 over 2 s**. In the same hour a cold `query_text` of ours took **8.17 s**, so the tail reaches at least that. Both observations are correct and neither alone describes the endpoint.
   **The consumer had first measured FOUR fresh strings, got 0.57-1.33 s, and written that the 12-15 s figure was retired and two searches now fit inside a phone call's budget.** Their own re-measurement overturned it. **Four samples describe a median and say nothing about a tail, and a caller does not experience the median - they experience the call they are on.** That is the same shape as reading a server version off `db_client`: a true observation supporting a claim strictly wider than it can discriminate.
   **The design consequence, which is the useful part: TWO SEQUENTIAL `query_text` SEARCHES ARE TWO INDEPENDENT DRAWS FROM THAT TAIL.** Reading two collections that way doubles the chance of meeting it, so the right shape is to embed ONCE and pass the same explicit `query_vector` to both - not because a single search is slow, since usually it is not, but because it halves the draws and lets one `embedTimeoutMs` bound one call instead of two. That also restores the explicit-`query_vector` recommendation on the independent ground already recorded here, that it is the only reproducible baseline.
   **AND A FAST REPEAT CANNOT ATTRIBUTE A SLOW CALL - ONLY REMOVING THE PROVIDER FROM THE PATH CAN.** When the 8.17 s search was followed by the same text answering in 0.267 s and 0.242 s, that was equally consistent with "the provider cached it and we are fine" and with "the provider cached it while our store is slow under swap". The measurement that decides it is a **pure DB read with no embedding in the path, which answered in 3-10 ms**. Keep that control to hand whenever attributing latency across the provider boundary; without it the reassuring reading and the alarming one produce identical numbers.
-- **The embedding call IS essentially the whole vector-search latency.** Measured on prod with the ranking doing identical work both ways: a fixed `query_vector` search returned in 3.4 s against 12-15 s for the same filter and `top_k` via `query_text`. There is no query-embedding cache, so every repeated search pays the provider again.
+- **The embedding call IS essentially the whole vector-search latency.** Measured on prod with the ranking doing identical work both ways: a fixed `query_vector` search returned in 3.4 s against 12-15 s for the same filter and `top_k` via `query_text`. A repeated search pays the provider again on the FUNCTION surface, which has no cache; through `/api/.../search` a repeat is served by the LRU. This sentence used to say there is no cache at all, which was wrong - see the cache entry above.
 - **A FILTERED VECTOR SEARCH IS NOW ONE SERVER-SIDE CALL (database 2.14.0+), exact and UNCAPPED.** The filters select candidates BEFORE ranking, so the answer is the true top-K among matching rows rather than a filtered slice of the unfiltered top-K, and there is no walk, no 10000 cap and nothing to truncate. Measured by the database team on 12447 rows at dim 4096: a filter matching ~430 rows at `topK` 500 took **51 ms indexed** against **187 ms for the same search unfiltered** - the filter makes it CHEAPER, because only matching rows are scored. Our emulation took **3.21 s** for that shape on prod.
   - **`scan_capped` is emitted EXPLICITLY as `false` on this path, never omitted**, and `scanned` is 0 because no walk happened - which here is literally true rather than a sentinel. A consumer maps an absent `scan_capped` to "this server cannot report truncation, so completeness is unknown" and shows that to an operator; on this path that is both false and PERMANENT, and a warning that always fires is one people learn to skip. Absence is also already spoken for by the 0.8.3 agreement, where a missing field means "old server" and nothing else.
   - **Detection is the server's own `filters_applied` response field, not a version check we have to get right.** A pre-2.14.0 server would silently answer UNFILTERED, so the client throws `FailedPrecondition` / `filters_unsupported` instead - which is the only reason the new path can be tried optimistically. The refusal is LATCHED per process, so a deployment on an older database pays one refused round trip rather than one per search; one-way on purpose, since the emulation is correct and merely capped, and it clears on the restart a database upgrade involves anyway.