ソースを参照

fix: drop the exists() probe from PATCH - it could 404 a document that exists

Exposed by a consumer's ghost-document report, and it is NOT the cause of
that report. Their diagnosis was that Client::exists returns false while
get succeeds, because PATCH probes exists first. Three handlers refute it:
PATCH probes exists, PUT uses get - the very call they report SUCCEEDING -
and DELETE calls remove and touches exists nowhere. All three answered 404,
so exists cannot be the common cause, and changing it would only have moved
PATCH's 404 from the probe to the patch() call. Reads find that row and
writes cannot, which is a storage question and the database's layer; routed
there.

What the report did expose is a real defect of ours, and the fix is a
deletion. Client::exists conflates "no such document" with "the call
failed", exactly as CollectionRegistry::get records - the defect that cost
a consumer a 6-minute ingest of an 8 GB mailbox when a transport blip
became "no such collection". A 404 is unretryable BY DESIGN for a careful
client, so a transient failure on that probe was permanent for the caller.

Removing it is free, measured before deleting rather than argued: with no
probe, PATCH of an absent document still answers 404 not_found because
patch() reports it through its own Failure, while a transport failure
arrives as Unavailable and now correctly answers 503. Control: a document
that exists still patches to 200. The probe bought nothing for correctness,
cost a round trip, and could only ever turn a 503 into a 404.

The test pinning it states what it does NOT cover, because it would
otherwise read as proof of the deletion: it passes identically with the
probe in place, and nothing in the fixture can count round trips or inject
a transport failure. What it pins is the fact the deletion rests on - that
patch() reports absence itself.

Swept the class rather than the instance. settings_store removeProject and
project_secret_store remove are the same shape (bool, caller maps false to
404) but admin-only and need a contract change, not a deletion - filed. The
settings bootstrap site reads alarmingly and is fine: s holds what get()
read two lines above, so a false exists writes the current settings back,
and a failed get throws and fails startup closed.

Also recorded why the symptom was unreadable, which is our fault: all three
write paths answer a byte-identical 404 "no such document", and so does a
genuinely absent document - measured on all three routes against an id that
never existed. The probe became the suspect only because it is the one of
the three that is visible in our source.
fszontagh 1 ヶ月 前
親
コミット
01967f8137
3 ファイル変更、96 行追加、5 行削除
  1. 7 0
      CLAUDE.md
  2. 29 5
      src/handlers/documents.cpp
  3. 60 0
      tests/test_api_integration.cpp

+ 7 - 0
CLAUDE.md

@@ -392,6 +392,13 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null.
 - **Null and absent are both unconstrained on a unique index** since database 2.12.0 - only real values collide. Before that, two nulls collided.
 - **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
+- **A GHOST DOCUMENT - READS FIND IT, EVERY WRITE 404s - AND THE OBVIOUS SUSPECT IN OUR CODE COULD NOT HAVE CAUSED IT.** Reported by a consumer 2026-10-22 on prod `toloajto:catalog_hardware`, one document created 2026-07-01 at `_version` 2, last written 2026-09-28: it LISTS, `GET` answers 200 with the full body, and PATCH (even `{}`), PUT and DELETE all answer **404 `not_found`**. Other collections' documents write fine with the same admin key, and a freshly POSTed document in the SAME collection writes fine, so it is one row rather than a collection or a key.
+  **Their diagnosis was that `Client::exists` returns false while `get` succeeds, because PATCH probes `exists` first. That is refuted by their own evidence, and the refutation is readable off three handlers:** PATCH probes `exists()`; **PUT uses `get()` - the very call they report SUCCEEDING** - and on finding the row goes to `updateIfVersion`; **DELETE calls `remove()` and touches `exists()` nowhere at all.** All three answered 404, so `exists()` cannot be the common cause, and changing it would have fixed nothing - it would only have relocated PATCH's 404 from the probe to the `patch()` call. **The correct statement is that READS find the row (`get`, `find`) and WRITES cannot (`update`, `patch`, `remove`)**, which is a storage question and therefore the DATABASE's layer, not ours. Routed there rather than received politely.
+  **Why the symptom was unreadable, and it is our fault: all three write paths answer a BYTE-IDENTICAL 404 `not_found` "no such document", and so does a genuinely absent document.** Measured locally on all three routes against an id that never existed - the responses are indistinguishable from the ghost's. So the one observation a consumer can make cannot discriminate "the row is gone", "this path cannot see it" or "the write was refused", and the probe became the suspect purely because it is the only one of the three that is VISIBLE in our source. A plausible mechanism is the MemoryStore/LMDB split this file already records from the other direction (`_`-prefixed collections: writes land in MemoryStore while reads route to LMDB), which would put this row in the mirror and not in the authoritative store - but that is a HYPOTHESIS with no measurement behind it, it concerns another team's internals, and it is theirs to confirm.
+  **WHAT WE FIXED IS A DIFFERENT, REAL DEFECT THE REPORT EXPOSED, AND IT IS A DELETION: the `exists()` probe is GONE from PATCH.** `Client::exists` conflates "no such document" with "the call failed", exactly as `CollectionRegistry::get` records - and that cost a consumer a 6-minute ingest of an 8 GB mailbox when a transport blip became "no such collection". A 404 is unretryable BY DESIGN for a careful client, so a transient failure on that probe was PERMANENT for the caller. **Removing it is free, and that was measured before deleting rather than argued:** with no probe, PATCH of an absent document still answers 404 `not_found` because `patch()` reports it through its own `Failure` (code `Ok` on a 0 return means "did not apply"), while a transport failure arrives as `Unavailable` and now correctly answers 503; the control, a document that exists, still patches to 200. So the probe bought nothing for correctness, cost a round trip, and could only ever turn a 503 into a 404.
+  **The test that pins it says what it does NOT cover, because it would otherwise read as proof of the deletion:** it passes identically with the probe in place, since the probe gave the same two answers, and nothing in the fixture can see a round-trip count or inject a transport failure. What it pins is the FACT the deletion rests on - that `patch()` reports absence itself - so if that ever broke, the test goes red and the deletion stands revealed as unsafe.
+  **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 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.

+ 29 - 5
src/handlers/documents.cpp

@@ -223,11 +223,35 @@ void registerDocumentRoutes(ApiServer& s) {
 
         if (!ifVersion) {
             // A patch is a server-side merge: it reads nothing out and cannot
-            // lose a concurrent writer's fields. The existence probe stays a
-            // probe rather than a read, so the common path does not pay for
-            // fetching a document it does not look at.
-            if (!d->db.client().exists(t.qualified, id))
-                throw ApiError(ErrCode::NotFound, "not_found", "no such document");
+            // lose a concurrent writer's fields.
+            //
+            // THERE USED TO BE AN `exists()` PROBE HERE AND IT WAS REMOVED,
+            // because it could answer an UNRETRYABLE 404 for a document that
+            // exists. `Client::exists` conflates "no such document" with "the
+            // call failed" - the same defect `CollectionRegistry::get` records
+            // and that cost a consumer a 6-minute ingest of an 8 GB mailbox
+            // when a transport blip became "no such collection". A 404 is
+            // unretryable BY DESIGN for a careful client, because adding it to
+            // a retry set would retry every genuine absence, so a transient
+            // failure here was permanent for the caller.
+            //
+            // Removing it is free, which is the part worth knowing rather than
+            // rediscovering: `patch()` ALREADY reports the absent case through
+            // its `Failure`, where code `Ok` on a call returning 0 means "did
+            // not apply" and maps to 404, while a transport failure arrives as
+            // Unavailable and maps to 503. So the probe bought nothing for
+            // correctness, cost an extra round trip, and could only ever turn a
+            // 503 into a 404. Measured before deleting it, with a control:
+            // with no probe, PATCH of an absent document still answers 404
+            // not_found, and PATCH of a document that exists still answers 200.
+            //
+            // It also made a live diagnosis harder than it needed to be. A
+            // consumer met a document that reads fine and refuses every write,
+            // and this probe was the obvious suspect precisely because it sits
+            // on one of the three write paths - but PUT uses `get()` and DELETE
+            // uses `remove()`, neither touches `exists()`, and all three answer
+            // the same 404. The probe was never the cause and could not have
+            // been; see the ghost-document note in CLAUDE.md.
             smartbotic::database::Client::Failure failure;
             uint64_t v = ttl ? d->db.client().patchWithTtl(t.qualified, id, patchBody, *ttl, failure)
                              : d->db.client().patch(t.qualified, id, patchBody, failure);

+ 60 - 0
tests/test_api_integration.cpp

@@ -4696,3 +4696,63 @@ TEST_F(ApiFixture, AKeyWithNoOriginAllowListStillListsFromAnywhere) {
     ASSERT_TRUE(res);
     EXPECT_EQ(res->status, 200) << "an empty allow-list means ANY origin: " << res->body;
 }
+
+// ---------------------------------------------------------------------------
+// The PATCH write path reports an absent document ITSELF, with no exists()
+// probe in front of it.
+//
+// There used to be a `Client::exists` probe there, and it was removed because
+// `exists` cannot tell "no such document" from "the call failed" - so a
+// transport blip answered an UNRETRYABLE 404 for a document that exists. This
+// pins the pairing that made the deletion safe: the absent case must still be
+// 404 (so `patch()` really does report it), and the present case must still be
+// 200 (so nothing about the probe was load-bearing).
+//
+// It is deliberately a PAIR. The 404 half alone would pass equally well against
+// a route that refused everything, which is a worse defect than the one being
+// fixed.
+//
+// WHAT THIS TEST DOES NOT COVER, stated because it would otherwise read as
+// proof of the deletion and is not: it passes IDENTICALLY with the probe in
+// place, because the probe produced the same two answers. Nothing here can see
+// whether the probe exists - that would need a round-trip count or an injected
+// transport failure, and the fixture offers neither. What it pins is the FACT
+// the deletion rests on: that `patch()` reports the absent case itself. If a
+// later change broke that, this goes red and the deletion stands revealed as
+// unsafe, which is the useful direction.
+// ---------------------------------------------------------------------------
+TEST_F(ApiFixture, PatchReportsAnAbsentDocumentWithoutAnExistenceProbe) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","noprobe"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/noprobe/documents";
+
+    // Absent: still 404, and still the slug a caller branches on.
+    auto missing = c.Patch((docs + "/definitely-not-here").c_str(),
+                           nlohmann::json::object().dump(), "application/json");
+    ASSERT_TRUE(missing);
+    EXPECT_EQ(missing->status, 404);
+    EXPECT_EQ(nlohmann::json::parse(missing->body)["error"]["code"], "not_found");
+
+    // Present: still 200. An EMPTY patch is used on purpose - that is the probe
+    // a consumer reached for when diagnosing a document that would not accept
+    // writes, so it is the exact shape worth pinning.
+    auto made = c.Post(docs.c_str(), nlohmann::json{{"v",1}}.dump(), "application/json");
+    ASSERT_TRUE(made); ASSERT_EQ(made->status, 201);
+    const std::string id = nlohmann::json::parse(made->body)["id"];
+    auto empty = c.Patch((docs + "/" + id).c_str(), nlohmann::json::object().dump(),
+                         "application/json");
+    ASSERT_TRUE(empty);
+    EXPECT_EQ(empty->status, 200) << empty->body;
+
+    // And the merge still works, so the route was not reduced to a no-op.
+    auto merged = c.Patch((docs + "/" + id).c_str(), nlohmann::json{{"w",2}}.dump(),
+                          "application/json");
+    ASSERT_TRUE(merged); ASSERT_EQ(merged->status, 200);
+    auto read = c.Get((docs + "/" + id).c_str());
+    ASSERT_TRUE(read); ASSERT_EQ(read->status, 200);
+    const nlohmann::json body = nlohmann::json::parse(read->body);
+    EXPECT_EQ(body["v"], 1) << "the empty patch or the merge dropped an existing field";
+    EXPECT_EQ(body["w"], 2);
+}