Ver Fonte

fix: the hourly snapshot stalls the database, and my explanation for a consumer's 503 was wrong

novitax grepped their own code and found ZERO call sites for the collections
listing I had told them was costing them a 503 on every queue page load.
Confirmed from our side: every collections-listing request that day falls in
one three-minute window, which was them probing sizes by hand while
diagnosing. The route's cost is measured and real; the claim that a consumer
was paying it was mine and was false.

The measurement covered the ROUTE and I used it to assert a CONSUMER's
behaviour, which it cannot reach - the lesson this file already records from
the kitchen_presets diagnosis, committed again the same way inside a week.

And the real cost was not being wrong: a tidy explanation closed the question.
Reopening it found this.

Every Deadline Exceeded vectorapi logged since Oct 20, timed against every
snapshot completion, excluding the database's own restart cluster:

  43 stalls: getCollectionInfo 30, similaritySearch 5, getMemoryStats 5,
             insert 3
  coincidence window 135s of a 3647s median interval = 3.7% of elapsed time
  34 of 43 land in it - a 21x enrichment

Control, because clustering is cheap to find once you have a hypothesis:
reshuffling the same 43 stalls to random times across the same span, 200
times, gives mean 1.4 hits and a MAXIMUM of 7. Observed 34.

My first pass said 56%, measuring from the nearest PRECEDING snapshot, and
filed nine stalls at +3639s/+3644s/+3651s as the uncorrelated remainder.
Snapshots drift ~45s later each hour, so those sit a few seconds BEFORE the
next one completed - during it. A window anchored on one side of a periodic
event misses the events just inside the other side.

The impact is real traffic: 5 similaritySearch and 3 insert failures are a
tenant's, and their kb_facts/search took 503s at rt=60.062, 21.063, 19.177,
17.810 and 14.391 on Oct 21, with the 01:13:07 cluster +4s after a snapshot.
Nobody reported it because every affected caller tolerates it - ours log a
warning and carry on, two stalls had no HTTP request at all, and the tenant
retries. Nothing alerts on a warning written by a path designed not to fail
loudly.

Not ours to fix in code: it is what 2.20.1's streaming snapshot writer
removes, so the window now buys a measurable present fix rather than only
insurance. SV-18.

This also refutes this file's own "running prod on swap costs nothing
measurable" entry. Its numbers still reproduce; the conclusion was too wide,
because the cost lasts seconds once an hour and a steady-state sample cannot
see it by construction. Labelled in place rather than left reading as true.
fszontagh há 1 mês atrás
pai
commit
5f07dadaf5
1 ficheiros alterados com 16 adições e 3 exclusões
  1. 16 3
      CLAUDE.md

+ 16 - 3
CLAUDE.md

@@ -282,7 +282,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   **FIXED BY ADDING SWAP, which is a floor under the symptom and not a cure.** 4 GB `/swapfile` plus an `/etc/fstab` line so it survives a reboot (`/etc/fstab` is owned by no package - `dpkg -S` first, per the conffile trap above; backed up to `/etc/fstab.bak-20261019`). **The fstab line alone is not enough: `findmnt --verify --fstab` warns "your fstab has been modified, but systemd still uses the old version", so a `systemctl daemon-reload` is needed for systemd to generate the `swapfile.swap` unit** - verified afterwards as loaded, active and `RequiredBy=swap.target`. Same shape as the `/etc` mode 0751 trap: correct today and only visible as broken after a reboot. **Verify the entry with `swapon -a`, which is idempotent and reports "already active", NEVER with `swapoff`** - paging 847 MB back into a 1973 MB box would re-kill the thing you just rescued. Boot then peaked at ~1514 MB RSS **and 818 MB of swap**, settling at 847 MB in use, so the anonymous demand is well ABOVE the 1973 MB box rather than marginally over it. The snapshot peak still scales with the store, and swapping a 400 MB serialise is slow; the structural fix is the database's.
   **THE KILL POINT IS A LOWER BOUND ON THE REQUIREMENT, NEVER THE REQUIREMENT.** Without swap the process died at 1.51 GB anon, and it is tempting to size against that. The kernel STOPPED it there - it never revealed its own peak. Only once swap gave it room did the real figure appear, and it was ~2.3 GB of anonymous demand. Sizing against an OOM kill point under-provisions by however much the process still had left to allocate, which is unknowable from the kill.
   **WHY NOBODY SAW IT, AND THIS IS THE GENERALISABLE PART: A CRASH THAT RESTARTS CLEANLY IS A SILENT CRASH.** systemd brought it back each hour, so the observable was a ~40 s outage once an hour inside consumers' retry budgets - and the database logs it only as `status=9/KILL`, with no line saying a snapshot FAILED. Worse, the run log lives in the database, so during each kill it goes QUIET rather than recording failures: the absence-is-not-information trap this file already records, now in its most expensive form. A consumer reported it only on the day it became permanent. **So "the service is up" and "the service has not been failing" are different claims, and `NRestarts` is the cheap way to tell them apart** - 183 here, which was visible all along and which nobody read. Check it when closing any window, next to `apt-mark showhold`; it is the same class of signal as the `ii`/`hi` column this file has now been read past twice.
-  **RUNNING PROD ON SWAP COSTS NOTHING MEASURABLE HERE, AND THAT IS A MEASUREMENT RATHER THAN A HOPE - BECAUSE THE SWAPPED PAGES ARE THE BOOT TRANSIENT AND ARE COLD.** The obvious worry after the fix is that a database holding 866 MB in swap now serves every read through paging. Measured after recovery: `vmstat` shows **si=0, so=0** - no page-in or page-out activity at all, so the swapped pages are the init-time peak sitting cold, not working set being thrashed. A pure DB read through our API (`/documents?limit=5`, no embedding in the path) answers in **3-10 ms**. The one slow number, an 8.17 s vector search, was NOT swap: the same `query_text` repeated answered in **0.267 s and 0.242 s**, which is the provider caching identical text exactly as recorded above, so the 8 s was the cold provider round trip in its known bad tail. **The pure DB read is the control that makes this conclusive** - it removes the provider from the path entirely, and at 3 ms it cannot be hiding a paging cost. Without it, a fast repeat would have been equally consistent with "swap is fine" and "the provider cached it while swap is still slow".
+  **RUNNING PROD ON SWAP COSTS NOTHING MEASURABLE IN THE STEADY STATE - BUT READ THE REFUTATION BELOW BEFORE USING THAT AS "IT IS FINE": MEASURED 2026-10-22, IT COSTS A MULTI-SECOND STALL ONCE AN HOUR, AND A STEADY-STATE SAMPLE CANNOT SEE THAT BY CONSTRUCTION.** The numbers in this paragraph all still reproduce; the conclusion drawn from them was wider than they could support, and the periodic cost is in the snapshot-stall entry further down. The obvious worry after the fix is that a database holding 866 MB in swap now serves every read through paging. Measured after recovery: `vmstat` shows **si=0, so=0** - no page-in or page-out activity at all, so the swapped pages are the init-time peak sitting cold, not working set being thrashed. A pure DB read through our API (`/documents?limit=5`, no embedding in the path) answers in **3-10 ms**. The one slow number, an 8.17 s vector search, was NOT swap: the same `query_text` repeated answered in **0.267 s and 0.242 s**, which is the provider caching identical text exactly as recorded above, so the 8 s was the cold provider round trip in its known bad tail. **The pure DB read is the control that makes this conclusive** - it removes the provider from the path entirely, and at 3 ms it cannot be hiding a paging cost. Without it, a fast repeat would have been equally consistent with "swap is fine" and "the provider cached it while swap is still slow".
   **No data was lost, and the arithmetic is the proof rather than the doc counts.** The last good snapshot ended at sequence 337213; recovery logged "Replayed 69616 WAL entries from sequence 337213" and "Persistence manager started, WAL sequence: 406829", and 337213 + 69616 = 406829 exactly - the WAL began precisely where the snapshot ended, with no gap and no overlap, across the whole ~69-hour snapshot drought. "Recovery complete (TrivialSuccess): 65030 docs in 73 collections", and a document body read back intact from all four live tenants. A COUNT would not have shown this: counts match under several wrong outcomes, whereas the sequence identity can only hold if every write in the gap was replayed.
   **GREPPING AN OOM LINE FOR A SERVICE NAME MISREADS IT, AND THE MISREADING IS THE FLATTERING ONE FOR WHOEVER IS GREPPING. `cpuset=` NAMES THE CGROUP THAT TRIGGERED THE ALLOCATION; `task=` AND `task_memcg=` NAME THE VICTIM.** Five kernel lines on 2026-10-19 read `cpuset=smartbotic-vectorapi.service ... task_memcg=/system.slice/smartbotic-database.service, task=smartbotic-data`, so a grep for our own service name matched them and they look exactly like vectorapi being OOM-killed. It never was: ours asked for memory, that request tripped the GLOBAL OOM killer, and the kernel chose the database as the victim because it was the largest. `NRestarts=0` on all three of our units is the control, against 183 on the database from the same command. Under global memory pressure the process that triggers a kill and the process that dies are routinely different, which also means **a service can be a repeated CAUSE of another service's death while its own logs stay perfectly clean** - worth knowing before taking "my service shows nothing wrong" as exculpatory. Read `task=`.
   **vectorapi itself came through untouched**, up since 2026-10-15 15:56 (the supervised restart after the client library moved) and the runner since 2026-10-13, and it answered **1664 requests with 503** during the permanent phase - correctly classified, naming the real condition, which is the error-slug work doing its job under the one condition nobody arranges deliberately.
@@ -301,6 +301,18 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   **The healthy signals are genuinely healthy and must not be read as "fine", because they are the output of the swapfile doing its job:** snapshots complete hourly in ~9 s, 14 of them that day, **the WAL directory is EMPTY** - which is the exact inverse of the Oct 17-19 state where nothing completed so nothing truncated - zero OOM kills since Oct 20, `NRestarts=0`, and `si=0 so=0`, so the swapped pages are the cold boot transient rather than working set being thrashed. Everything works. It works with no headroom.
   **So the 2.20.1 window moved from "the structural fix for a solved outage" to "the thing standing between us and the same outage at the next step-change", and the distinction this file already draws decides what it buys:** streaming the snapshot writer removes the hourly peak and therefore prevents phase 1 and the WAL growth that made phase 2 unsurvivable - but **boot still holds the whole dataset in memory, which 2.20.1 does NOT fix**, and the dataset is now 42% larger than the one that could not boot on 2026-10-19. The swapfile is what covers that today. Quote both halves when asking for the window.
 
+  **THE HOURLY SNAPSHOT STALLS THE DATABASE FOR SECONDS AND FAILS REAL TENANT SEARCHES. 79% OF EVERY gRPC DEADLINE FAILURE COINCIDES WITH ONE, AGAINST A BASE RATE OF 3.7%.** Measured 2026-10-22, and it is the memory state above showing up as latency rather than as a crash - which is why it was invisible. Every `Deadline Exceeded` vectorapi logged since Oct 20, excluding the cluster around the database's own restart, timed against every snapshot completion:
+  - **43 stalls**: `getCollectionInfo` 30, **`similaritySearch` 5**, `getMemoryStats` 5, **`insert` 3**
+  - coincidence window completion-15 s to +120 s (a snapshot takes ~9 s) = 135 s of a 3647 s median interval, i.e. **3.7% of elapsed time**
+  - **34 of 43 land in it - a 21x enrichment**
+
+  **The control is what makes it an association rather than a pattern found by looking for one:** reshuffling the same 43 stalls to uniformly random times across the same span, 200 times, gives **mean 1.4 hits and a MAXIMUM of 7**. Observed 34. Clustering is cheap to find once you have a hypothesis, and this is the cheap check that says whether it is there.
+  **A WINDOW ANCHORED ON ONE SIDE OF A PERIODIC EVENT SYSTEMATICALLY MISSES THE EVENTS JUST INSIDE THE OTHER SIDE, and it nearly cost half the result.** My first pass measured each stall from the nearest PRECEDING snapshot and reported 56%. Nine stalls came out at `+3639s`, `+3644s`, `+3651s` and read as the uncorrelated remainder. **Snapshots drift ~45 s later each hour** because the timer restarts after each completion, so a stall 3639 s after one snapshot is a few seconds BEFORE the next one finished - during it. Measuring to the nearest snapshot in either direction moved 56% to 79%.
+  **The impact is real traffic, not only our own metadata reads.** 5 `similaritySearch` and 3 `insert` failures are a tenant's. Cross-checked in the access log: one tenant's `kb_facts/search` took 503s at **rt=60.062, 21.063, 19.177, 17.810 and 14.391** on 21 Oct, and the 01:13:07 cluster sits **+4 s after a snapshot completion**.
+  **NOBODY REPORTED IT BECAUSE EVERY AFFECTED CALLER TOLERATES IT - the tolerated-failure trap this file already demands a re-check trigger for, now costing an hourly outage nobody can see.** Ours log a warning and carry on (`function scheduler could not list projects`, `function event watcher could not list projects`, `function job reclaim failed`, `could not enqueue cron job`), and two of the 22 Oct stalls had **no HTTP request in that minute at all**, so they were purely internal. The tenant retries. **Nothing alerts on a warning written by a path that is designed not to fail loudly**, so the signal sat in the journal for days.
+  **This is not ours to fix in code: it is exactly what 2.20.1's streaming snapshot writer removes**, which means the window buys a measurable present fix rather than only insurance against the next step-change. Tracked as SV-18.
+  **It also REFUTES this file's own claim that running prod on swap "costs nothing measurable here".** That entry stands as a steady-state measurement - `si=0 so=0`, a 3-10 ms document read, and those still reproduce - but the conclusion drawn from it was too wide. The cost is seconds long and once an hour, so **a steady-state sample cannot see it by construction**, and the sample was taken on the reassuring side of the very thing it was meant to rule out. The discriminating measurement is one that spans the periodic event, not one taken between them.
+
 - **A SECOND RESTART IS NOT NEEDED ON 2.17.2, measured rather than reasoned.** Our `KeyStore`/`SettingsStore` bootstraps DO perform the online upgrade after the migration, and the log says so - but with **0 rows and 0 history versions rewritten**, because the collections are already ciphertext through the bare-alias merge. `encryption-verify` then reports `sealed: yes`, `CLEAN`, exit 0. So the window is TWO steps and ONE compaction (upgrade, then start vectorapi), with verify as the branch: plain `CLEAN` means done, `CLEAN (UNSEALED: ...)` means take the reseal inside the window. On 2.17.1 that same flag move requested a reseal that compacted every project, which is where the obsolete three-step plan came from.
   Note the upstream log line still says "old plaintext copies are removed at the next restart" even when it rewrote NOTHING, which contradicts verify's `sealed: yes` and would have an operator restart for no reason. Trust verify.
 - **MOVING THE CLIENT PACKAGE UNDER AN EXISTING BINARY IS AN ABI QUESTION, AND IT IS CHEAP TO TEST.** Every 2.x client shares one SONAME, so apt will happily put a 2.17.2 `libsmartbotic-db-client.so.2` under a server binary compiled against 2.14.0 headers - and the documented failure mode is that it installs fine and segfaults later. Verified before deploying rather than hoped: a Debian 13 container holding the real `smartbotic-vectorapi 0.12.0-1` deb plus `libsmartbotic-db-client 2.17.2-1`, against a 2.17.2 server, answered **21 of 21 calls** correctly - including `POST /indexes` with `unique`, which exercises `CreateIndexResult`, the by-value struct whose SIZE is the thing that would break, and a 409 duplicate refusal, which proves `duplicateExamples` crossed the boundary intact. `/api/v1/version` reported `db_client: 2.17.2` so the new library really was loaded. Repeat this whenever `DB_CLIENT_VERSION` and the deployed client diverge; it takes minutes and the alternative is a restart days later.
@@ -357,8 +369,9 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   | collections listing (11 collections) | 0.428 / 0.409 / 0.492 s |
   | **control: one document listing, no fan-out** | **0.002 s** |
 
-  **The control is what makes this a measurement rather than "that route feels slow"** - it removes the per-collection fan-out and nothing else, and the gap is three orders of magnitude. On a SINGLE vCPU, under the consumer's own 126-requests-in-a-minute burst, that 0.43 s stretches past the client deadline: their only 503 of the day was `GET .../collections` at `rt=9.693`, and the journal names the call - `Client::getCollectionInfo failed: Deadline Exceeded`.
-  **The diagnosis that this is NOT the database needed four controls, because "the database is slow today" is the reading every signal superficially supports:** snapshots completed hourly (14 that day), zero OOM kills since Oct 20, `NRestarts=0`, the database's own minute line reading `pressure=normal, 0 evicted` on both sides of the failure, and the consumer's own p50 at **0.049 s over 2014 requests**. A consumer about to retune their pagination against a database that was fine would have been fixing the wrong layer, which is exactly what they asked us to rule out first.
+  **The control is what makes this a measurement rather than "that route feels slow"** - it removes the per-collection fan-out and nothing else, and the gap is three orders of magnitude. **NO CONSUMER CALLS THIS ROUTE, AND I ASSERTED THAT ONE DID. The cost above is measured and real; the impact claim was mine and was false.** I wrote that a consumer was paying it on every queue page load and that it explained their 503. They grepped their own `src/`, `scripts/` and `functions/` and found **zero call sites** - their client only ever reads documents and index values. Confirmed from our side rather than taken on report: **every collections-listing request that day falls inside one three-minute window**, which was the consumer probing collection sizes BY HAND while diagnosing. So the 503 I built the story on was their own diagnostic call, and the route costs nobody anything in production.
+  **The measurement covered the ROUTE's cost and I used it to claim a CONSUMER's behaviour, which it could not reach.** A consumer's call sites are not derivable from our access log - the exact lesson this file already records from the `kitchen_presets` diagnosis, committed again the same way inside a week. Writing the rule down is not applying it.
+  **And the cost was not the embarrassment, it was that a tidy explanation closed the question.** Having attributed the 503 to "their burst plus our expensive route" I stopped looking, and the real cause - the hourly snapshot stalling the database, below - went on being invisible. It was in the journal the whole time. **A wrong cause that FITS is more expensive than no cause at all**, because no cause keeps someone looking.
   **It is the same shape as the rate-limiter decision one layer down, and worth noticing that we got it right there and not here:** that route deliberately charges the limiter ONCE because "one request is one request", and then fans out 22 round trips for the same single request. Tracked as SV-16; no fix shipped, because making the stats opt-in changes the response shape and caching them makes an exact `document_count` stale, and this file already records an exact count finding a real data defect (13093 against 13092).
 - **Prod's database binds `localhost`, not `0.0.0.0`** (`storage.bind_address`), which is why it is only reachable from vectorapi on the same box - correct, and worth knowing before wondering why a port-mapped copy refuses connections.
 - **`policy-rc.d` DOES NOT HOLD THE DATABASE PACKAGE. It blocks `invoke-rc.d`, and that postinst calls `systemctl` DIRECTLY.** Measured the hard way on 2026-10-12: a `policy-rc.d` returning 101 was in place, the pinned install ran at 18:21:12, and the service restarted anyway - the 2.17.2 first-boot migration ran to completion before the install command had even returned. **A hold point three consumers had been promised simply did not exist**, and that cost TWO separate things, not one. One consumer lost the chance to say "wait, a call is live" that they had explicitly been offered. **And because the install itself triggered the migration, the outage happened at 18:21 rather than in the 18:30 slot all three had approved** - it ran NINE MINUTES EARLY, outside the approved window, which is a governance failure distinct from the missing check. A consumer put that second point in the record; my own account had blurred it into the first, which understated it.