Jelajahi Sumber

docs: RETRACT the id retraction - .insert() DOES honour an id refs SV-43 SV-48

api/llms.txt said "THE FUNCTION BUILDER ASSIGNS DOCUMENT IDS. A function CANNOT
choose one" from 0.22.3 until today. It was false, and the live risk was not the
sentence - it was somebody making the server match it. A consumer's reviewer
registration keys rows on a normalised e-mail address, so that change would have
locked out every new reviewer.

host_context.cpp:1851 insert() reads payload.doc.id and passes it to
client().insert(); documentFrom() erases it from the stored BODY because the id
is the row's identity rather than a field, and that erase line is what I read as
the id being discarded. git log -L bottoms out at fc63a26, the commit that
created the runner, so the behaviour has never changed - only the documentation
moved. Refuted independently by novitax measuring deployed 0.22.3.

The retraction was written while correcting a genuine earlier error and went
PAST the truth. An over-correction reads as diligence and inherits credibility
from the real error it fixes, which is a shape this file had not recorded.

Corrected, including two errors found in the correction itself by an independent
re-verification against source:
- `.insert()` takes ttl_seconds ONLY; ifVersion is refused on an insert too. My
  first fix claimed it took both.
- a taken id is 409 duplicate_id against database 2.12.1+ and duplicate_values
  against anything older, so the slug is conditional rather than absolute.

Also now documented: a NON-STRING id is not honoured and is still erased, so
{id: 123} loses the field AND gets a server id; and .store() places the id in
the call object rather than in a document, where an id inside metadata is
discarded - the same silent ignoring _id gets on an insert.

The real finding is the asymmetry, which is a better thing to have written down
than either version of the limitation: `id` is honoured, `_id` is silently
ignored, and the ignored one still returns {id} and still reports success. That
explains a consumer's throttle admitting 6 of 6 against a limit of 3 without
needing the capability to be absent - no collision, so the AlreadyExists branch
is unreachable and every window row sits at 1.

chosenInsertId() is extracted as a pure seam because nothing pinned this: no
test reached the id branch, so the suite could not contradict the wrong sentence.
Falsified both ways - implementing the behaviour llms.txt claimed turns the
HONOURS test red while IGNORES stays green, and honouring _id as a fallback does
the reverse. Coverage boundary is stated in the test file: these pin the
identity decision, not that the id reaches the database.

Also fixes the filter example, which interpolated a path parameter straight into
topic:eq:${...}. Filter values are JSON-parsed with a fallback to a literal
string, so a topic of 2026 or true changes type and answers 200 with an empty
array - indistinguishable from an empty collection. Now JSON.stringify, with the
reason beside it, since that is the line people copy.

1544/1544 tests pass.
fszontagh 5 hari lalu
induk
melakukan
5d0e5db83a
3 mengubah file dengan 94 tambahan dan 10 penghapusan
  1. 10 5
      api/llms.txt
  2. 34 5
      runner/src/host_context.cpp
  3. 50 0
      runner/tests/host_context_test.cpp

+ 10 - 5
api/llms.txt

@@ -499,7 +499,11 @@ export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method:
 
 export default async function (ctx) {
   const docs = await ctx.collections('kb_chunks')
-      .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
+      // JSON.stringify, NOT bare interpolation: a filter value is JSON-parsed
+      // with a fallback to a literal string, so a bare topic of `2026` or `true`
+      // is read as a number or a boolean and matches nothing, answering 200 with
+      // an empty array - indistinguishable from an empty collection.
+      .filter(`topic:eq:${JSON.stringify(ctx.params.topic)}`).limit(20).find();
   const hits = await ctx.collections('kb_chunks')
       .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
   ctx.log('found', docs.length, 'documents');
@@ -522,10 +526,11 @@ export default async function (ctx) {
 - **A project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
 - **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
 
-- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
-- **THE FUNCTION BUILDER ASSIGNS DOCUMENT IDS. A function CANNOT choose one, and there is no upsert.** This is the single most important difference between `ctx.collections(...)` and the HTTP routes, and this file previously implied the opposite. `.insert(doc)` returns `{id}` with an id the SERVER generated: an `id` or `_id` in the body is stripped (the same reserved-field strip the HTTP route does), and `.insert(doc, {id})` is refused by name because `ttl_seconds` is the only option it takes. `.update(id, doc)` on a document that does not exist is **404 `not_found`** - it is a replace, never an upsert - and `.increment(id, deltas)` likewise requires the row to exist.
-  **SO THE COUNTER PATTERN THIS FILE AND OUR OWN MESSAGES RECOMMENDED IS IMPOSSIBLE HERE, AND IT FAILS SILENTLY RATHER THAN LOUDLY.** The advice was "increment; on NotFound insert with the starting value at a FIXED id; on AlreadyExists increment again". That is correct for the **C++ client**, where an id is an argument, and it was transplanted here without checking that this surface has the capability. From a function, "insert at a fixed id" is really "insert a NEW row", so the `AlreadyExists` branch is **unreachable** - there is never a collision - and a throttle built this way creates a fresh row per call, every one at `1`. Measured by a consumer on prod: **six of six calls admitted against a limit of three.** Fourteen of their unit tests passed, because their fake honoured the id in the body, which the real API discards.
-  **THE PATTERN THAT WORKS, and it needs an index**: find the window row by FILTER rather than by id, and make the create race safe with a **composite unique index** on the identifying fields (for a throttle: kind, key, bucket). Two runs racing to create the same window means one gets **409 `duplicate_values`**, and the loser re-finds the winner's row and increments that. Verified live by the consumer who found this: six sequential calls on a limit of three gave 3 allowed then 3 refused, and **five SIMULTANEOUS calls gave exactly 3 allowed and 2 refused with one window row at `3`**. Without the index the concurrent case silently allows **twice** the limit, which is the only condition a throttle exists for - so the index is not an optimisation here, it is the correctness.
+- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP. **QUOTE ANY CALLER-SUPPLIED FILTER VALUE WITH `JSON.stringify`.** The value is run through `json::parse` with a fallback to a literal string, so a path parameter or query value that happens to parse as JSON changes type under you: a topic of `2026` becomes the number 2026 and a topic of `true` becomes a boolean, neither of which matches the string stored in the field. The result is **200 with an empty array**, which is indistinguishable from the collection genuinely having no such rows - so it fails silently and in the direction nobody checks.
+- **`.insert(doc)` HONOURS AN `id` INSIDE THE DOCUMENT OBJECT - that is the idiom for an idempotent write - BUT `_id` IS SILENTLY IGNORED, AND THAT ASYMMETRY IS THE WHOLE TRAP.** `id` becomes the document's identity and is stripped from the stored BODY (it is the row's name, not one of its fields), so it reads back as `_id` and not as `id`. `_id` in the body is stripped as read-only metadata and **does NOT set the identity**, so an insert keyed on `_id` quietly gets a server-generated id instead - the row is stored, the call returns `{id}`, and the id is not the one you asked for. A taken id is **409**, carrying `duplicate_id` against database 2.12.1 or newer and `duplicate_values` against anything older - that refusal is what makes the pattern idempotent rather than silently duplicating. **A NON-STRING `id` IS NOT HONOURED AND IS STILL REMOVED**, so `{id: 123}` loses the field AND gets a server-generated id: quote it. `.insert(doc, {id})` is refused by name, because the id belongs in the document and **`ttl_seconds` is the only option `.insert()` takes** - `ifVersion` is refused on an insert too, since a document that does not yet exist has no version to be conditional on. **`.store()` PLACES THE ID DIFFERENTLY, and the difference is exactly the kind that caused this entry's own error**: `.store()` takes ONE object, so `id` sits beside `text` in that call (`.store({id, text})`) rather than inside a nested document - and an `id` tucked inside `metadata` is discarded, the same silent ignoring `_id` gets on an insert. `.update(id, doc)` on a document that does not exist is **404 `not_found`** - it is a replace, never an upsert - and `.increment(id, deltas)` likewise requires the row to exist.
+  **THIS FILE SAID THE OPPOSITE FROM 0.22.3 UNTIL 2026-11-21 - "the builder assigns document ids, a function CANNOT choose one" - AND IT WAS SIMPLY WRONG.** Refuted by a consumer measuring the deployed 0.22.3 (`.insert({id:'chosen-one'})` returns `{id:'chosen-one'}` and reads back at that `_id`; a second insert at it is 409; `_id` is ignored) and confirmed in the source of the serving artefact: `insert()` reads `payload.doc.id` and passes it as the document id, in code dating from the commit that created the runner, so **the behaviour has never changed and only the documentation moved.** The wrong sentence was written while correcting a different error and corrected past the truth. A consumer's live reviewer registration depends on e-mail-as-id, and had anyone made the server match this file, that would have locked out every new reviewer.
+  **WHAT THE RETRACTED PARAGRAPH GOT RIGHT IS THE SYMPTOM, AND THE CAUSE IS ONE CHARACTER AWAY FROM WHAT IT CLAIMED.** A counter built as "increment; on NotFound insert the starting value at a FIXED id; on AlreadyExists increment again" **does work** when the key is `id`: the collision is real, so the `AlreadyExists` branch is reachable. It fails exactly as described - a fresh row per call, every one at `1`, **six of six calls admitted against a limit of three**, measured on prod - when the id is passed as `_id` or as an option, because then nothing sets the identity and every "insert at a fixed id" is an insert of a NEW row. So the failure was real and the diagnosis was one layer off: the capability exists and that spelling does not reach it. **An insert whose chosen id does not come back in `{id}` is the tell**, and it is worth asserting rather than assuming, because the row stores and the call succeeds either way.
+  **THE INDEX-BASED PATTERN REMAINS CORRECT AND IS STILL THE ONE TO REACH FOR WHEN THE WINDOW IS NOT ADDRESSABLE BY ID**: find the row by FILTER, and make the create race safe with a **composite unique index** on the identifying fields (for a throttle: kind, key, bucket). The loser of a race gets **409 `duplicate_values`**, re-finds the winner's row and increments that. Verified live: six sequential calls on a limit of three gave 3 allowed then 3 refused, and **five SIMULTANEOUS calls gave exactly 3 allowed and 2 refused with one window row at `3`**. Where the window IS addressable by a deterministic id, the fixed-id insert is race-safe for the same reason by way of `duplicate_id`, and needs no index.
 - **A FILTERED `.find()` NEEDS THE `list` GRANT, NOT `read`.** `read` covers `.get(id)` only. A policy of read/insert/update therefore throws on every `.find()`, and because the scope refusal deliberately cannot distinguish "not granted" from "does not exist", the symptom is simply that your function fails - which reads as the feature being broken rather than as a missing grant. The message does name `operation 'list'`; read it rather than inferring. Op to grant, in full: `.find()` is `list`, `.get()` is `read`, `.insert()`/`.store()` are `insert`, `.update()`/`.patch()`/`.increment()` are `update`, `.delete()` is `delete`, `.search()` is `search`.
 - **Write options**, previously undocumented. `ttl_seconds` is accepted by `.insert()`, `.update()`, `.patch()` and `.store()`; it sets or clears a document's expiry, and **absent is not zero** - omitting it leaves an existing expiry untouched while `0` clears it, so a plain `.patch()` cannot accidentally make a temporary document permanent. **`ifVersion: n`** makes the write conditional on the document still being at version `n` (as returned in `_version`); a lost race is **409** `version_conflict` carrying `current_version`, which means "someone else has it" and should be handled by dropping the work or re-reading, never by retrying the same write. `ifVersion` must be a positive integer - version 0 does not exist, since a first write produces 1. It is accepted by **`.update()` and `.patch()` only**: `.insert()` refuses it by name, because there is no existing version for a document that does not yet exist. `ttl_seconds` together with `ifVersion` is refused (`unsupported_combination`) rather than silently dropping one. A conditional `.update()` returns `{id, version}`; the unconditional form returns `{id}`.
 - Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters, embedTimeoutMs?})`, returning an **array** of hits, and `.store({text|vector, metadata, embedTimeoutMs?})`. Embedding resolves through the normal precedence, so a project's provider override applies.

+ 34 - 5
runner/src/host_context.cpp

@@ -394,6 +394,36 @@ nlohmann::json stripDbMetadata(nlohmann::json doc) {
     return doc;
 }
 
+/// The identity an `.insert(doc)` asks for, or "" to let the server assign one.
+///
+/// `id` INSIDE THE DOCUMENT is honoured - it is how a function writes an
+/// idempotent row, exactly as POST /documents honours `body.id` - while `_id`
+/// is read-only metadata and is IGNORED. documentFrom() erases BOTH from the
+/// stored body, so the asymmetry leaves no trace in what lands on disk: one
+/// spelling becomes the row's name, the other simply vanishes, and both calls
+/// return `{id}` and report success.
+///
+/// THAT IS WHY THIS IS A NAMED FUNCTION WITH ITS OWN TESTS rather than three
+/// lines inside insert(). `api/llms.txt` asserted the opposite of this
+/// behaviour for a release - "the builder assigns document ids, a function
+/// CANNOT choose one" - and nothing in the suite could contradict it, because
+/// no test exercised the id branch at all. A consumer's live reviewer
+/// registration keys its rows on a normalised e-mail address, so anyone who
+/// had made the server match that sentence would have locked out every new
+/// reviewer. The behaviour dates from the commit that created this runner; only
+/// the documentation ever moved.
+///
+/// A NON-STRING id is not honoured: `{id: 123}` answers "" and is still erased
+/// from the body, so the field is lost AND the server names the row. Refusing
+/// it would be defensible and is a behaviour change, so it is documented rather
+/// than quietly altered here.
+std::string chosenInsertId(const nlohmann::json& payload) {
+    if (!payload.is_object() || !payload.contains("doc")) return "";
+    const nlohmann::json& doc = payload.at("doc");
+    if (!doc.is_object() || !doc.contains("id") || !doc.at("id").is_string()) return "";
+    return doc.at("id").get<std::string>();
+}
+
 /// The deltas a `.increment(id, {field: n})` call carries.
 ///
 /// No `{"data": ...}` unwrapping, for the reason documentFrom() gives: that
@@ -1851,11 +1881,10 @@ struct HostContext::Impl {
     nlohmann::json insert(const std::string& collection, const nlohmann::json& payload) {
         nlohmann::json doc = documentFrom(payload);
         // An explicit id is honoured, exactly as POST /documents honours
-        // body.id, so a function can write an idempotent row.
-        std::string id;
-        if (payload.at("doc").is_object() && payload.at("doc").contains("id") &&
-            payload.at("doc").at("id").is_string())
-            id = payload.at("doc").at("id").get<std::string>();
+        // body.id, so a function can write an idempotent row. Extracted to a
+        // pure seam so the `id` honoured / `_id` ignored asymmetry is pinned by
+        // a test; see chosenInsertId() for why that is not optional.
+        const std::string id = hostdetail::chosenInsertId(payload);
         // `ttl_seconds` absent is 0 here and only here: an insert has no stored
         // expiry to preserve, so "say nothing" and "no expiry" are the same
         // thing - which is also what POST /documents does with the parameter.

+ 50 - 0
runner/tests/host_context_test.cpp

@@ -73,6 +73,7 @@ std::optional<std::string> base64Decode(std::string_view in);
 std::optional<uint32_t> ttlFrom(const nlohmann::json& payload);
 std::optional<uint64_t> ifVersionFrom(const nlohmann::json& payload);
 nlohmann::json stripDbMetadata(nlohmann::json doc);
+std::string chosenInsertId(const nlohmann::json& payload);
 nlohmann::json incrementDeltasFrom(const nlohmann::json& payload);
 uint64_t jobRunAfterSec(const nlohmann::json& payload, int64_t wall_now_ms);
 nlohmann::json jobTrigger(const nlohmann::json& payload, uint32_t depth,
@@ -687,6 +688,55 @@ TEST(HostDetail, ClientMetadataIsStrippedBeforeAWriteButNothingElseIs) {
     EXPECT_TRUE(detail::stripDbMetadata(nlohmann::json(7)).is_number());
 }
 
+TEST(HostDetail, AnInsertHONOURSanIdInTheDocumentBody) {
+    // THE REGRESSION THIS EXISTS FOR IS A DOCUMENTATION ONE THAT ALMOST BECAME A
+    // CODE ONE. api/llms.txt asserted for a release that "the builder assigns
+    // document ids, a function CANNOT choose one". It was false, and nothing in
+    // this suite could say so, because no test reached the id branch - so the
+    // live risk was somebody making the server match the file. A consumer's
+    // reviewer registration keys rows on a normalised e-mail address, and that
+    // change would have locked out every new reviewer.
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"id", "chosen-one"}, {"note", "a"}}}}),
+              "chosen-one");
+
+    // An e-mail address is the live case, so it is the one pinned by name.
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"id", "probe@novitax.hu"}}}}),
+              "probe@novitax.hu");
+}
+
+TEST(HostDetail, AnInsertIGNORESanUnderscoreIdAndThatAsymmetryIsThePoint) {
+    // `_id` is read-only metadata, so it does NOT name the row - and because
+    // documentFrom() strips both spellings from the stored body, the two are
+    // indistinguishable in what lands on disk. Both calls return `{id}` and
+    // both report success; only the id differs, and only one of them is yours.
+    // This is the shape a consumer walked into: four probes covering `_id` and
+    // the option form, none covering `id`, and a confident wrong conclusion.
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"_id", "under-one"}, {"note", "d"}}}}), "");
+
+    // An empty answer means "let the server name it" rather than "no id", which
+    // is why the paired test above has to exist: a function that returned ""
+    // for EVERYTHING would pass this one.
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"note", "c"}}}}), "");
+
+    // A NON-STRING id is not honoured either, and the field is erased from the
+    // body regardless - so `{id: 123}` loses the field AND gets a server id.
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"id", 123}}}}), "");
+    EXPECT_EQ(detail::chosenInsertId({{"doc", {{"id", nullptr}}}}), "");
+
+    // Malformed payloads answer rather than throw: an id is optional on an
+    // insert, unlike documentId(), which requires one for update/patch/delete.
+    EXPECT_EQ(detail::chosenInsertId(nlohmann::json::object()), "");
+    EXPECT_EQ(detail::chosenInsertId({{"doc", 7}}), "");
+    EXPECT_EQ(detail::chosenInsertId(nlohmann::json(7)), "");
+}
+
+// WHAT THESE TWO DO NOT COVER, stated because they would otherwise read as
+// proof of the whole behaviour. They pin the IDENTITY decision, which is the
+// half that was undocumented and unpinned. They do NOT prove the id reaches
+// the database, nor that documentFrom() erases it from the stored body - both
+// need a live insert, so they live in packaging/devstack and in the HTTP twin
+// (tests/test_api_integration.cpp posts {"id":"m1"} and reads back _id "m1").
+// A change that made insert() stop PASSING this id would leave these green.
 TEST(HostDetail, AVersionConflictIsReportedByCodeNotByMessage) {
     using Client = smartbotic::database::Client;
     // The database says a stale version with ErrorCode::Aborted and reports the