Prechádzať zdrojové kódy

docs: record what the 0.5.0 release and deploy taught

CLAUDE.md gains the facts that cost time today and would cost it again.

Two deploy traps. `--rebuild-base` is required when DB_CLIENT_VERSION
moves, because the client is baked into the Docker base image - and
devstack/run-tests.sh installs the client debs explicitly, so the TEST
path can sit on a newer client than the RELEASE path. A green suite is
not evidence about the packages, which is exactly how this one got past
683 passing tests. And `systemctl start` on an already-running unit is a
no-op, so config written after apt needs a restart: the package postinst
had already started the runner, and health reported a pool size the file
on disk disagreed with, one second apart.

Three error-mapping rules, each of which was wrong in the deployed
0.4.0. FailedPrecondition means three different things and must be
branched on reason - mapping the bare code to 422 told a caller that a
read-only database was its own validation mistake. A version conflict is
Aborted and maps to 409, not the 503 "retry as-is" it used to fold into,
which is the opposite of the required instruction. And a patch with null
REMOVES the field rather than storing it.

The function-runtime section records why wall time has two ceilings and
why job runs need their own pool lane (a lease is held for a run's whole
duration, so without one N slow jobs starve every interactive route),
that jobs.enabled is off by default and must be turned on or cron
silently enqueues work nothing drains, that delivery is at-least-once,
and that the loop guard reads provenance from the audit trail rather than
from a field in user documents.
fszontagh 1 mesiac pred
rodič
commit
acccc13b70
1 zmenil súbory, kde vykonal 15 pridanie a 2 odobranie
  1. 15 2
      CLAUDE.md

+ 15 - 2
CLAUDE.md

@@ -45,7 +45,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - TS: no `any`, no TS `enum`, no constructor parameter-property shorthand (tsconfig `erasableSyntaxOnly`). Iterating parsed JSON: bind to a named var first (range-for over `nlohmann::json::parse(...)[...]` dangles).
 - Commits: conventional prefixes (`feat`/`fix`/`build`/`docs`/`test`). Branch for feature work; `main` is pushed to `ssh://git.smartbotics.ai:10022/fszontagh/smartbotic-vectorapi.git`.
 
-## Function runtime (slice 1, in progress)
+## Function runtime
 
 - **A function is a principal, not a key holder** (`principal.hpp`). `requireCapabilityCore()` answers project/scope/rate-limit questions for any caller; the `ApiKey` overload adds the things only an HTTP request has (Origin allow-list, captcha), because those are meaningless for a cron or event run. One implementation, so function access and HTTP access cannot drift.
 - **A code push can never widen access.** `mergeForCodePush()` (`function_record.hpp`, pure) takes `policy` and `enabled` from the stored row and **never reads the ones in the payload** - not unioned, not used as a fallback. A first registration inherits the project default. Identity is `function_id` from the script's `on` block and `path` carries no meaning, so a rename keeps the row and its policy.
@@ -55,6 +55,13 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving — re-resolving IS the rebinding window. One resolution, one classification.
+- **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) and `job` (reached only by being enqueued, which is where slow work belongs). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug.
+- **Wall time has TWO ceilings** (`functions/wall_budget.hpp`): an HTTP one (~2 s, which `RunnerPool::readTimeoutSec` must exceed) and a JOB one, which is exempt because a queue-claimed run holds no socket. `RunService::run` takes the kind as a PARAMETER, never inferred from the descriptor, and defaults to Http - the narrow budget - so a caller that forgets is slow rather than dangerous. Precedence: `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`, resolved by the pure `resolveWallBudget()`. The engine's `JsLimits::wall_time_ms` is raised to the highest ceiling at construction, or the clamp inside `JsRuntime::run` would kill every job at the HTTP value.
+- **Job runs draw from their OWN pool lane.** A lease is held for a run's whole duration, every `ctx.fetch` included, so without a lane N slow jobs leave one runtime for every interactive route and the second overlapping HTTP run blocks until the read timeout fires - a 503 from a healthy runner. Worst-case memory is `(pool + job_pool) x memory_limit_bytes`, so the two lanes ADD.
+- **The database-event loop guard reads the event's actor** (client 2.12.0). Every write a function makes is stamped `fn:<project>/<id>:<depth>` via the `actor` parameter, and `Event::actor` carries it back - so provenance costs nothing and lives in the audit trail, NOT in a field inside user documents (which would travel into every export forever). A chain is refused past `events.max_depth` generations and logged at error.
+- **Delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs again, so cron and db functions must be idempotent. `singleFlight` (default true for cron) skips a tick while the previous run is still going, which bounds stacking but is not exactly-once.
+- **`jobs.enabled` is OFF by default in the runner**, so a runner upgrade never starts draining a queue in a deployment whose server has no scheduler. On a host that wants cron it MUST be turned on, or the scheduler enqueues work nothing ever runs - the most confusing possible way for cron to look broken.
+- **Project secrets** live in `<project>:vectorapi_secrets`, encrypted and deliberately NOT in the collection registry - so the documents API and `ctx.collections` both 404 it, and even a policy granting every collection cannot read it. Writes are admin-only; no GET ever returns a value. A `SVAPI_FN_<project>__<NAME>` host variable WINS over a stored secret of the same name, which is the break-glass a stolen API credential cannot shadow.
 - **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run.
 - **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN_<project>__<NAME>` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.<NAME>`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets.
 - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
@@ -73,9 +80,15 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **DB client strips an `id` field from stored doc bodies.** So API keys store their stable id as `key_id` in the body (exposed as `id` externally); document handlers strip `id` before insert and use the separate id param.
 - **Debian 13 (trixie) gRPC cmake config is broken** unless `protobuf-compiler-grpc` + `libgrpc++-dev` + `libprotobuf-dev` are installed — `find_package(gRPC CONFIG)` (used transitively by `smartbotic-db-clientConfig.cmake`) fails on a `gRPCTargets.cmake` referencing missing plugin files. The Docker base installs them.
 - **Abseil ABI:** `smartbotic-database`/client debs must be built against the system's current Abseil; a stale build crash-loops on `libabsl_*.so.<old>`. Rebuild the DB if it won't start.
-- **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`, default 2.11.3-1 = what prod runs). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together.
+- **`--rebuild-base` is required when `DB_CLIENT_VERSION` moves.** The client version is baked into the Docker BASE image, so bumping the variable alone leaves the release build compiling against the old headers - it fails on the new entry points, or worse, silently links the old ones. Note `devstack/run-tests.sh` installs the client debs explicitly, so the TEST path can be on a newer client than the RELEASE path: a green suite is not evidence about the packages.
+- **`systemctl start` on an already-running unit is a no-op.** A package postinst starts the service, so any config written AFTER apt needs a `restart`, not a `start` - otherwise the process keeps the config that existed at install time and the file on disk disagrees with the running state. Compare the file mtime against `systemctl show -p ActiveEnterTimestamp` when a setting appears not to apply.
+- **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together.
 - **The apt repo drops superseded versions on publish**, so `pkg=<old version>` is uninstallable afterwards. Old `.deb`s survive in `$DEB_REPO_DIR/dist`; `build.sh` vendors the pinned client from there into `packaging/vendor/`, and a prod rollback needs them scp'd to the target first.
 - **The Void dev host can no longer build the C++ natively.** Void moved to protobuf 35 / gRPC 1.83; protobuf 35 removed `google/protobuf/map_field_inl.h`, which the database's generated protos include, so `libsmartbotic-db-client` neither compiles nor links there (the installed `.so` still wants `libgrpc++.so.1.61`). Release builds are unaffected because they run in the Debian 13 image. For local backend work use `packaging/devstack`; `ctest` cannot run on this host.
+- **`FailedPrecondition` means three different things** and must be branched on `FailureDetail.reason`: `missing_parent` and `delete_restricted` are 422, `read_only` is **503**, and an absent or unrecognised reason is **500**, never a guessed 422. Mapping the bare code to 422 told a caller that a read-only database was its own validation mistake, so it would fix its payload and retry forever instead of waiting. Use the `FailureDetail&` overloads wherever a call offers one - the reason-less `Failure` form cannot tell these apart.
+- **A version conflict is `ErrorCode::Aborted`** (client 2.12.0) carrying `currentVersion`, and maps to **409** `version_conflict`. It used to arrive as `Unknown` and fold into 503 "retry as-is", which is the opposite of the required instruction: re-read first. Never match on the message text for this.
+- **`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.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.