ソースを参照

docs: RETRACT the counter pattern - a function cannot choose a document id

MY ADVICE WAS WRONG TWICE AND COST A CONSUMER AN EVENING AND A WORKING
THROTTLE. I told novitax, and this file implied, that a counter should be built
by "increment; on NotFound insert with the starting value at a FIXED id; on
AlreadyExists increment again". That dance cannot be performed from a function.

Verified in our own source after their report, not taken on trust:
`.insert(doc, options)` takes `ttl_seconds` and nothing else, so `{id}` is
refused by name; `documentFrom()` strips `id`/`_id` from the body; `.update()`
is a replace and 404s on a missing row; `.increment()` requires the row.

So "insert at a fixed id" is really "insert a NEW row", the AlreadyExists
branch is UNREACHABLE because there is never a collision, and the failure is
silent: a throttle built that way creates a fresh row per call, each at 1.
Measured by them 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 that the real API discards.

WHERE IT CAME FROM IS THE GENERALISABLE PART: verbatim from
`client.hpp:567-570`, which is the C++ CLIENT's comment, where an id IS an
argument. I transplanted a remedy from one surface to another without checking
the second surface had the capability. That is the precedent-does-not-transfer
error this project already records - the mechanism was identical and the
capability was not - and the cost is higher in a doc than in a message,
because a doc is read by people who will not be corrected.

THE WORKING PATTERN IS DOCUMENTED WITH THEIR MEASUREMENTS, because it is not
obvious and the index in it is not an optimisation: identify the window by
FILTER, and make the create race safe with a COMPOSITE UNIQUE INDEX on the
identifying fields, so a losing racer gets 409 duplicate_values, re-finds the
winner's row and increments that. They verified five SIMULTANEOUS calls giving
exactly 3 allowed and 2 refused with one row at 3; without the index the
concurrent case silently allows TWICE the limit, which is the only condition a
throttle exists for.

ALSO DOCUMENTED, from the same report: a filtered `.find()` needs the `list`
grant, not `read` (`read` is `.get(id)` only), with the full op-to-grant table.
Their symptom was "the throttle is down", because the scope refusal cannot
distinguish "not granted" from "does not exist" - which is deliberate and
right, and is exactly what makes it unguessable from outside.

NOT changed, and raised for a decision rather than taken: whether `.insert`
should accept an id or `.update` should upsert. Either would make a per-key
counter two calls instead of three and need no index. That is a new surface on
the function API, so it is the owner's call, not mine - and the three-call
shape works today.

openapi.json is deliberately untouched here: `ctx.collections` appears in it
ZERO times, so it documents the HTTP surface only and the function caveat
belongs in llms.txt. Checked rather than assumed.
fszontagh 6 日 前
親
コミット
bca26ac681
3 ファイル変更、6 行追加、2 行削除
  1. 1 1
      VERSION
  2. 4 0
      api/llms.txt
  3. 1 1
      api/openapi.json

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.22.2
+0.22.3

+ 4 - 0
api/llms.txt

@@ -523,6 +523,10 @@ export default async function (ctx) {
 - **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.
+- **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.
 - **An UNKNOWN option on a vector `/search` body is now refused with 422 `unknown_option`, naming every unrecognised key.** It used to be accepted and ignored, which produced silently wrong answers rather than errors. Measured on prod before the fix: `topK: 3` (the camelCase misspelling) returned **five** rows, the default, so a caller asking for three got five and was told nothing; `minScore: 0.99` returned rows where the correct `min_score: 0.99` returns none; and **`filter:` in the singular returned the rows the caller meant to EXCLUDE**. The accepted set is `query_text`, `query_vector`, `top_k`, `min_score`, `filters`, `embedTimeoutMs`. Matching is exact and case-sensitive, so `Top_K` is refused rather than quietly accepted as a second spelling.

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.22.2",
+    "version": "0.22.3",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {