askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
doc_pages.tsv · 799.2 KB · 10613 lines
| 1 | id title category nav_order summary content |
| 2 | why Why DBBASIC — The Advantages, Honestly Stated Start Here 100 A plain-spoken case for DBBASIC's design — live changes, apps as data, one permission engine — with its current boundaries stated just as plainly. "DBBASIC is a small server with strong opinions. This page states the |
| 3 | advantages plainly, and the boundaries next to them, because a claim |
| 4 | without its boundary is marketing. |
| 5 | |
| 6 | ## Change is live |
| 7 | |
| 8 | Objects load per execution: edit an object and the next request serves |
| 9 | the new code. Schemas, permission rules, routes, and site pages are |
| 10 | data, changed over HTTP. Only changes to the server file itself need a |
| 11 | restart (seconds). There is no build, no deploy pipeline, no migration |
| 12 | ceremony. |
| 13 | |
| 14 | Safety comes from **reversibility instead of ceremony**: object source |
| 15 | is versioned with rollback, schemas keep history, records keep |
| 16 | changelogs, permission changes and admin actions are audited. Ship in |
| 17 | steps of one; undo in steps of one. |
| 18 | |
| 19 | ## Apps are data |
| 20 | |
| 21 | An application is a package: schema + permission rules + optionally one |
| 22 | page object ([the app suite](/docs/app-packages)). The server grows only |
| 23 | when a genuinely new *kind* of capability appears — search, sharing, |
| 24 | file storage, AI — and each lands once, generically, then every app |
| 25 | uses it by declaring so in its schema. |
| 26 | |
| 27 | The consequence: **capability grows with data, not code.** Add a |
| 28 | schema for any obscure domain and it immediately has validated writes, |
| 29 | generated forms, search, sharing, MCP tools, and AI conversation about |
| 30 | it. Nobody ships function-calling for your beekeeping records; here it |
| 31 | is free. |
| 32 | |
| 33 | ## One permission engine, every surface |
| 34 | |
| 35 | Browser pages, the records API, MCP agents, global search, file |
| 36 | downloads, and AI tool calls all pass the same policy: role rules, row |
| 37 | filters (`$user_id`, `$accessible_projects`, `$owned_projects`), field |
| 38 | redaction, audit. A rule written once binds everywhere — no surface can |
| 39 | leak what another surface hides. Sharing is records (`project_access` |
| 40 | rows), so granting and revoking are audited record writes. |
| 41 | |
| 42 | ## Fast because it does less |
| 43 | |
| 44 | A request here is: a dict-router match, a TSV read the OS page cache |
| 45 | already holds, permission string-checks, JSON out. No ORM, no |
| 46 | connection pool, no query planner, no middleware stack, no signal |
| 47 | cascade. At personal-and-team data sizes (thousands of rows per |
| 48 | collection), scanning a hot file in-process beats an indexed query |
| 49 | across a socket. |
| 50 | |
| 51 | **Boundary:** this inverts somewhere past hundreds of thousands of rows |
| 52 | in one collection. Collections are per-file, so a hot one can gain an |
| 53 | index later without changing the platform; the search contract promises |
| 54 | no ranking, so an index can slot in behind it. |
| 55 | |
| 56 | ## AI-native without AI lock-in |
| 57 | |
| 58 | The whole admin surface is MCP; agents operate the server with their |
| 59 | own identities and audited sessions. Users store their own provider |
| 60 | keys (write-only), pick their own models, and hand the AI a chosen |
| 61 | subset of tools ([the shell](/docs/shell-and-ai)). The server never meters |
| 62 | your tokens or requires a vendor. An AI acting for a user is exactly as |
| 63 | powerful as the user — no more. |
| 64 | |
| 65 | ## Yours |
| 66 | |
| 67 | Stdlib-only Python plus uvicorn; one VM; data in human-readable TSV and |
| 68 | JSON files you can grep, back up, and take elsewhere. Small enough for |
| 69 | one person to read. MIT licensed, with the operator console |
| 70 | (Scroll) open source |
| 71 | too. Multi-domain hosting means one instance serves many sites with one |
| 72 | identity store and one audit trail. |
| 73 | |
| 74 | ## Current boundaries, plainly |
| 75 | |
| 76 | - One VM; no cluster correctness claims. |
| 77 | - Realtime push is live over one permission-filtered websocket (`/ws`); |
| 78 | the durable event log remains as the poll fallback. |
| 79 | - A background-job runtime exists (`app-runner`, plus the daemon's |
| 80 | scheduler and queue); what it lacks is handlers for long media work |
| 81 | such as PDF extraction and thumbnails. |
| 82 | - Untrusted arbitrary code execution is not offered; object writes are |
| 83 | operator/admin actions, and the worker pool isolates processes without |
| 84 | CPU or memory limits. |
| 85 | - Self-service signup and password reset exist, off by default; signup |
| 86 | refuses to turn on until enforcement is on and no rule gives every |
| 87 | signed-in user unscoped access. Strangers still cannot run their own code. |
| 88 | - Permission enforcement is opt-in per deployment rather than the shipped |
| 89 | default (staging runs with it on). |
| 90 | |
| 91 | The direction on each is recorded in status. The rule for |
| 92 | new capability is unchanged: it must pass the same permission engine, |
| 93 | audit trail, and reversibility bar as everything before it. |
| 94 | " |
| 95 | quickstart Quickstart — From a Fresh VM to Your First App Start Here 110 A linear, thirty-minute path from a bare Debian/Ubuntu VM to a running DBBASIC Object Server with login, HTTPS, and your first app installed. "This is the linear path: a bare Debian/Ubuntu VM to a running object |
| 96 | server, a login, a public domain, and a first app installed — in one |
| 97 | sitting, about thirty minutes, most of it waiting on `apt`. Every step |
| 98 | is a real command you can paste. |
| 99 | |
| 100 | For the full reference (systemd hardening, journald caps, backups, |
| 101 | permission rollout, per-route proxy allowlists), see |
| 102 | [single-vm deployment](/docs/single-vm-deployment). This page is the happy |
| 103 | path; that one is the operator's manual. |
| 104 | |
| 105 | ```mermaid |
| 106 | flowchart LR |
| 107 | A[""Fresh VM<br/>+ a domain""] --> B[""Run the installer""] |
| 108 | B --> C[""Create your admin user<br/>+ enable login""] |
| 109 | C --> D[""Caddy: domain + TLS""] |
| 110 | D --> E[""Enable package installs""] |
| 111 | E --> F[""Install an app<br/>→ live at /notes""] |
| 112 | ``` |
| 113 | |
| 114 | ## 0. What you need |
| 115 | |
| 116 | - A small VM (a $5–$7 droplet is plenty) running Debian 12 or Ubuntu |
| 117 | 22.04+, with root or `sudo`. |
| 118 | - Optional but recommended: a domain name with an `A` record pointing at |
| 119 | the VM's IP, so Caddy can get you automatic HTTPS. |
| 120 | |
| 121 | ## One-click installs |
| 122 | |
| 123 | An installer such as GitStable's ""Install on DigitalOcean"" runs |
| 124 | `scripts/one-click-install.sh <release>` through the server's cloud-init |
| 125 | (`cloud-init.yaml`, `DBBASIC.md`). It does steps 1 to 3 below for you, installs |
| 126 | the apps to start with (home and menu, projects, notes, tasks, |
| 127 | files), with two |
| 128 | differences: HTTPS comes on the server's bare IP address (a Let's |
| 129 | Encrypt IP certificate) until you add a domain, and no admin is created. |
| 130 | Its permission policy is the rules those apps ship, enforced from the first start. |
| 131 | The server answers only `/health` and `/setup` until you open `/setup` with |
| 132 | the one-time setup code the installer showed you and choose your own email |
| 133 | and password (`object_setup.py` says why it works that way). Lost the code? |
| 134 | SSH in and do step 2: once an admin exists, setup is over. |
| 135 | |
| 136 | ## 1. Run the installer |
| 137 | |
| 138 | `--version 2026.11v1` installs that release instead of the newest `main`, |
| 139 | and `/health` then names the release and commit. |
| 140 | |
| 141 | |
| 142 | The installer is a readable script — download it, read it, run it. It |
| 143 | installs dependencies, creates the service user and layout, builds a |
| 144 | virtualenv, generates an admin token, and starts a systemd service on |
| 145 | `127.0.0.1:8001`. It is idempotent, so re-running it is safe. |
| 146 | |
| 147 | ```bash |
| 148 | git clone <repository-url> dbbasic-object-server |
| 149 | cd dbbasic-object-server |
| 150 | less scripts/install.sh # read it first |
| 151 | sudo bash scripts/install.sh |
| 152 | ``` |
| 153 | |
| 154 | When it finishes you have a running server. Confirm: |
| 155 | |
| 156 | ```bash |
| 157 | curl http://127.0.0.1:8001/health |
| 158 | ``` |
| 159 | |
| 160 | Your admin token lives in `/etc/dbbasic-object-server.env` as |
| 161 | `DBBASIC_ADMIN_TOKEN` (readable by root and the service group only). |
| 162 | Everything the installer did on purpose *not* to do — login, a public |
| 163 | domain, app installs — is below, as short deliberate steps. |
| 164 | |
| 165 | ## 2. Create your admin user and turn on login |
| 166 | |
| 167 | ```bash |
| 168 | cd /opt/dbbasic-object-server |
| 169 | sudo -u dbbasic DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data \ |
| 170 | .venv/bin/python object_identity_cli.py create-superuser \ |
| 171 | --user-id you --email you@example.com |
| 172 | ``` |
| 173 | |
| 174 | It prompts for a password twice (no echo) and stores only a scrypt hash |
| 175 | under the runtime data directory. Now enable password login and restart: |
| 176 | |
| 177 | ```bash |
| 178 | sudo sed -i 's/^DBBASIC_ENABLE_PASSWORD_LOGIN=false/DBBASIC_ENABLE_PASSWORD_LOGIN=true/' \ |
| 179 | /etc/dbbasic-object-server.env |
| 180 | sudo systemctl restart dbbasic-object-server |
| 181 | ``` |
| 182 | |
| 183 | ## 3. Put a domain and HTTPS in front |
| 184 | |
| 185 | Keep uvicorn bound to localhost and let Caddy terminate TLS. If a domain |
| 186 | points at the VM, this is all it takes: |
| 187 | |
| 188 | ```bash |
| 189 | sudo apt install -y caddy |
| 190 | sudo tee /etc/caddy/Caddyfile >/dev/null <<'EOF' |
| 191 | your-domain.com { |
| 192 | handle / { |
| 193 | rewrite * /objects/site_home |
| 194 | reverse_proxy 127.0.0.1:8001 |
| 195 | } |
| 196 | handle { |
| 197 | reverse_proxy 127.0.0.1:8001 |
| 198 | } |
| 199 | } |
| 200 | EOF |
| 201 | sudo systemctl reload caddy |
| 202 | ``` |
| 203 | |
| 204 | Caddy fetches a certificate automatically. Visit `https://your-domain.com` |
| 205 | — you should see the home object, and `https://your-domain.com/login` |
| 206 | should accept the user you just created. |
| 207 | |
| 208 | > The catch-all `handle` above proxies every path to the server, which |
| 209 | > relies on the permission policy as the gate. For a locked-down public |
| 210 | > staging box that instead exposes only named routes, use the per-route |
| 211 | > allowlist in [single-vm deployment](/docs/single-vm-deployment#https-proxy). |
| 212 | |
| 213 | ## 4. Enable app installs and install your first app |
| 214 | |
| 215 | Apps are packages that ship in the repo under `packages/`. Turn on |
| 216 | installs, then ask the server to install one. (Installs are gated by the |
| 217 | admin token, so this stays an operator action.) |
| 218 | |
| 219 | ```bash |
| 220 | sudo sed -i 's/^DBBASIC_ENABLE_PACKAGE_INSTALLS=false/DBBASIC_ENABLE_PACKAGE_INSTALLS=true/' \ |
| 221 | /etc/dbbasic-object-server.env |
| 222 | sudo systemctl restart dbbasic-object-server |
| 223 | |
| 224 | TOKEN=$(sudo grep -oP 'DBBASIC_ADMIN_TOKEN=\K.*' /etc/dbbasic-object-server.env) |
| 225 | |
| 226 | # Projects is the hub other apps relate to; install it first, then notes. |
| 227 | for app in app-projects app-notes; do |
| 228 | curl -s -X POST http://127.0.0.1:8001/packages/$app/install \ |
| 229 | -H ""Authorization: Token $TOKEN"" -H 'Content-Type: application/json' -d '{}' |
| 230 | echo |
| 231 | done |
| 232 | ``` |
| 233 | |
| 234 | `app-notes` includes a page object. To turn permission enforcement on so |
| 235 | each user sees only their own notes, follow the audit-then-enforce |
| 236 | rollout in [permissions](/docs/permissions-model#route-enforcement); on a |
| 237 | single-operator box you can leave it open to start. |
| 238 | |
| 239 | Visit `https://your-domain.com/notes`, sign in, and you have a working |
| 240 | notes app — quick capture, projects, search, public sharing — that you |
| 241 | never wrote a line of server code for. Browse |
| 242 | [the app suite](/docs/app-packages) for the rest (tasks, contacts, |
| 243 | articles, calendar, files, the shell) and install the ones you want. |
| 244 | |
| 245 | ## 5. Optional: the talk-to-everything shell |
| 246 | |
| 247 | Install `app-shell`, then store an AI provider key and chat with your |
| 248 | data — see [the shell and AI guide](/docs/shell-and-ai). Storing a key is |
| 249 | one command in the shell (`/key anthropic sk-...`), and the AI operates |
| 250 | the server with your permissions. |
| 251 | |
| 252 | ## What to do next |
| 253 | |
| 254 | - **Back it up.** All state is files under |
| 255 | `/var/lib/dbbasic-object-server/data`; see [backup and restore](/docs/backup-restore). |
| 256 | - **Harden it.** systemd sandboxing, journald caps, and the readiness |
| 257 | gates are in [single-vm deployment](/docs/single-vm-deployment). |
| 258 | - **Understand the model.** [Why DBBASIC](/docs/why) and |
| 259 | [comparisons](/docs/comparisons) explain what you are and are not |
| 260 | signing up for. |
| 261 | - **Build.** Copy `app-notes` to make your own app |
| 262 | ([package authoring](/docs/package-authoring)), or add a system-tool |
| 263 | object ([capability objects](/docs/capability-objects)). |
| 264 | |
| 265 | ## Upgrading later |
| 266 | |
| 267 | ```bash |
| 268 | cd /opt/dbbasic-object-server |
| 269 | sudo -u dbbasic git pull --ff-only |
| 270 | sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]' |
| 271 | sudo systemctl restart dbbasic-object-server dbbasic-object-daemon |
| 272 | ``` |
| 273 | |
| 274 | Changes to live objects and schemas need no deploy at all — that is the |
| 275 | point. Only server-code upgrades need the pull-and-restart above. |
| 276 | " |
| 277 | architecture Architecture — The Layers, and Where Each Doc Fits Start Here 120 A map of the DBBASIC Object Server stack, from storage through access surfaces, with pointers to the focused doc for each layer. "DBBASIC is a small stack. Everything is a record or an object in a |
| 278 | human-readable store; each layer above adds capability without hiding the one |
| 279 | below. This page is the map — read it first, then branch into the focused doc |
| 280 | for whichever layer you care about. |
| 281 | |
| 282 | ```mermaid |
| 283 | flowchart TB |
| 284 | A[""Access surfaces — Web · HTTP API · Shell / AI / MCP · Files""] |
| 285 | P[""Permission engine — one policy enforced on every surface""] |
| 286 | G[""Generative UI — list / table / board / tree / calendar · forms · detail · filters · search""] |
| 287 | C[""Capabilities — comments · attachments · sharing""] |
| 288 | D[""Data — schemas (types · validation · relations · transitions) + collections""] |
| 289 | R[""Runtime — ASGI object execution · realtime change log · daemon (triggers · schedules)""] |
| 290 | S[""Storage — human-readable TSV + object source / state / logs / files / versions""] |
| 291 | |
| 292 | A --> P --> G |
| 293 | G --> C |
| 294 | G --> D |
| 295 | C --> D |
| 296 | D --> R --> S |
| 297 | R -. live updates .-> G |
| 298 | ``` |
| 299 | |
| 300 | Every app is a **package** installed onto this stack — a schema, permission |
| 301 | rules, and at most one page object, with no app-specific server code. The same |
| 302 | stack serves the web page, the API, search, files, and the AI. |
| 303 | |
| 304 | ## The layers, bottom to top |
| 305 | |
| 306 | **Storage.** Collections are plain TSV you can `grep`, in one of two modes |
| 307 | (classic overwrite, or append-only with tombstones + compaction). Each object |
| 308 | keeps its source, state, logs, files, and version trail next to it. |
| 309 | → [`storage-modes.md`](/docs/storage-modes), |
| 310 | [`append-only-storage-design.md`](/docs/append-only-storage), |
| 311 | [`durability-and-recovery.md`](/docs/durability-and-recovery), |
| 312 | [`backup-restore.md`](/docs/backup-restore) |
| 313 | |
| 314 | **Runtime.** A long-running ASGI server executes objects in-process, pooled, or |
| 315 | in a subprocess. A daemon runs scheduled passes, compaction, and |
| 316 | trigger→target automation. A websocket change log lets any surface re-render |
| 317 | live. |
| 318 | → `runtime-contract.md`, |
| 319 | [`realtime.md`](/docs/realtime), |
| 320 | [`asgi-realtime-direction.md`](/docs/asgi-realtime-direction), |
| 321 | [`object-authoring.md`](/docs/object-authoring), |
| 322 | [`capability-objects.md`](/docs/capability-objects) |
| 323 | |
| 324 | **Data & schema.** A collection's schema declares its fields — types, enums, |
| 325 | relations (validated pointers), bounds, defaults, and status transitions — and |
| 326 | those are enforced on every write, not just in the form. |
| 327 | → [`schema-forms.md`](/docs/schema-forms), |
| 328 | [`validation-and-logic.md`](/docs/validation-and-logic), |
| 329 | [`business-logic-patterns.md`](/docs/business-logic-patterns), |
| 330 | [`logic-decisions.md`](/docs/logic-decisions) |
| 331 | |
| 332 | **Permissions.** One engine decides access for every surface: access modes, |
| 333 | role/object/action rules, ownership, row and field filters, temporary paid |
| 334 | access, and record sharing. Routing maps URLs; the policy decides what a |
| 335 | caller may see or write. |
| 336 | → [`permissions-model.md`](/docs/permissions-model), |
| 337 | [`site-routing.md`](/docs/site-routing), |
| 338 | [`secrets-and-credentials.md`](/docs/secrets-and-credentials) |
| 339 | |
| 340 | **Generative UI.** One renderer turns a schema into a live |
| 341 | list/table/board/tree/calendar, a form, and a composed detail page — with |
| 342 | filters, sort, search, relation labels, and realtime updates — no per-app UI |
| 343 | code. The design system is a semantic contract, not prescribed widgets. |
| 344 | → [`generative-ui.md`](/docs/generative-ui), |
| 345 | [`design-system.md`](/docs/design-system), |
| 346 | [`ui-decisions.md`](/docs/ui-decisions) |
| 347 | |
| 348 | **Capabilities.** Generic per-collection *behaviors* on top of the display |
| 349 | layer: a schema flag grows a comment thread, attachment list, or owner-checked |
| 350 | sharing, with no per-app table. |
| 351 | → [`capabilities.md`](/docs/capabilities) |
| 352 | |
| 353 | **Access surfaces.** The same records reach a web page, the HTTP API, |
| 354 | cross-collection search, file up/download, MCP agents, and a talk-to-everything |
| 355 | shell — all behind the one permission engine. |
| 356 | → [`http-api-contract.md`](/docs/http-api-contract), |
| 357 | [`rest-and-object-messages.md`](/docs/rest-and-object-messages), |
| 358 | [`shell-and-ai.md`](/docs/shell-and-ai) |
| 359 | |
| 360 | **Packages.** Apps are installable packages with a data-preserving upgrade |
| 361 | system (provenance baselines, three-way reconcile, override objects, feature |
| 362 | flags). |
| 363 | → [`app-packages.md`](/docs/app-packages), |
| 364 | [`package-authoring.md`](/docs/package-authoring), |
| 365 | [`upgrade-and-customization.md`](/docs/upgrade-and-customization) |
| 366 | |
| 367 | ## Operating it |
| 368 | |
| 369 | → [`quickstart.md`](/docs/quickstart) (fresh VM to first app), |
| 370 | [`single-vm-deployment.md`](/docs/single-vm-deployment), |
| 371 | [`docker-deployment.md`](/docs/docker-deployment), |
| 372 | [`traffic-limits.md`](/docs/traffic-limits), |
| 373 | `status.md` |
| 374 | |
| 375 | ## Why it's shaped this way |
| 376 | |
| 377 | → [`why-dbbasic.md`](/docs/why) (the advantages, honestly stated), |
| 378 | [`comparisons.md`](/docs/comparisons) (what DBBASIC deletes vs Django/Rails/ |
| 379 | no-code, and the cost of each deletion) |
| 380 | " |
| 381 | zero-to-code From Zero Code to Some Code Start Here 130 The staged path every app on the DBBASIC Object Server follows, from a schema with no code at all through hooks, event handlers, verbs, scheduled runners, and hand-written pages. "The question every generative system eventually gets asked: *fine, the |
| 382 | metadata builds the app — but when I need real code, where does it go?* |
| 383 | This page is the known path. Every app on this server grows through the |
| 384 | same stages, in the same order, and the order is the point: **code enters |
| 385 | through the write path first and the page last** — the exact reverse of |
| 386 | the classic web framework, where code entered through the controller |
| 387 | first and that is where the logic rotted. |
| 388 | |
| 389 | ## Stage 0 — an app with no code at all |
| 390 | |
| 391 | A schema (`schemas/notes.json`), permission rules, and two seeded view |
| 392 | records (an index at `/notes`, a detail at `/notes/{id}`). From those |
| 393 | alone: list, search, sort, create/edit forms, a detail page, realtime |
| 394 | updates, the JSON API, MCP tools for agents, and global search. All of it |
| 395 | reads the schema; none of it is emitted as code |
| 396 | ([`generative-ui.md`](/docs/generative-ui), including why this is *not* |
| 397 | scaffolding). |
| 398 | |
| 399 | `app-notes` ships this way today: a package registering zero objects. |
| 400 | |
| 401 | ## Stage 1 — logic as declarations (still no code) |
| 402 | |
| 403 | Most business rules are not code and never should be: |
| 404 | |
| 405 | - shape, bounds, required, enums, FK-exists → **schema validation** |
| 406 | - who may do what, whose rows are whose → **permission rules** |
| 407 | - legal state moves and who may make them → **`transitions` + `when`** |
| 408 | - same-record derivations → **`formula` fields** |
| 409 | - sums over children → **`rollup` fields** |
| 410 | - ""how many of these are waiting for somebody"" on the home page → an |
| 411 | **`attention` declaration** (`collection` + `where`, counted per viewer |
| 412 | through the permission rules; [`package-authoring.md`](/docs/package-authoring#declared-counts-collection--where)) |
| 413 | |
| 414 | Every surface enforces these because they live on the shared write path, |
| 415 | not in a page. A large fraction of real apps end here. |
| 416 | |
| 417 | ## Stage 2 — the first line of Python is a gate |
| 418 | |
| 419 | The first rule that *cannot* be declared is almost always a cross-record |
| 420 | check: ""a payment may not exceed the invoice balance"", ""a journal must |
| 421 | balance before posting"", ""a loss move cannot have a destination"". That is |
| 422 | a **pre-write hook** — one file, one function: |
| 423 | |
| 424 | ```python |
| 425 | # objects/hook/payments.py schema: ""hooks"": {""before_write"": ""hook_payments""} |
| 426 | def BEFORE_WRITE(request): |
| 427 | if too_much(request[""record""]): |
| 428 | return {""error"": ""..."", ""status"": 409} # reject |
| 429 | record = dict(request[""record""]); record[""rate""] = looked_up # or stamp |
| 430 | return {""record"": record} |
| 431 | ``` |
| 432 | |
| 433 | Hooks run on the shared write path, so the form, the API, and an AI agent |
| 434 | all hit the same gate. They fail closed. This is where code enters the |
| 435 | system, and it enters *enforcing*, not rendering. |
| 436 | |
| 437 | ## Stage 3 — reactions |
| 438 | |
| 439 | Something should *happen* after a write: a status flips, a journal is |
| 440 | composed, someone is notified. Notifications are data (`notify_rules`); |
| 441 | follow-on writes are an **event handler** — a `system/` object with |
| 442 | `HANDLES = [""payments.record.created""]` and an `EVENT(request)` function. |
| 443 | Reactions are post-commit and best-effort: they may never block the write |
| 444 | that already happened ([`logic-decisions.md`](/docs/logic-decisions) #6), and |
| 445 | anything they generate is idempotent by provenance (#7). |
| 446 | |
| 447 | ## Stage 4 — verbs |
| 448 | |
| 449 | Users (and agents) do things that are not CRUD: *reverse this journal*, |
| 450 | *apply this count*, *import this statement*, *resolve this bank line*. |
| 451 | Each is an **action object** — `objects/action/<verb>.py` with a `POST` |
| 452 | that checks identity, validates, and writes through the same records |
| 453 | layer. A verb is the honest home for anything a button should do that a |
| 454 | form cannot. |
| 455 | |
| 456 | ## Stage 5 — time |
| 457 | |
| 458 | Aging, dunning, recurring entries, escalation: time-driven state belongs |
| 459 | to the **daemon** (#2), as a runner object registered on the scheduler |
| 460 | (the `/scheduler` board shows every run's outcome) or a message on the |
| 461 | queue (delay, retry, backoff — already built). A runner is just an object |
| 462 | with a `POST`; it is callable by hand for testing and by the clock in |
| 463 | production. |
| 464 | |
| 465 | ## Stage 6 — presentation code, last of all |
| 466 | |
| 467 | Only when a page must *show* something no generic block can express: |
| 468 | |
| 469 | - first an **`object` block** — one hand-written panel inside an otherwise |
| 470 | generated page (`{""kind"": ""object"", ""object_id"": ""site_my_panel""}`); |
| 471 | - then, rarely, a **full page object** — `site/notes.py` overrides the |
| 472 | generated `/notes` by convention the moment the file exists, and |
| 473 | deleting it reverts. Reports are the legitimate case: the trial balance, |
| 474 | the statements, the reconciliation tie-out are folds across collections |
| 475 | with audit-grade warnings, and they stay hand-written on purpose. |
| 476 | |
| 477 | The rule that keeps stage 6 safe: **a page may never be the only place a |
| 478 | rule exists.** A gate written into a page does not gate the API or an |
| 479 | agent — it provably does not hold — so enforcement stays in stages 1–2 |
| 480 | where every surface shares it. Pages show; they never decide. |
| 481 | |
| 482 | ## The whole path at a glance |
| 483 | |
| 484 | | stage | you add | it lives in | enforced for | |
| 485 | |---|---|---|---| |
| 486 | | 0 | schema + rules + 2 view rows | data | every surface | |
| 487 | | 1 | declarations (transitions, formulas, rollups) | schema | every surface | |
| 488 | | 2 | a gate | `hook/` on the write path | every surface | |
| 489 | | 3 | a reaction | `system/` handler, `notify_rules` | post-commit | |
| 490 | | 4 | a verb | `action/` | its callers | |
| 491 | | 5 | a schedule | runner + scheduler/queue | the clock | |
| 492 | | 6 | a panel, then a page | `object` block → `site/` | presentation only | |
| 493 | |
| 494 | ## Where this page came from |
| 495 | |
| 496 | This path was not designed and then implemented — it was **extracted**. A |
| 497 | week of building real modules concretely (payments, the books spine, bank |
| 498 | reconciliation, inventory losses, cash counts) kept producing the same |
| 499 | placement decisions, and once every kind of business rule had exactly one |
| 500 | home, the homes sorted themselves into the order an app acquires them. |
| 501 | The taxonomy is the load-bearing thing; the path is its corollary. |
| 502 | |
| 503 | That is also why earlier frameworks never had a page like this. They |
| 504 | documented their *mechanisms* (models, controllers, middleware, signals) |
| 505 | but never fixed where *logic* lives — any rule could go anywhere, so there |
| 506 | was no gradient from zero code to some code, only a cliff. ""Fat models, |
| 507 | skinny controllers"" was a slogan, not a placement table with enforcement |
| 508 | behind it. A path only exists where placement is decided. |
| 509 | |
| 510 | The runtime twin of this page is [`write-pipeline.md`](/docs/write-pipeline): |
| 511 | once logic is placed, that page says exactly when it runs, in what order, |
| 512 | and what can stop a write. |
| 513 | |
| 514 | Placement questions beyond this page: the flowchart in |
| 515 | [`business-logic-patterns.md`](/docs/business-logic-patterns) decides where |
| 516 | any individual rule goes, and [`logic-decisions.md`](/docs/logic-decisions) |
| 517 | records why. |
| 518 | " |
| 519 | object-authoring Object Authoring Building on DBBASIC 200 How to write DBBASIC objects: source layout, HTTP-style methods, request identity, runtime helpers, response shapes, and public deployment safety. "This document describes the object shape supported by the current public server |
| 520 | slice. It is intentionally small and should stay compatible with the working |
| 521 | private runtime while the hardened runtime moves into this repository. |
| 522 | |
| 523 | ## Source Location |
| 524 | |
| 525 | Object source lives under `objects/` by default: |
| 526 | |
| 527 | ```text |
| 528 | objects/site/home.py |
| 529 | objects/basics/counter.py |
| 530 | objects/users/42/deals.py |
| 531 | ``` |
| 532 | |
| 533 | The source root can be changed for deployments: |
| 534 | |
| 535 | ```text |
| 536 | DBBASIC_OBJECTS_DIR=/var/lib/dbbasic-object-server/objects |
| 537 | ``` |
| 538 | |
| 539 | Object IDs are derived from paths: |
| 540 | |
| 541 | - `objects/site/home.py` becomes `site_home` |
| 542 | - `objects/basics/counter.py` becomes `basics_counter` |
| 543 | - `objects/users/42/deals.py` becomes `u_42_deals` |
| 544 | |
| 545 | ## Methods |
| 546 | |
| 547 | An object is a Python file that can define HTTP-style methods: |
| 548 | |
| 549 | ```python |
| 550 | def GET(request): |
| 551 | return {""status"": ""ok""} |
| 552 | |
| 553 | def POST(request): |
| 554 | return {""status"": ""created"", ""payload"": request} |
| 555 | ``` |
| 556 | |
| 557 | `GET` receives query parameters. `POST`, `PUT`, and `DELETE` receive the parsed |
| 558 | request body plus query parameters where the HTTP contract allows it. |
| 559 | |
| 560 | ## Request Identity |
| 561 | |
| 562 | Every request payload includes a server-controlled `_identity` key describing |
| 563 | the resolved caller, so objects can render per-user pages and make per-user |
| 564 | decisions without hand-rolling auth: |
| 565 | |
| 566 | ```python |
| 567 | def GET(request): |
| 568 | identity = request[""_identity""] |
| 569 | if identity[""user_id""] is None: |
| 570 | return {""status"": 401, ""error"": ""Sign in first""} |
| 571 | return {""hello"": identity[""user_id""], ""roles"": identity[""roles""]} |
| 572 | ``` |
| 573 | |
| 574 | `_identity` contains `user_id`, `account_id`, `roles`, `subscriptions`, and |
| 575 | `auth_method` (`admin_token`, `session_token`, `session_cookie`, |
| 576 | `trusted_headers`, or `anonymous`). The server overwrites any client-supplied |
| 577 | `_identity` value before the object runs, so it cannot be spoofed through the |
| 578 | request body or query string. Anonymous requests still receive the key with |
| 579 | `user_id` set to `None`. |
| 580 | |
| 581 | ## Runtime Helpers |
| 582 | |
| 583 | Loaded object modules receive a small set of runtime helpers. The current public |
| 584 | runtime injects: |
| 585 | |
| 586 | ```python |
| 587 | _state_manager.get(key, default=None) |
| 588 | _state_manager.set(key, value) |
| 589 | _state_manager.increment(key, delta=1) # -> new value; missing key starts at 0 |
| 590 | _state_manager.get_all() |
| 591 | _state_manager.reload() |
| 592 | |
| 593 | _logger.debug(message, **fields) |
| 594 | _logger.info(message, **fields) |
| 595 | _logger.warning(message, **fields) |
| 596 | _logger.error(message, **fields) |
| 597 | ``` |
| 598 | |
| 599 | State is stored under `data/state/{object_id}/state.tsv`. Writers |
| 600 | (`set`, `delete`, `increment`, ...) hold a per-file lock (thread lock plus an |
| 601 | `flock` on `state.tsv.lock`), so `increment` is exact across threads, warm |
| 602 | pool workers and spawned processes. A non-numeric existing value raises |
| 603 | `TypeError` and is left unchanged. Logs are stored under |
| 604 | `data/logs/{object_id}/log.tsv`. The active log is plain TSV. Rotated logs are |
| 605 | gzip-compressed by default and can still be read by the server. |
| 606 | |
| 607 | User-namespace objects (`u_<uid>_*`) get these same helpers as proxies |
| 608 | across a sandbox boundary, with a few deliberate differences (`files_dir`, |
| 609 | `update(after_set=...)`, and loaded *system* objects expose only `execute`); |
| 610 | see runtime-contract.md ""User Object Isolation"". |
| 611 | |
| 612 | ### `_files`: per-object file storage |
| 613 | |
| 614 | ```python |
| 615 | _files.put(filename, content: bytes) -> None # create or replace |
| 616 | _files.get(filename) -> bytes # FileNotFoundError if missing |
| 617 | _files.delete(filename) -> None # a missing file is not an error |
| 618 | _files.list() -> [{""name"": str, ""size"": int, ""modified"": float}, ...] |
| 619 | _files.exists(filename) -> bool |
| 620 | _files.files_dir # pathlib.Path of the directory |
| 621 | ``` |
| 622 | |
| 623 | Files live in `<DBBASIC_DATA_DIR>/files/<object_id>/` and are the same files |
| 624 | the HTTP object-file API serves (`object_files.py` does all path handling). |
| 625 | Each object's `_files` is bound to its own object id and cannot name another's. |
| 626 | Names may contain `/` subdirectories; `..`, absolute paths, NUL, empty names |
| 627 | and symlinks that leave the directory raise `ValueError`. `put` accepts bytes |
| 628 | only (`TypeError` otherwise) and refuses content larger than |
| 629 | `DBBASIC_MAX_OBJECT_FILE_BYTES` (default 1 MiB, the same limit as the HTTP |
| 630 | file API) with `ValueError`. `list()` includes files in subdirectories (names |
| 631 | are relative, `a/b.txt`); the old server listed only the top level. |
| 632 | |
| 633 | ### `_runtime`: calling another object |
| 634 | |
| 635 | ```python |
| 636 | other = _runtime.load_object(""tools_ocr"") # an object id, not a path |
| 637 | result = other.execute(""POST"", {""image"": ""...""}) # whatever the method returns |
| 638 | other.state_manager, other.file_manager, other.logger, other.object_id |
| 639 | ``` |
| 640 | |
| 641 | Ids resolve exactly as for HTTP requests (`object_namespace.resolve_object_id`). |
| 642 | Paths such as `examples/x.py` are not accepted. Errors, all subclasses of |
| 643 | `object_runtime_helpers.CompositionError`: `CompositionNotFoundError` |
| 644 | (`LookupError`), `CompositionDeniedError` (`PermissionError`) and |
| 645 | `CompositionDepthError`. |
| 646 | |
| 647 | Namespace rule (fail closed): an object in a user namespace (`u_<uid>_...`) |
| 648 | may load only objects in its own namespace (`u_<same uid>_...`) and non-user |
| 649 | (system or package) objects. It can never load `u_<other>_*`; the refusal is |
| 650 | the same whether or not the target exists. Non-user objects may load any |
| 651 | object. The loaded object runs inside the caller's process with the caller's |
| 652 | isolation (pool worker, spawned child, or in-process) and its own `_files` and |
| 653 | `_state_manager`. A locked check may not load objects at all. |
| 654 | |
| 655 | Call depth is limited to `object_runtime_helpers.MAX_COMPOSITION_DEPTH` (8) |
| 656 | nested executions per call chain, counting the outermost request; an object |
| 657 | that calls itself, or A -> B -> A, fails with `CompositionDepthError`. This is |
| 658 | not a sandbox: an object can still import modules and touch the filesystem. |
| 659 | |
| 660 | ### `_schedule` / `_unschedule`: running a method on a timer |
| 661 | |
| 662 | ```python |
| 663 | _schedule(1800, ""refresh"") # run refresh() every 30 minutes; returns the task row |
| 664 | _unschedule(""refresh"") # stop that one; returns how many tasks went |
| 665 | _unschedule() # stop every method this object scheduled |
| 666 | ``` |
| 667 | |
| 668 | The earlier object server's signatures, so ported objects (weather and RSS caches, the scan |
| 669 | processor, `basics/ticker.py`) run unchanged, including their |
| 670 | `if _scheduler_registered or not _schedule:` guards. Each call writes one |
| 671 | `interval` task on the daemon's scheduler board (`object_schedule.py`), keyed |
| 672 | by (object id, method): calling again is an update, and calling again with the |
| 673 | same interval changes nothing -- so calling it on every request is safe. The |
| 674 | daemon (`object_daemon.py`, which must be running: see the deployment docs) |
| 675 | calls the method by its exact name with **no arguments** (or the empty payload |
| 676 | if its signature requires one), through the normal execution path. It runs as |
| 677 | itself: no caller's identity is attached. |
| 678 | |
| 679 | Rules: the method must be a public function the object defines (a name not |
| 680 | starting with `_`; checked when you schedule); intervals are whole seconds, at |
| 681 | least `DBBASIC_SCHEDULE_MIN_INTERVAL_SECONDS` (default 5). User objects |
| 682 | (`u_<uid>_*`) may schedule only themselves, at least every |
| 683 | `DBBASIC_SCHEDULE_USER_MIN_INTERVAL_SECONDS` (default 60), and one user's |
| 684 | objects hold at most `DBBASIC_SCHEDULE_USER_MAX_TASKS` (default 10) |
| 685 | schedules. Refusals raise `ValueError`. If the object or the method later |
| 686 | disappears, the daemon skips the task and logs it once; destroying the object |
| 687 | (`DELETE ?destroy=true`) removes its tasks. Unlike the old server, schedules |
| 688 | survive restarts, appear in `GET /daemon/scheduler/tasks`, and an interval |
| 689 | counts from the last run, so a stopped daemon does not owe a backlog. |
| 690 | |
| 691 | ## Default Storage And Integrations |
| 692 | |
| 693 | The default DBBASIC object should not need a separate database. Source, state, |
| 694 | logs, files, and versions are file-backed so a useful app can start on one VM |
| 695 | with normal Unix paths and backups. |
| 696 | |
| 697 | Objects can still connect to SQL databases, SQLite files, HTTP APIs, AI APIs, or |
| 698 | other services when a workload needs them. Those integrations should be explicit |
| 699 | object behavior or package behavior, not hidden platform requirements. |
| 700 | |
| 701 | This keeps the base stack small while leaving room for: |
| 702 | |
| 703 | - SQL/reporting objects |
| 704 | - schema and relationship inspectors |
| 705 | - API connector objects |
| 706 | - migration objects |
| 707 | - AI-assisted query and data tools |
| 708 | |
| 709 | DBBASIC Scroll can expose SQL, schema, and diagram screens, but those should be |
| 710 | capabilities of the object system rather than proof that every app needs a |
| 711 | database tier by default. |
| 712 | |
| 713 | Schema still matters. The difference is that DBBASIC should let schemas, |
| 714 | validation rules, relationships, and generated admin screens live close to the |
| 715 | objects and packages that use them. That avoids forcing every small app through |
| 716 | an external database, migration, ORM, admin, and deployment loop before the app |
| 717 | has proved it needs that weight. |
| 718 | |
| 719 | ```mermaid |
| 720 | flowchart LR |
| 721 | subgraph DB[""Database-first loop""] |
| 722 | D1[""Design schema""] --> D2[""Run migration""] |
| 723 | D2 --> D3[""Update model/ORM""] |
| 724 | D3 --> D4[""Update route/view/controller""] |
| 725 | D4 --> D5[""Deploy""] |
| 726 | D5 --> D6[""Inspect errors""] |
| 727 | D6 --> D1 |
| 728 | end |
| 729 | |
| 730 | subgraph OBJ[""DBBASIC object loop""] |
| 731 | O1[""Edit object or package metadata""] --> O2[""Run it""] |
| 732 | O2 --> O3[""Read output, logs, state, errors""] |
| 733 | O3 --> O4[""Fix source or schema metadata""] |
| 734 | O4 --> O5[""Keep versions""] |
| 735 | O5 --> O1 |
| 736 | end |
| 737 | |
| 738 | O3 -.-> I[""Optional integrations: SQL, SQLite, HTTP APIs, AI APIs""] |
| 739 | ``` |
| 740 | |
| 741 | ## JSON Object |
| 742 | |
| 743 | ```python |
| 744 | def GET(request): |
| 745 | count = int(_state_manager.get(""count"", 0)) + 1 |
| 746 | _state_manager.set(""count"", count) |
| 747 | _logger.info(""counter served"", count=count) |
| 748 | return { |
| 749 | ""status"": ""ok"", |
| 750 | ""count"": count, |
| 751 | } |
| 752 | ``` |
| 753 | |
| 754 | Normal dictionaries return JSON. |
| 755 | |
| 756 | ## HTML Object |
| 757 | |
| 758 | ```python |
| 759 | def GET(request): |
| 760 | count = int(_state_manager.get(""count"", 0)) + 1 |
| 761 | _state_manager.set(""count"", count) |
| 762 | _logger.info(""home served"", count=count, response_type=""html"") |
| 763 | |
| 764 | html = f""""""<!doctype html> |
| 765 | <html lang=""en""> |
| 766 | <head> |
| 767 | <meta charset=""utf-8""> |
| 768 | <meta name=""viewport"" content=""width=device-width, initial-scale=1""> |
| 769 | <title>DBBASIC Object</title> |
| 770 | </head> |
| 771 | <body> |
| 772 | <h1>DBBASIC Object</h1> |
| 773 | <p>This object has been served {count} times.</p> |
| 774 | </body> |
| 775 | </html> |
| 776 | """""" |
| 777 | |
| 778 | return { |
| 779 | ""content_type"": ""text/html; charset=utf-8"", |
| 780 | ""body"": html, |
| 781 | } |
| 782 | ``` |
| 783 | |
| 784 | Dicts with `content_type` and `body` become raw HTTP responses. This is the |
| 785 | shape used for pages, generated views, images, and other non-JSON object |
| 786 | responses. |
| 787 | |
| 788 | Plain strings also return `text/html; charset=utf-8`. Plain bytes return |
| 789 | `application/octet-stream`. |
| 790 | |
| 791 | ## HTML Form Object |
| 792 | |
| 793 | Forms are how design changes ship without a deploy: the page, the handler, and |
| 794 | the state live in one object. `GET` renders the form; `POST` receives the |
| 795 | submitted fields (form posts from a signed-in browser carry the session cookie, |
| 796 | so `request[""_identity""]` identifies the user in both methods): |
| 797 | |
| 798 | ```python |
| 799 | def GET(request): |
| 800 | identity = request[""_identity""] |
| 801 | if identity[""user_id""] is None: |
| 802 | return (303, [(""Location"", ""/login?next=/objects/notes_quick"")], b"""") |
| 803 | |
| 804 | saved = _state_manager.get(f""note:{identity['user_id']}"", """") |
| 805 | html = f""""""<!doctype html> |
| 806 | <html lang=""en""> |
| 807 | <body> |
| 808 | <h1>Quick note for {identity['user_id']}</h1> |
| 809 | <form method=""post""> |
| 810 | <textarea name=""note"">{saved}</textarea> |
| 811 | <button type=""submit"">Save</button> |
| 812 | </form> |
| 813 | </body> |
| 814 | </html>"""""" |
| 815 | return {""content_type"": ""text/html; charset=utf-8"", ""body"": html} |
| 816 | |
| 817 | |
| 818 | def POST(request): |
| 819 | identity = request[""_identity""] |
| 820 | if identity[""user_id""] is None: |
| 821 | return {""status"": 401, ""error"": ""Sign in first""} |
| 822 | |
| 823 | _state_manager.set(f""note:{identity['user_id']}"", str(request.get(""note"", """"))) |
| 824 | _logger.info(""note saved"", user_id=identity[""user_id""]) |
| 825 | return (303, [(""Location"", ""/objects/notes_quick"")], b"""") |
| 826 | ``` |
| 827 | |
| 828 | Cookie-authenticated form posts are origin-checked by the server (same-site |
| 829 | only), so objects do not need their own CSRF plumbing for basic forms. Records |
| 830 | and schemas are the step up from object state when the data needs listing, |
| 831 | validation, and change history — see the collections sections of |
| 832 | [`http-api-contract.md`](/docs/http-api-contract). |
| 833 | |
| 834 | ## Upload Forms |
| 835 | |
| 836 | `multipart/form-data` posts (forms with `enctype=""multipart/form-data""`) are |
| 837 | parsed for you: text fields arrive as plain payload keys, and each uploaded |
| 838 | file arrives under `request[""_files""]` with its content base64-encoded so the |
| 839 | payload survives the subprocess execution boundary: |
| 840 | |
| 841 | ```python |
| 842 | import base64 |
| 843 | |
| 844 | def POST(request): |
| 845 | upload = request[""_files""][""document""] |
| 846 | content = base64.b64decode(upload[""content_base64""]) |
| 847 | _logger.info(""upload received"", filename=upload[""filename""], size=upload[""size""]) |
| 848 | return {""saved"": upload[""filename""], ""bytes"": len(content)} |
| 849 | ``` |
| 850 | |
| 851 | Each `_files` entry has `filename`, `content_type`, `size`, and |
| 852 | `content_base64`. Upload size is bounded by `DBBASIC_MAX_REQUEST_BYTES`. |
| 853 | |
| 854 | An object that receives an upload can process it with system tools — |
| 855 | OCR, transcode, thumbnail, extract — by shelling out to binaries like |
| 856 | `tesseract` or `ffmpeg`. See [capability objects](/docs/capability-objects) |
| 857 | for the subprocess model, worked examples, and the trust boundary. |
| 858 | Store durable uploads through the object file APIs so they inherit |
| 859 | permissions and change history. |
| 860 | |
| 861 | ## Low-Level Response |
| 862 | |
| 863 | When an object needs exact status and headers, return a tuple: |
| 864 | |
| 865 | ```python |
| 866 | def POST(request): |
| 867 | return (201, [(""Content-Type"", ""text/plain"")], [b""created""]) |
| 868 | ``` |
| 869 | |
| 870 | The tuple shape is: |
| 871 | |
| 872 | ```text |
| 873 | (status, headers, body) |
| 874 | ``` |
| 875 | |
| 876 | `body` may be bytes, text, or a list of bytes/text parts. |
| 877 | |
| 878 | ## Authoring Rule |
| 879 | |
| 880 | Keep each object small enough to inspect, run, log, fix, and version quickly. |
| 881 | The point of DBBASIC is the short loop: |
| 882 | |
| 883 | ```mermaid |
| 884 | flowchart LR |
| 885 | A[""edit object""] --> B[""run""] |
| 886 | B --> C[""read output, logs, state, errors""] |
| 887 | C --> D[""fix""] |
| 888 | D --> E[""keep version""] |
| 889 | E --> A |
| 890 | ``` |
| 891 | |
| 892 | Objects can call other objects, emit events, handle jobs, serve pages, or expose |
| 893 | APIs, but the first rule is the same: make the running object easy to inspect. |
| 894 | |
| 895 | ## Public Deployment Safety |
| 896 | |
| 897 | Until role, object, and row-level permissions are enforced, do not expose the |
| 898 | full `/objects` API on a public hostname. |
| 899 | |
| 900 | For public staging: |
| 901 | |
| 902 | - keep `DBBASIC_ENABLE_SOURCE_WRITES=false` |
| 903 | - generate a deployment-specific `DBBASIC_ADMIN_TOKEN` outside the source tree |
| 904 | - bind uvicorn to `127.0.0.1` |
| 905 | - allowlist explicit public object routes in a reverse proxy |
| 906 | - keep object source, state, logs, versions, and object listing private from |
| 907 | normal public users |
| 908 | " |
| 909 | package-authoring Package Authoring Building on DBBASIC 210 Practical guide to building and installing a DBBASIC package: manifest structure, install semantics, navigation and attention registries, and the authoring workflow. "This is the practical guide for building a DBBASIC package: one installable |
| 910 | directory that ships an app piece — objects, schemas, and seed data — without |
| 911 | a deploy pipeline. It is written for humans and AI tools that generate |
| 912 | packages. The runtime contract details live in `runtime-contract.md#packages`; |
| 913 | this page is the authoring workflow. |
| 914 | |
| 915 | ## Find Your Task |
| 916 | |
| 917 | | I want to... | Go to | |
| 918 | |---|---| |
| 919 | | upgrade a package without losing data, and test it | [Upgrading a package](#upgrading-a-package-data-backfill-and-an-upgrade-test) | |
| 920 | | know what a field permission does on a write | [permissions-model.md](/docs/permissions-model#field-permissions-on-writes-what-is-checked-and-the-known-limits) | |
| 921 | | start a new package that already works | [Start from a scaffold](#start-from-a-scaffold) (`scripts/new_package.py`) | |
| 922 | | check a change as different people, with permissions enforced | [Try Your Change](#try-your-change) (`scripts/try_package.py`) | |
| 923 | | see which rows and labels a page would list for someone | [Try Your Change](#try-your-change), `--rows` | |
| 924 | | let a role read every row while only owners write | [Recipes](#a-role-reads-every-row-while-only-owners-write) | |
| 925 | | let staff enter records owned by members, donors or patients | [permissions-model.md](/docs/permissions-model#who-owns-a-record-you-create) (`""on_behalf"": true`) | |
| 926 | | make a person's records show up in a subject access export | [Personal data](#personal-data-the-subject-export) (`""subject""`) | |
| 927 | | count ""my queue"" on the menu or home page | [Recipes](#a-count-over-rows-i-own-or-am-assigned), [Attention](#attention-attention) | |
| 928 | | freeze fields once a record is settled | [Recipes](#freeze-some-fields-once-a-record-is-settled) | |
| 929 | | add a field and show it in a list | [Recipes](#add-a-field-and-show-it-in-a-list-page) | |
| 930 | | make a value unique, required only in some state, or bounded | [Add a field](#add-a-field-and-show-it-in-a-list-page) links each rule | |
| 931 | | compare a datetime with now in a check (aware or naive, UTC, unparseable values) | [Comparing a datetime with now](#comparing-a-datetime-with-now) | |
| 932 | | refuse a write on the date, on another field, or on another collection | [What can't be declared](#what-cant-be-declared) | |
| 933 | | require a field when a row of another collection says so (a category, a type) | [A requirement another collection decides](#a-requirement-another-collection-decides) | |
| 934 | | see a whole app built that way (expenses, mileage, a register) | expense-substantiation.md | |
| 935 | | change a page or route I already shipped | [Changing a seeded row in a new version](#changing-a-seeded-row-in-a-new-version) | |
| 936 | | decide what to bump in `version` | [Which version to bump](#which-version-to-bump) | |
| 937 | | know why an integer comes back as `""4""` | [What a record looks like on the wire](#what-a-record-looks-like-on-the-wire) | |
| 938 | | my test failed after I added a field, a dependency or a version | [A failing pin on a pure addition is a test bug](#what-a-schemas-version-does) | |
| 939 | | install, dry-run, restore | [What install does](#what-install-actually-does-today), [Authoring workflow](#authoring-workflow) | |
| 940 | |
| 941 | ## What A Package Is |
| 942 | |
| 943 | A package is a directory under `packages/` (or `DBBASIC_PACKAGES_DIR`) with a |
| 944 | manifest and package-relative content: |
| 945 | |
| 946 | ```text |
| 947 | packages/{package_id}/ |
| 948 | dbbasic-package.json |
| 949 | objects/ # object source files |
| 950 | schemas/ # collection schema JSON files |
| 951 | seed/ # initial records, TSV files (new ids are added on every install) |
| 952 | permissions/ # rule fragments: merged into the deployment policy on install |
| 953 | migrations/ # declared, not run: install refuses a package that lists any |
| 954 | ``` |
| 955 | |
| 956 | `permissions/` is installed: each file is `{""rules"": [...]}`, and install |
| 957 | validates the rules, tags them with this package's id and appends the ones the |
| 958 | policy does not already hold ([What install does](#what-install-actually-does-today) |
| 959 | has the detail, including how a rule is retired). `seed/` is merged by record |
| 960 | id, not written once ([same section](#what-install-actually-does-today)). |
| 961 | |
| 962 | A good package is one app primitive: contacts, notes, tasks, articles, |
| 963 | invoices. Small enough to review, complete enough to install and use. |
| 964 | |
| 965 | ## The Manifest |
| 966 | |
| 967 | `dbbasic-package.json` is plain JSON: |
| 968 | |
| 969 | ```json |
| 970 | { |
| 971 | ""dron"": ""0.2"", |
| 972 | ""id"": ""contacts"", |
| 973 | ""name"": ""Contacts"", |
| 974 | ""version"": ""0.1.0"", |
| 975 | ""description"": ""Contact records with a browse/edit page"", |
| 976 | ""compatibility"": {""dbbasic_object_server"": "">=0.1.0""}, |
| 977 | ""dependencies"": [], |
| 978 | ""objects"": [ |
| 979 | {""id"": ""contacts_directory"", ""path"": ""objects/contacts/directory.py""} |
| 980 | ], |
| 981 | ""schemas"": [ |
| 982 | {""collection"": ""contacts"", ""path"": ""schemas/contacts.json""} |
| 983 | ], |
| 984 | ""seed"": [ |
| 985 | {""collection"": ""contacts"", ""path"": ""seed/contacts.tsv""} |
| 986 | ], |
| 987 | ""permissions"": [], |
| 988 | ""migrations"": [], |
| 989 | ""schedules"": [ |
| 990 | {""id"": ""contacts_dedupe_nightly"", |
| 991 | ""object_id"": ""contacts_directory"", |
| 992 | ""schedule"": ""10 6 * * *"", |
| 993 | ""description"": ""Flag likely duplicate contacts overnight.""} |
| 994 | ], |
| 995 | ""nav"": [ |
| 996 | {""id"": ""contacts"", ""label"": ""Contacts"", ""path"": ""/contacts"", |
| 997 | ""blurb"": ""People, the organizations they belong to, and interactions"", |
| 998 | ""surface"": ""member"", ""group"": ""Work"", ""order"": 60} |
| 999 | ] |
| 1000 | } |
| 1001 | ``` |
| 1002 | |
| 1003 | Rules the server enforces: |
| 1004 | |
| 1005 | - `id` must be a safe package identifier; object ids and collection names are |
| 1006 | validated with the same rules as the rest of the server. |
| 1007 | - All paths are package-relative. Absolute paths, null bytes, and `..` |
| 1008 | traversal are rejected at parse time. |
| 1009 | - `dron` (optional) names the DRON version the package was written for, as |
| 1010 | `""MAJOR.MINOR""` text. A server installs it if it reads that version or a |
| 1011 | later minor of the same major; a later minor, another major, or a value |
| 1012 | that is not `""MAJOR.MINOR""` text refuses the install (and the dry run) |
| 1013 | before anything is written, naming the version asked for and the version |
| 1014 | the server reads: `Package app-tickets dbbasic-package.json: the package |
| 1015 | was written for DRON 0.3 and this server reads DRON 0.2, ...; upgrade the |
| 1016 | server ...`. Leave it out and the package installs as it always did. The |
| 1017 | scaffold writes the server's version. See dron.md. |
| 1018 | - **A key DRON does not define refuses the install.** A misspelt section |
| 1019 | (`schedule` for `schedules`), a `nav` entry's `lable`, a schema field's |
| 1020 | `requird` or a rule's `row_filtr` is refused when the package is loaded, |
| 1021 | before anything is written, and the message names the file, the entry or |
| 1022 | rule, the key and the closest spelling: `Package permission rule is |
| 1023 | invalid: permissions/rules.json rule 3: unknown key 'row_filtr' (did you |
| 1024 | mean 'row_filter'?)`. (Until this was tightened such a key was dropped and |
| 1025 | the install succeeded; a rule whose `row_filter` was misspelt covered every |
| 1026 | row.) The same goes for values the loader used to coerce or re-case |
| 1027 | (`""required"": ""no""`, a text `version`, `""nav_optional"": ""no""`, `""type"": |
| 1028 | ""Integer""`, `""effect"": ""Allow""`, `""surface"": ""Public""`), for an unknown |
| 1029 | field type, and, in permission rules and transition guards, for an unknown |
| 1030 | action, principal, operator or `$`-variable (`$userid`) and a boolean filter |
| 1031 | value (write `""true""`). The engine-only synonyms (`readonly`, `readOnly`, |
| 1032 | `computed: true`, `validation.regex`, `validation.required`, |
| 1033 | `validation.choices`, `validation.in`, `{""values"": [...]}`) are refused with |
| 1034 | the DRON spelling. So are values that used to install and then fail the |
| 1035 | first write or render that touched them, or do nothing: a `validation.min` |
| 1036 | or `max` that is not a number, a field `permissions` level other than `edit`, |
| 1037 | `read` or `hidden` (`write` and `readonly` are the engine's spellings, not |
| 1038 | DRON's), a `relation` with no collection, a `formula` or `rollup` on a field |
| 1039 | that is not `""type"": ""computed""`, a rollup with no `collection`, `fk_field` |
| 1040 | or `op`, an `op` other than `sum`, `count`, `min`, `max` or `avg`, or an op |
| 1041 | other than `count` with no `field`, a `hooks.before_write` that is not an |
| 1042 | object id, and a `views.list_mode` other than `table`, `board`, `tree`, |
| 1043 | `calendar`, `cards` or `feed`: `Package schema is invalid: |
| 1044 | schemas/orders.json: orders: views.list_mode 'grid' is not a list mode; write |
| 1045 | one of table, board, tree, calendar, cards or feed`. Schemas already stored on |
| 1046 | a box, ones saved through the schema API, and the deployment's own policy |
| 1047 | file are read as before: only a package declaration is held to DRON. |
| 1048 | The DRON JSON Schema, [below](#editor-help-the-dron-schemas), catches the |
| 1049 | same mistakes earlier, in your editor or through `tests/test_dron_schema.py`, |
| 1050 | which validates every shipped manifest, schema and rules file against it (it |
| 1051 | needs no `jsonschema` package; it carries its own small validator). A package |
| 1052 | of your own is checked the same way once it sits under `packages/`: |
| 1053 | `python -m pytest tests/test_dron_schema.py -k your-package-id`. The dry run |
| 1054 | (`GET /packages/{package_id}?dry_run=true`) lists a refused declaration in |
| 1055 | its `warnings`, with the same reason, before you install. |
| 1056 | |
| 1057 | ## What Install Actually Does Today |
| 1058 | |
| 1059 | Installs are deliberately conservative: |
| 1060 | |
| 1061 | - `objects` entries are written under the configured objects root. Existing |
| 1062 | objects require `allow_replace`. |
| 1063 | - `schemas` entries are validated and written under `data/schemas/`. Existing |
| 1064 | schemas require `allow_replace`; with it, an unedited schema is replaced |
| 1065 | (`updated`), and one an operator has customised is merged field by field |
| 1066 | (`merged`) or parked as a conflict to resolve. See |
| 1067 | [What a schema's `version` does](#what-a-schemas-version-does). |
| 1068 | - `seed` TSV is **merged by `id`**: a collection with no records takes the |
| 1069 | whole file; a collection that already holds records gets only the seed rows |
| 1070 | whose `id` it does not have (reported `status: ""merged""`, or `""skipped""` |
| 1071 | when nothing was new). A row that is already there is never overwritten |
| 1072 | with something an operator changed, so a reinstall never destroys live |
| 1073 | data and never blocks the install. A column the package itself changed in |
| 1074 | the new version, and nobody has edited since the install wrote it, is |
| 1075 | refreshed; an edited one is kept and reported (`replaced` / `kept` on the |
| 1076 | seed entry): see [Changing a seeded row in a new |
| 1077 | version](#changing-a-seeded-row-in-a-new-version). A row the collection refuses (a `unique` key live data already |
| 1078 | holds, a value its schema rejects) is listed under `rejected` in the result |
| 1079 | and the rest still merge. This is what makes an in-place upgrade safe: |
| 1080 | reinstall with `allow_replace` to ship new object code, a migrated schema, |
| 1081 | and re-merged permissions while every existing record is preserved. Live |
| 1082 | records live outside the package, in `data/collections/<name>/records.tsv` |
| 1083 | keyed by collection, so an upgrade has no reason to touch them. (Evolving a |
| 1084 | schema across an upgrade — backfilling a newly added field on old rows — is |
| 1085 | the separate `migrations` story below, not yet implemented; adding a |
| 1086 | field is safe because old rows simply read as empty for it, and a `default` |
| 1087 | applies to rows written from then on, not to old ones.) |
| 1088 | - `permissions` entries MERGE: each fragment file is |
| 1089 | `{""rules"": [ ... ]}` using the same rule shape as the policy document |
| 1090 | (`effect`, `principal`, `actions`, optional `collection`/`object_id`, |
| 1091 | row filters, field lists). On install the rules are validated, stamped |
| 1092 | with `""package"": ""<package_id>""` provenance, and appended to the |
| 1093 | deployment policy — skipping any rule that already exists, so reinstalls |
| 1094 | are idempotent. This is how a site package makes its own pages public: |
| 1095 | ship the grant with the code instead of hand-editing policy after install. |
| 1096 | Invalid fragments block the whole install. |
| 1097 | - **Deleting or changing a rule is a retirement, and an upgrade performs |
| 1098 | it.** Two rules are the same rule when everything but `reason` matches, |
| 1099 | so adding a row filter to a grant, or dropping an action from it, ships a |
| 1100 | NEW rule and withdraws the old one. Every install records the rules the |
| 1101 | package shipped (`permissions` in `data/package_baselines/<id>.json`); |
| 1102 | the next install removes from the policy any rule that is in that record, |
| 1103 | is no longer shipped, and is still tagged as this package's. Nothing to |
| 1104 | write: delete the rule from `rules` and it goes on upgrade. |
| 1105 | |
| 1106 | A box installed before 2026-11-28 has no such record, so for it (and for |
| 1107 | any rule you want gone whatever the box's history) list the withdrawn |
| 1108 | rule in the fragment's optional `retracted` array, in the same shape, |
| 1109 | with a `reason` that says why it was withdrawn: |
| 1110 | |
| 1111 | ```json |
| 1112 | { |
| 1113 | ""retracted"": [ |
| 1114 | {""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""], |
| 1115 | ""collection"": ""template_runs"", |
| 1116 | ""reason"": ""replaced by the owner-filtered read""} |
| 1117 | ], |
| 1118 | ""rules"": [ ... ] |
| 1119 | } |
| 1120 | ``` |
| 1121 | |
| 1122 | **When you delete or tighten a shipped rule, add the old rule to |
| 1123 | `retracted` in the same commit** and leave it there: it is how every |
| 1124 | older install finds out. A rule may not be in both lists (the install is |
| 1125 | refused). `tests/test_package_permission_retraction.py` reads this |
| 1126 | checkout's git history and fails, printing the entries to paste, when a |
| 1127 | rule that was once shipped is neither shipped nor retracted. |
| 1128 | |
| 1129 | Either way a live rule is removed only if it is tagged as this package's |
| 1130 | AND identical to the withdrawn one. A rule the operator edited no longer |
| 1131 | matches and a rule the operator wrote has no tag; both stay, and the |
| 1132 | install reports them (`permission_retractions` in the dry run and the |
| 1133 | install response; removed rules are kept whole in the package change |
| 1134 | log). `GET /permissions/unshipped` lists every rule in the policy that no |
| 1135 | installed package ships. See ""Package Rules And Upgrades"" in |
| 1136 | [`permissions-model.md`](/docs/permissions-model). |
| 1137 | - **A grant you leave out is not a refusal for the row's owner.** With no |
| 1138 | rule matching, the engine's owner fallback lets whoever `owner_id`, |
| 1139 | `user_id` or `created_by` names read, update and delete the row. If the |
| 1140 | people a collection's rows belong to must not change or remove them |
| 1141 | (a ledger, a log, a run history, anything whose rule says ""no delete""), |
| 1142 | ship the rule that says so: |
| 1143 | |
| 1144 | ```json |
| 1145 | {""effect"": ""deny"", ""principal"": ""owner_fallback"", |
| 1146 | ""actions"": [""update"", ""delete""], ""collection"": ""wallet_entries"", |
| 1147 | ""reason"": ""the ledger is the balance: entries are never edited or deleted""} |
| 1148 | ``` |
| 1149 | |
| 1150 | It switches the fallback off and nothing else: your explicit grants still |
| 1151 | grant, admins and in-process writers are unaffected. Details and where the |
| 1152 | fallback reaches: ""Ownership"" in |
| 1153 | [`permissions-model.md`](/docs/permissions-model). |
| 1154 | `tests/test_owner_fallback_opt_out.py` fails until a new collection whose |
| 1155 | owners get update or delete from the fallback alone is either opted out, |
| 1156 | granted explicitly, or listed there as a deliberate decision. |
| 1157 | - `migrations` are accepted in the manifest and reported in dry-runs, but |
| 1158 | install rejects them until explicit run semantics land. |
| 1159 | - `schedules` become `task_<id>` rows in the scheduler trigger's state, |
| 1160 | which is where `object_daemon.process_scheduler` reads the board from. |
| 1161 | **If your app needs a recurring pass, declare it here.** A schedule that |
| 1162 | exists only in a running server's state is invisible to review, absent |
| 1163 | from a fresh install, and gone the next time the box is rebuilt — that |
| 1164 | is precisely how a demo server ended up with four nightly passes that |
| 1165 | appeared nowhere in this repository. Fields: `id` (becomes the state |
| 1166 | key, `[a-z][a-z0-9_]*`), `object_id`, `schedule`, and optional `type` |
| 1167 | (`cron` — the default — or `onetime`), `method` (default `POST`), |
| 1168 | `payload`, `description`. |
| 1169 | |
| 1170 | Three properties make declaring a schedule safe to do repeatedly: |
| 1171 | |
| 1172 | - **Run history survives.** `last_run`, `run_count` and `next_run` |
| 1173 | belong to the daemon and are never reset by an install. An upgrade |
| 1174 | that forgot when a pass last worked would make ""is this actually |
| 1175 | running?"" unanswerable. |
| 1176 | - **A pause is honoured.** The package declares what *should* run; an |
| 1177 | operator decides what *does* right now. A reinstall never restarts a |
| 1178 | task somebody deliberately paused. |
| 1179 | - **A changed expression reschedules.** Editing the cron clears |
| 1180 | `next_run` so the daemon recomputes it; leaving it alone keeps |
| 1181 | tonight's firing exactly where it was, so shipping a patch does not |
| 1182 | skip a run. |
| 1183 | |
| 1184 | Two things are refused outright, at install time rather than at 3am: |
| 1185 | an unparseable cron (the daemon reads that as ""no next run"" and moves |
| 1186 | on in silence — a pass that never runs and never complains), and a |
| 1187 | schedule aimed at an object neither this package nor the server |
| 1188 | provides. Removing a schedule from a manifest does **not** delete the |
| 1189 | task, matching the rest of install: deregistering never destroys. |
| 1190 | - `nav` entries become rows in the `nav_entries` collection, which every |
| 1191 | navigation surface folds over. **If your app serves a page, declare its |
| 1192 | door here.** See the section below. |
| 1193 | - `attention` entries become rows in the `attention_sources` collection, |
| 1194 | which the daemon's rollup pass reads its list of providers from. |
| 1195 | **If your app has a queue that waits on a person, declare it here.** |
| 1196 | See the section below. |
| 1197 | - The HTTP install route creates a restore point first and appends changelog |
| 1198 | rows under `data/package_changes/{package_id}/changes.jsonl`. |
| 1199 | |
| 1200 | ## Navigation (`nav`) |
| 1201 | |
| 1202 | A menu maintained by hand rots the moment somebody ships without editing |
| 1203 | it, and the rot is invisible — nothing fails, the front door just |
| 1204 | advertises a server that no longer exists. This repository had three such |
| 1205 | lists of the same apps: the app switcher's JS array in `site_nav` (25 |
| 1206 | entries), the home page's tile grid in `site_home` (21), and a |
| 1207 | collection-to-URL map for search hits. They disagreed with each other and |
| 1208 | between them named none of the eight newest apps. Worse, `site_home` |
| 1209 | existed in no package at all — it lived only on a running server, so a |
| 1210 | rebuilt box came back with no front door and said nothing about it, which |
| 1211 | is precisely the failure the `schedules` section was built to end for |
| 1212 | cron. |
| 1213 | |
| 1214 | So a door is declared by the app that owns it, and every navigation |
| 1215 | surface becomes a fold over one registry: |
| 1216 | |
| 1217 | ```json |
| 1218 | ""nav"": [ |
| 1219 | {""id"": ""shop"", ""label"": ""Shop"", ""path"": ""/shop"", |
| 1220 | ""blurb"": ""Browse what is for sale and buy it"", |
| 1221 | ""surface"": ""public"", ""group"": ""Commerce"", ""order"": 400} |
| 1222 | ] |
| 1223 | ``` |
| 1224 | |
| 1225 | - `id` becomes the `nav_entries` record id, so `[a-z][a-z0-9_]*`. It must |
| 1226 | be unique across every installed package: two packages writing one row |
| 1227 | is two packages fighting over one door. |
| 1228 | - `label` and `path` are required. `path` starts with `/` and holds no |
| 1229 | whitespace. |
| 1230 | - `blurb` is one honest line in the present tense saying what the app |
| 1231 | does — it is rendered under the label on the home grid. No marketing. |
| 1232 | - `surface` is `public` | `member` | `operator` | `hidden`, default |
| 1233 | `member`. This governs the MENU and is not access control: permissions |
| 1234 | decide who may open a page, and leaving a door off the menu hides |
| 1235 | nothing that was not already protected. `/shop` and the public |
| 1236 | product/pay/portal pages are `public`; ordinary app pages are `member`; |
| 1237 | `/scheduler`, `/flow`, `/urls`, `/dashboard` and other admin or debug |
| 1238 | pages are `operator`. |
| 1239 | - `group` is free text, default `Apps`. The house groups are **Work**, |
| 1240 | **Publishing**, **Money**, **Commerce**, **Warehouse** and **System**. |
| 1241 | - `order` is an integer, default `100`. Packages band it by group (Work |
| 1242 | in the 0s, Publishing the 200s, Money the 300s, Commerce the 400s, |
| 1243 | Warehouse the 500s, System the 600s) because a group sorts where its |
| 1244 | earliest entry sorts — that way the reading order of the groups falls |
| 1245 | out of the same number, instead of a seventh list holding it. |
| 1246 | |
| 1247 | Three properties make declaring a door safe to do repeatedly: |
| 1248 | |
| 1249 | - **The operator's `hidden` survives.** `operator_hidden` is a separate |
| 1250 | boolean column and an install never writes it on an existing row. The |
| 1251 | package says what the app IS; the operator says what they want to SEE. |
| 1252 | An upgrade that silently put back a page somebody deliberately removed |
| 1253 | would be the same class of incident as one that restarts a paused |
| 1254 | nightly pass — so an operator flips `operator_hidden` (a `role:manager` |
| 1255 | update on `nav_entries`) instead of editing somebody else's manifest. |
| 1256 | - **Unchanged means unwritten.** Every package-owned field — label, path, |
| 1257 | blurb, group, surface, order — is compared before anything is written, |
| 1258 | so a plan that reports `unchanged` is one where nothing at all is about |
| 1259 | to happen. A dry run that under-reports is worse than no dry run. |
| 1260 | - **Removing an entry does not delete the row.** Same as the rest of |
| 1261 | install: deregistering never destroys. |
| 1262 | |
| 1263 | Two things are refused, and one deliberately is not: |
| 1264 | |
| 1265 | - A **duplicate id inside one manifest**, and an **invalid surface, path |
| 1266 | or order**, fail at parse time. |
| 1267 | - A **collision with another package** blocks the install: an id already |
| 1268 | registered by a different package, or a path a different package |
| 1269 | already claims. Whichever installed last would otherwise silently win, |
| 1270 | and the loser's menu entry would point somewhere its own package never |
| 1271 | chose. |
| 1272 | - Whether a path is actually **served** is NOT checked. Routing has three |
| 1273 | sources (convention, `site_routes` records, `views` records) and two of |
| 1274 | them are data the same install may be about to seed, so resolving a |
| 1275 | route here would produce false blockers. The registry records the door |
| 1276 | the package intends; `/urls` is where you go to see what the server |
| 1277 | actually answers. |
| 1278 | |
| 1279 | If the `nav_entries` collection does not exist yet (app-nav is not |
| 1280 | installed), nav entries (and `attention` sources) are reported as `skipped` |
| 1281 | with a reason and the install proceeds, with a line in the result's |
| 1282 | `warnings` saying they were NOT registered. A package must never fail because |
| 1283 | the navigation app is absent, and **install order does not matter**: the |
| 1284 | install records what the package declared (in its baseline), and installing |
| 1285 | `app-nav` registers the nav entries and attention sources of every package |
| 1286 | already installed, listed in its result as `registered_for_others`. Only |
| 1287 | missing rows are written, as their own package's; an existing row (an |
| 1288 | operator's `operator_hidden` or `operator_muted`, another package's id) is |
| 1289 | left as it is. A box installed before declarations were recorded falls back |
| 1290 | to the package's manifest, only when that is the installed version, and |
| 1291 | otherwise names the package in `warnings` (reinstall it). |
| 1292 | `tests/test_install_order_nav.py` checks both orders. |
| 1293 | |
| 1294 | The same holds on an upgraded box whose `app-nav` is still the previous |
| 1295 | release's. Its installed `attention_sources` schema can be older than the one |
| 1296 | this tree ships (before declared counts it required `object_id`), and a row |
| 1297 | written under the old schema would be refused, failing the install of the |
| 1298 | package that declares the count. An install that finds the owner's installed |
| 1299 | schema behind the one in this tree does not write those attention rows: they |
| 1300 | are `skipped` with `stale_schema_owner` naming the package, the install |
| 1301 | succeeds, and `warnings` says the rows wait for it. Installing `app-nav` |
| 1302 | refreshes the schema and registers them (`registered_for_others`). A real |
| 1303 | validation error against a current schema still refuses the install. |
| 1304 | `tests/test_install_order_after_upgrade.py` installs `app-nav` from the |
| 1305 | previous tag, then a package from this tree. |
| 1306 | |
| 1307 | ### Depend on app-nav |
| 1308 | |
| 1309 | **The rule: a package that declares `nav` or `attention` lists `""app-nav""` in |
| 1310 | `dependencies`.** The installer does not resolve dependencies (it records |
| 1311 | them), but `scripts/try_package.py` installs a package's dependencies first, so |
| 1312 | the declaration makes `app-nav` land first and the entries land with the |
| 1313 | package itself; it also tells a reader what the package needs. `scripts/new_package.py` |
| 1314 | writes it. It is a ""should"", not a ""must"": nothing refuses a manifest without |
| 1315 | it, because install must never fail on the navigation app's absence, and an |
| 1316 | app-nav installed later registers the entries anyway (above). Most of the |
| 1317 | packages shipped before this rule was written do not declare it (a gap the |
| 1318 | next version bump of each is the time to close, not a reason to copy it). |
| 1319 | |
| 1320 | ### The opt-out |
| 1321 | |
| 1322 | `tests/test_package_nav.py` asserts that every package shipping a `site_*` |
| 1323 | object or a `site_routes` seed declares at least one nav entry. That test |
| 1324 | is the thing that stops the drift coming back. Some packages legitimately |
| 1325 | serve a URL that is not a door — a mounted widget (`site_thread`, |
| 1326 | `site_share`), a fragment inside another page |
| 1327 | (`site_materialize_run_button`), a POST endpoint (`site_timer_actions`), |
| 1328 | or a per-record document reached from the record itself |
| 1329 | (`site_packing_slip`, `site_receiving_sheet`, `site_return_form`). Those |
| 1330 | declare: |
| 1331 | |
| 1332 | ```json |
| 1333 | ""nav_optional"": true |
| 1334 | ``` |
| 1335 | |
| 1336 | which makes ""this app has no front page"" a reviewable claim in the |
| 1337 | manifest rather than an omission nobody notices. |
| 1338 | |
| 1339 | ## Attention (`attention`) |
| 1340 | |
| 1341 | A menu answers ""where can I go"". The only question a home screen is |
| 1342 | actually asked is **does anything need me?**, and this server is unusually |
| 1343 | well placed to answer it, because it is built almost entirely out of gates |
| 1344 | and derived states. Every one of them produces a queue of things a machine |
| 1345 | deliberately refused to decide: scans sitting at `extracted` waiting to be |
| 1346 | confirmed into expenses, time entries `submitted` waiting for an approver |
| 1347 | who is by design not the person who logged them, invoices past their due |
| 1348 | date, bank lines nothing matched, POs a supplier shorted, orders committed |
| 1349 | and not yet in a box, returns that arrived and were never judged. |
| 1350 | |
| 1351 | The system already computes all of it, on a schedule, and throws it away |
| 1352 | at the end of each pass. `system_scan_processor` has been returning a |
| 1353 | field literally named `needing_a_human` since the day it was written and |
| 1354 | no surface has ever read it. The arithmetic was never missing; a place to |
| 1355 | declare that the arithmetic *means* something was — and that declaration |
| 1356 | can only honestly live in the package that owns the domain, because |
| 1357 | nobody else knows that `extracted` is a waiting room and `confirmed` is |
| 1358 | not. |
| 1359 | |
| 1360 | So it is declared, third use of the pattern that already fixed cron |
| 1361 | (`schedules`) and navigation (`nav`): |
| 1362 | |
| 1363 | ```json |
| 1364 | ""attention"": [ |
| 1365 | {""id"": ""orders_to_pick"", ""object_id"": ""system_order_attention"", |
| 1366 | ""reads"": [""orders"", ""order_lines"", ""shipments"", ""shipment_lines""], |
| 1367 | ""label"": ""Orders to pick"", ""path"": ""/orders"", |
| 1368 | ""nav_id"": ""orders"", ""group"": ""Commerce"", ""severity"": ""normal""} |
| 1369 | ] |
| 1370 | ``` |
| 1371 | |
| 1372 | Or, when the queue is ""rows of one collection in a waiting state"" (it |
| 1373 | usually is), declare the count instead of writing a provider — see |
| 1374 | [Declared counts](#declared-counts-collection--where): |
| 1375 | |
| 1376 | ```json |
| 1377 | ""attention"": [ |
| 1378 | {""id"": ""scans_to_confirm"", ""collection"": ""scans"", |
| 1379 | ""where"": {""status"": ""extracted""}, |
| 1380 | ""detail"": {""op"": ""count"", |
| 1381 | ""where"": {""created_at"": {""op"": ""older_than_days"", ""value"": 7}}, |
| 1382 | ""text"": ""{value} over a week old""}, |
| 1383 | ""label"": ""Receipts to confirm"", ""path"": ""/scans"", |
| 1384 | ""nav_id"": ""scans"", ""group"": ""Money"", ""severity"": ""normal""} |
| 1385 | ] |
| 1386 | ``` |
| 1387 | |
| 1388 | - `id` becomes the `attention_sources` record id, so `[a-z][a-z0-9_]*`, |
| 1389 | and it must be unique across every installed package. |
| 1390 | - `object_id` names the provider (below), or `collection` names the |
| 1391 | collection a declared count reads — exactly one of the two. Checked: a |
| 1392 | counter aimed at an object (or a collection) neither this package nor |
| 1393 | the server provides **blocks the install**, exactly as a schedule does. A counter pointing |
| 1394 | at nothing reads zero forever, and a queue that reads zero forever is |
| 1395 | indistinguishable from a queue that is empty — the silent failure this |
| 1396 | whole section exists to end. |
| 1397 | - `reads` (providers only) lists the collections the provider folds its |
| 1398 | number from. The number is computed with no viewer, so it is shown only |
| 1399 | to a viewer who may read **every row** of each listed collection the box |
| 1400 | has — see [Who sees a provider's number](#who-sees-a-providers-number). |
| 1401 | Leave it out and only admins see the count. |
| 1402 | - `label` is what a person calls the queue, in their words: ""Receipts to |
| 1403 | confirm"", not ""scans.status=extracted"". |
| 1404 | - `path` is where the count clicks through to. Required, starts with `/`, |
| 1405 | no whitespace. **A number that cannot be acted on in one click does not |
| 1406 | belong on a home page.** Whether anything actually serves the path is |
| 1407 | not checked, for the same reason `nav` does not check it. |
| 1408 | - `nav_id` is optional: the `nav_entries` row this count decorates, so the |
| 1409 | app list itself reads ""Invoices — 5 overdue"" with no second surface to |
| 1410 | maintain. Omit it when the package ships no door at all (app-intake). |
| 1411 | **Two queues may name one door, and its badge is their sum**: a person with |
| 1412 | one deal they own and one assigned to them, as two sources on `nav_id: |
| 1413 | ""deals""`, sees `2` on the Deals entry (the entry's `severity` is the |
| 1414 | loudest of the two and its `detail` joins theirs). Before 2026-11 the |
| 1415 | louder queue won and the other was silently dropped. Each queue still has |
| 1416 | its own row, with its own count, in `attention`. Because they are added, a |
| 1417 | row that matches both queues is counted twice on the badge: make the |
| 1418 | queues disjoint, or put the union in one provider. |
| 1419 | - `group` is free text, default `Apps`, and uses the same house groups as |
| 1420 | `nav`. |
| 1421 | - `severity` is `normal` | `warning` | `urgent`, default `normal`, and is |
| 1422 | the first sort key on the home band. `normal` is work waiting; |
| 1423 | `warning` is work that is already late (an overdue invoice); `urgent` |
| 1424 | is something broken (a scheduler pass that failed). Three steps, |
| 1425 | because a scale with more is a scale nobody calibrates. |
| 1426 | |
| 1427 | ### Declared counts (`collection` + `where`) |
| 1428 | |
| 1429 | Ten of the first sixteen providers were the same fifteen lines: read one |
| 1430 | collection, keep the rows in the waiting state, return `len()` and a |
| 1431 | sentence. A declaration says that instead, and `object_attention.count` |
| 1432 | is the one function that evaluates every declaration. |
| 1433 | |
| 1434 | - **`where` is the permission row-filter language**, the same one a |
| 1435 | rule's `row_filter` uses and `object_permissions.record_matches_filter` |
| 1436 | decides — not a second one. Each value is a literal (`eq`), a |
| 1437 | `$`-variable, one `{""op"", ""value""}` condition (`eq`, `ne`, `in`, `gte`, |
| 1438 | `lte`, `gt`, `lt`), or a list of conditions ANDed. Membership is |
| 1439 | `{""op"": ""in"", ""value"": [""unmatched"", """"]}`; a bare list is refused, |
| 1440 | because in a row filter it is not membership. ""Not one of these"" is a |
| 1441 | list of `ne` conditions. |
| 1442 | - **One operator is added**, for attention only: `{""op"": |
| 1443 | ""older_than_days"", ""value"": 7}`, which is **inclusive**: a row matches when |
| 1444 | its age is 7 or more days (`age >= 7`). A `YYYY-MM-DD` value is aged in |
| 1445 | calendar days against the server's local date; any other value is an ISO |
| 1446 | datetime (`Z` accepted, naive read as UTC) aged in elapsed whole days. An |
| 1447 | empty or unparseable value is never older than anything. ""Due before |
| 1448 | today"" is `{""op"": ""older_than_days"", ""value"": 1}` on a date. |
| 1449 | - **Its threshold may be a setting**: `{""op"": ""older_than_days"", ""value"": |
| 1450 | {""setting"": ""carrier.stuck_days"", ""default"": 10}}` reads the first |
| 1451 | `app_settings` row with exactly that key and a non-blank value, once per |
| 1452 | count, through the key index. A value that is not a whole number of days |
| 1453 | ≥ 0 (`soon`, `7.5`, `-3`), or a box without app-settings, reads as the |
| 1454 | default. That is the only thing a declaration reads from settings: a |
| 1455 | number of days, by key — never an expression. |
| 1456 | - **At least one literal equality is required** (`""status"": ""submitted""`, |
| 1457 | or `in`). The rows are fetched through the records cache's field index on |
| 1458 | it, so counting costs the queue, not the collection. A `where` made only |
| 1459 | of `ne` / ranges is refused at install. |
| 1460 | - **""My own rows"" is `$user_id`** — `{""status"": ""draft"", ""owner_id"": |
| 1461 | ""$user_id""}` — resolved for the viewer. There is no separate scope switch. |
| 1462 | |
| 1463 | `detail` is optional: one part, or a list of parts joined with "", "". |
| 1464 | |
| 1465 | | Part | Value | |
| 1466 | |---|---| |
| 1467 | | `{""op"": ""count"", ""where""?: {...}, ""text"": ""{value} over a week old""}` | the counted rows, or those also matching `where` | |
| 1468 | | `{""op"": ""sum"", ""field"": ""amount_cents"", ""format""?: ..., ""text"": ...}` | an integer field summed; an unparseable cell adds 0 | |
| 1469 | | `{""op"": ""max_age_days"", ""field"": ""requested_on"", ""text"": ""oldest {value} days""}` | the oldest dated row's age; undated and future rows add nothing | |
| 1470 | |
| 1471 | A part whose value is 0 is left out unless it says `""show_zero"": true`; a |
| 1472 | `max_age_days` with no dated rows is always left out. `{value}` is |
| 1473 | optional: a `text` without it is a fixed sentence shown exactly when the |
| 1474 | part would have been (`{""op"": ""count"", ""text"": ""failed 3 or more syncs in a |
| 1475 | row""}`). `format` (sums only): `integer` (default), `cents` (`1,234.56`), |
| 1476 | `dollars` (`$1234.56`), `hours` (seconds as hours, one decimal). Integer |
| 1477 | arithmetic throughout. |
| 1478 | |
| 1479 | **Booleans need no case-insensitive operator.** The write path stores a |
| 1480 | `boolean` field as exactly `true` or `false` (or blank), so ""enabled, |
| 1481 | where blank means enabled"" is `{""op"": ""in"", ""value"": [""true"", """"]}` and |
| 1482 | ""failed"" is `""ok"": ""false""`. **""Not one of these"" over an `enum`** that |
| 1483 | must also serve as the index is the complement written out — `""status"": |
| 1484 | {""op"": ""in"", ""value"": [""sent"", ""partial"", ""overdue"", """"]}` — with a test |
| 1485 | that the list plus the excluded values is the enum plus blank, so a value |
| 1486 | added to the enum later fails a test instead of silently dropping out of |
| 1487 | the count (`tests/test_app_invoices_package.py`). |
| 1488 | |
| 1489 | **Counted for the viewer, through the permission engine.** A declared |
| 1490 | count is the number of matching rows *the person looking* may read |
| 1491 | (`object_access.Access.visible`, the same per-row question the record API |
| 1492 | asks), and the detail is computed over the same rows. An admin sees the |
| 1493 | whole queue; a manager whose rule grants the collection sees the rows that |
| 1494 | rule grants; a member with an owner-filtered read sees their own; someone |
| 1495 | with no grant sees nothing. It fails closed wherever `object_access` does: |
| 1496 | no identity, an unreadable policy. Project and share grants count, as they |
| 1497 | do for the record API. |
| 1498 | |
| 1499 | **Counted from the fields the viewer may read**, when permissions are |
| 1500 | enforced (`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT`). Reading a row is not |
| 1501 | reading all of it: a rule's `fields` / `denied_fields` or a schema field's |
| 1502 | `permissions` can hide a field from someone who reads the row. Each row is |
| 1503 | therefore judged as the record API would serve it to the viewer |
| 1504 | (`object_access.Access.readable`), and: |
| 1505 | |
| 1506 | - a `where` condition on a field the viewer cannot read in a row is |
| 1507 | **false for that row**, whatever the operator (`ne` included). The count |
| 1508 | becomes ""rows where this field, which you can see, matches"": a support |
| 1509 | agent who reads every ticket but not `salary_band` sees `0` for a queue |
| 1510 | declared `""where"": {""status"": ""open"", ""salary_band"": ""A""}`, not the |
| 1511 | number of band-A tickets. If a queue is meant for people who cannot read |
| 1512 | the field it filters on, filter on a field they can read; |
| 1513 | - a `sum` or `max_age_days` adds nothing from a row whose `field` the |
| 1514 | viewer cannot read, and a detail part's own `where` follows the rule |
| 1515 | above. When a field is hidden on some rows only (a field hidden from the |
| 1516 | row's `owner`), the sentence covers the rows where it is readable; |
| 1517 | - a detail part that depends on a hidden field in **every** counted row is |
| 1518 | left out, even with `""show_zero"": true`: ""0.00 awaiting approval"" would |
| 1519 | be a statement about a field the viewer cannot read. The other parts of |
| 1520 | the sentence are kept. |
| 1521 | |
| 1522 | With enforcement off or audit-only nothing is redacted anywhere, and |
| 1523 | counts and sentences are the row-level ones described above, unchanged. If |
| 1524 | the mode cannot be determined, nothing is counted. A viewer who reads |
| 1525 | every field a declaration names sees the same numbers either way. Being an |
| 1526 | admin is not the same thing: the schema can hide a field from an admin as |
| 1527 | from anyone. Among the shipped packages (audited 2026-12-03) exactly two |
| 1528 | queues change, `thread_comments_to_moderate` and |
| 1529 | `profile_comments_to_moderate`: their `status` is hidden from everyone but |
| 1530 | the comment's owner and the `moderator` role, so with enforcement on an |
| 1531 | admin who is not also a moderator is no longer shown those counts (the |
| 1532 | record API does not show them `status` either). Moderators, and admins who |
| 1533 | are also moderators, see what they did. The threshold a `{""setting"": ...}` reads from `app_settings` is |
| 1534 | the box's configuration, the same for every viewer, and is not redacted. |
| 1535 | |
| 1536 | A code provider's number, by contrast, is computed with no viewer, so it |
| 1537 | reaches only viewers who may read every row it was folded from |
| 1538 | ([below](#who-sees-a-providers-number)) — which is why a queue that can be |
| 1539 | declared should be: a member then sees their own share instead of nothing. |
| 1540 | |
| 1541 | Declared counts are therefore **not rolled up**: the daemon skips them, |
| 1542 | and removes any number a replaced provider left in `attention_counts`, a |
| 1543 | global count being exactly what a per-viewer one must not leak. The index read is what keeps |
| 1544 | this inside the rule below: the cost of a home render is each queue's |
| 1545 | candidate rows, not a fold over the collection. (A collection over |
| 1546 | `DBBASIC_RECORDS_CACHE_MAX_ROWS` has no index and is read whole, exactly as |
| 1547 | every API list of it already is.) |
| 1548 | |
| 1549 | Write a provider instead when the number needs another collection (a |
| 1550 | quantity still owed across order and receipt lines), arithmetic between |
| 1551 | fields (how far below its reorder point the worst shelf is), one field |
| 1552 | standing in for another (a run's `started_at`, else its `created_at`), or |
| 1553 | a comparison the row-filter language does not have (a naive local |
| 1554 | datetime against the wall clock, in minutes). Those are loops, functions |
| 1555 | and expressions, and configuration never gets them. The five providers |
| 1556 | that remain, and why: |
| 1557 | |
| 1558 | | Provider | Why it is code | |
| 1559 | |---|---| |
| 1560 | | `orders_to_pick` | ordered minus shipped, across orders, order lines, shipments and shipment lines | |
| 1561 | | `pos_short_received` | the detail folds receipts and receipt lines against order lines | |
| 1562 | | `products_to_reorder` | the detail is `reorder_point - on_hand` | |
| 1563 | | `pickup_orders_overdue` | ""not ready"" has no index-able equality (it is the whole order history), `promised_at` is local wall-clock time, and the detail is in minutes | |
| 1564 | | `scheduler_failures` | `started_at` falling back to `created_at`, distinct tasks by `task_id` falling back to `object_id`; scheduler runs are admin-read only, so gating it loses nobody | |
| 1565 | |
| 1566 | ### Who sees a provider's number |
| 1567 | |
| 1568 | A provider's count was computed by the daemon over every row of the |
| 1569 | collections it reads, with no viewer, and until 2026-11 it was shown to |
| 1570 | every signed-in user — so a member with no grant on purchase orders saw how |
| 1571 | many were short. Now `object_attention.provider_shown_to` decides, fail |
| 1572 | closed: |
| 1573 | |
| 1574 | - an admin sees it; |
| 1575 | - anyone else sees it only when the entry's `reads` names at least one |
| 1576 | collection the box has, and for **each** of them the viewer may read |
| 1577 | every row, whole (`object_access.Access.reads_every_row`): no deny rule |
| 1578 | that applies to them (filtered or not), and either the access mode allows |
| 1579 | the read or some allow rule grants it with no row filter and no field |
| 1580 | restriction. An own-rows grant is not enough — the number is everybody's |
| 1581 | rows; |
| 1582 | - an entry with no `reads`, a `reads` that does not parse, or a stored |
| 1583 | count whose source row is gone: admins only; |
| 1584 | - a listed collection the box does not have holds no rows and is skipped. |
| 1585 | - with permissions enforced, a listed collection whose **schema** could |
| 1586 | hide any field from the viewer in some row hides the number from them, |
| 1587 | admins included (`object_field_permissions.may_hide_a_field`). The rule |
| 1588 | check above looks at rules only, and a provider does not say which |
| 1589 | fields it folds, so any field the record API would redact for this |
| 1590 | viewer might be one it counted or described. ""Could hide"" is decided |
| 1591 | without a row and fails closed: a field hidden from a principal the |
| 1592 | viewer matches, hidden from `owner` (anyone can own a row), hidden by |
| 1593 | `default` unless a role or other row-independent principal the viewer |
| 1594 | matches grants read or edit, or a `permissions` that does not parse. With |
| 1595 | enforcement off no field is redacted and this check is skipped; if the |
| 1596 | mode cannot be determined the number is shown to nobody. No shipped |
| 1597 | provider reads a collection with field permissions today. |
| 1598 | |
| 1599 | `attention_counts` itself is readable by nobody but an admin: the menu |
| 1600 | reads it in process (`action_nav_entries`), and app-nav retracts the |
| 1601 | `registered` read rule it used to ship, so an upgraded box drops it too. |
| 1602 | |
| 1603 | ### The COUNT contract |
| 1604 | |
| 1605 | A provider is an ordinary object exposing: |
| 1606 | |
| 1607 | ```python |
| 1608 | def COUNT(request): |
| 1609 | return {""count"": 3, ""detail"": ""1 over a week old""} |
| 1610 | ``` |
| 1611 | |
| 1612 | `COUNT` and not `GET` or `POST`, deliberately: a distinct verb means the |
| 1613 | same object stays free to answer a human on the other methods without |
| 1614 | either use accidentally serving the other. `count` must be a real |
| 1615 | non-negative integer — the rollup refuses to coerce a string or a float, |
| 1616 | because every coercion here is a way for a broken provider to look like |
| 1617 | an empty queue. `detail` is optional and is the sentence a bare number |
| 1618 | cannot say (""62 hours awaiting approval"", ""18 units still owed""). |
| 1619 | |
| 1620 | A provider reads its own collections and **degrades to `{""count"": 0}` |
| 1621 | when they are absent** — a deployment that never installed your app |
| 1622 | should not produce an error every five minutes. A provider that genuinely |
| 1623 | fails should raise; see below for what happens then. |
| 1624 | |
| 1625 | ### Counts are a rollup, not a live fold |
| 1626 | |
| 1627 | `object_daemon.process_attention` executes every code provider on an |
| 1628 | interval (`DBBASIC_ATTENTION_INTERVAL_SECONDS`, default 300) and writes |
| 1629 | the answers to the `attention_counts` collection. The home page and the |
| 1630 | app list read that one small table. |
| 1631 | |
| 1632 | This is not an optimisation, it is a rule. Folding a dozen collections on |
| 1633 | every home render is how a home page becomes the slowest page, and worse: |
| 1634 | this box went to 675MB resident and started swapping because something |
| 1635 | folded a big collection on a timer. A home screen that folds a dozen |
| 1636 | collections per render is that same mistake with a nicer name, and it |
| 1637 | makes the front page's cost grow with the number of installed packages — |
| 1638 | the one place cost must not grow. Staleness is bounded by the interval |
| 1639 | and **stated on the page** (""as of 6 minutes ago"") rather than pretended |
| 1640 | away. |
| 1641 | |
| 1642 | Two consequences worth knowing when you write a provider: |
| 1643 | |
| 1644 | - **A broken provider must look broken, never look calm.** One that |
| 1645 | raises, or answers with a non-integer count, has its `error` written |
| 1646 | and its *previous* count kept, with `computed_at` left where it was. |
| 1647 | Zeroing it would report an empty queue when what happened is that |
| 1648 | nobody looked. |
| 1649 | - **Do not do expensive work per row.** The pass runs every five minutes |
| 1650 | on the same box that serves requests. A full scan of your own |
| 1651 | collections is the intended cost; calling out to a network is not. |
| 1652 | |
| 1653 | ### Zeros disappear |
| 1654 | |
| 1655 | A count of zero is stored (the absence of a row means the provider has |
| 1656 | never run, which is a different fact) and **rendered nowhere**. When |
| 1657 | every queue is empty the home page's ""Needs you"" band is absent entirely |
| 1658 | — not ""0 pending"", not an empty panel with a heading: gone. |
| 1659 | |
| 1660 | This is the rule that separates an inbox from a dashboard. A board that |
| 1661 | says ""0 pending approvals"" every day trains people to stop reading it, |
| 1662 | and once they have stopped they do not start again on the day it says |
| 1663 | three. A page that is EMPTY when nothing needs them, and short when |
| 1664 | something does, gets read every time. ""Nothing needs you"" is a complete |
| 1665 | and welcome answer, and blank space gives it better than any sentence |
| 1666 | would. |
| 1667 | |
| 1668 | ### Idempotency and the operator |
| 1669 | |
| 1670 | The same three properties `nav` has: |
| 1671 | |
| 1672 | - **The operator's `operator_muted` survives.** A deployment that does |
| 1673 | not work a queue mutes it (a `role:manager` update on |
| 1674 | `attention_sources`) instead of editing somebody else's manifest, and |
| 1675 | an install never writes that column. A muted source is not executed at |
| 1676 | all and its stored count is removed, so it costs nothing and shows |
| 1677 | nothing. |
| 1678 | - **Unchanged means unwritten.** Every package-owned field — |
| 1679 | `object_id`, `collection`, `where`, `detail`, `label`, `path`, `nav_id`, `group`, `severity` — is |
| 1680 | compared before anything is written. |
| 1681 | - **Removing an entry does not delete the row.** Deregistering never |
| 1682 | destroys. |
| 1683 | |
| 1684 | A **collision with another package** on an `id` blocks the install: two |
| 1685 | packages writing one row is two definitions of what needs a human, and |
| 1686 | whichever installed last would silently win. Unlike `nav` there is no |
| 1687 | path-collision rule — two queues legitimately point at one list, and |
| 1688 | blocking that would be a false blocker. |
| 1689 | |
| 1690 | If the `attention_sources` collection does not exist (app-nav is not |
| 1691 | installed) the entries are reported as `skipped` with a reason and the |
| 1692 | install proceeds, exactly as `nav` entries are. |
| 1693 | |
| 1694 | ## Personal data: the subject export |
| 1695 | |
| 1696 | `action_export_subject_data` (app-privacy, admin-only) answers a subject |
| 1697 | access request: everything the server holds about one email address, in one |
| 1698 | document. It does not have its own list of collections. Each schema declares |
| 1699 | what in it is personal, and the export folds every installed collection by |
| 1700 | those declarations (three schema files, shown together): |
| 1701 | |
| 1702 | ```text |
| 1703 | {""name"": ""patients"", ""fields"": [ |
| 1704 | {""name"": ""id""}, |
| 1705 | {""name"": ""email"", ""subject"": ""email""}]} |
| 1706 | |
| 1707 | {""name"": ""appointments"", ""fields"": [ |
| 1708 | {""name"": ""id""}, |
| 1709 | {""name"": ""patient_id"", ""subject"": ""relation"", ""relation"": {""collection"": ""patients""}}]} |
| 1710 | |
| 1711 | {""name"": ""treatment_notes"", ""fields"": [ |
| 1712 | {""name"": ""id""}, |
| 1713 | {""name"": ""appointment_id"", ""subject"": ""relation"", ""relation"": {""collection"": ""appointments""}}]} |
| 1714 | ``` |
| 1715 | |
| 1716 | - `""subject"": ""email""` — this field holds the person's email address. A row |
| 1717 | whose value is their address (case and surrounding spaces ignored) is |
| 1718 | theirs. |
| 1719 | - `""subject"": ""relation""` — this relation points at a record already proven |
| 1720 | to be theirs, so the row is theirs too. Relations are followed to any depth |
| 1721 | (notes → appointments → patients), and only in that direction: from the |
| 1722 | person's own rows to rows that point at them. A relation to a shared record |
| 1723 | (a product, a fund) is not declared and is never a way in. |
| 1724 | - `""subject_exempt"": ""<why>""` at the schema root — no field identifies a |
| 1725 | person (rows keyed by an anonymous visitor token, the operator's own |
| 1726 | mailboxes). The sentence is returned under `not_searchable`. |
| 1727 | |
| 1728 | The loader refuses any other `subject` value, and a `relation` declaration |
| 1729 | without a relation, because a typo there would leave a person's records out of |
| 1730 | their own request. A collection with an email-like field (a name containing |
| 1731 | `email`, or `to` / `sent_to`) that declares nothing is still named in the |
| 1732 | export's `not_searchable`, with `""undeclared"": true` and the fields, and is |
| 1733 | not searched. `tests/test_privacy.py` fails when a shipped schema has such a |
| 1734 | field and no declaration. The export also lists what it `searched`, and under |
| 1735 | `unavailable` any collection a declaration points at that the box doesn't have, |
| 1736 | or that could not be read. |
| 1737 | |
| 1738 | A box upgraded from before these keys existed keeps its installed schemas until |
| 1739 | the upgrade reinstalls the packages. Until then the export names those |
| 1740 | collections as undeclared rather than guessing. |
| 1741 | |
| 1742 | The declarations say what is personal. They say nothing about what may be |
| 1743 | **erased** or how long it is **kept**. The export offers no erasure: orders, |
| 1744 | invoices and payments are business records with statutory retention, and |
| 1745 | deleting a row an invoice references breaks the ledger rather than |
| 1746 | anonymising anyone. Which fields are contact details (redactable) and which are |
| 1747 | evidence (kept), and for how long, is an open decision for the owner, to be |
| 1748 | made per collection before any erasure code is written. |
| 1749 | |
| 1750 | ## Editor Help: The DRON Schemas |
| 1751 | |
| 1752 | Everything a package declares (schemas, manifest, permission rules) is |
| 1753 | described by JSON Schema files in `dron/`, the formal side of |
| 1754 | DRON. Point an editor at them and it completes keys, shows each |
| 1755 | key's description on hover, and underlines the mistakes the installer would |
| 1756 | refuse (a misspelt `row_filter`, `maxlength` for `validation.max_length`, |
| 1757 | `""surface"": ""private""`) before you get as far as installing. |
| 1758 | |
| 1759 | | File | Schema | |
| 1760 | |---|---| |
| 1761 | | `packages/*/schemas/*.json` | `dron/dron-collection.schema.json` | |
| 1762 | | `packages/*/dbbasic-package.json` | `dron/dron-package.schema.json` | |
| 1763 | | `packages/*/permissions/*.json` | `dron/dron-permissions.schema.json` | |
| 1764 | |
| 1765 | Two more schemas describe files that are not part of a package: the |
| 1766 | deployment's own policy, `data/permissions/policy.json` (what |
| 1767 | `PUT /permissions/policy` stores), by `dron/dron-policy.schema.json`, and the |
| 1768 | signed envelope boxes exchange, by `dron/dron-document.schema.json`. Map them |
| 1769 | the same way in your own deployment's editor settings; a box reads its own |
| 1770 | policy more loosely than the schema (see `dron.md`), so run an |
| 1771 | operator-written policy through the schema before saving it. |
| 1772 | |
| 1773 | **VS Code, no change to any package file.** In `.vscode/settings.json`: |
| 1774 | |
| 1775 | ```json |
| 1776 | { |
| 1777 | ""json.schemas"": [ |
| 1778 | {""fileMatch"": [""packages/*/schemas/*.json""], |
| 1779 | ""url"": ""./dron/dron-collection.schema.json""}, |
| 1780 | {""fileMatch"": [""packages/*/dbbasic-package.json""], |
| 1781 | ""url"": ""./dron/dron-package.schema.json""}, |
| 1782 | {""fileMatch"": [""packages/*/permissions/*.json""], |
| 1783 | ""url"": ""./dron/dron-permissions.schema.json""} |
| 1784 | ] |
| 1785 | } |
| 1786 | ``` |
| 1787 | |
| 1788 | **Or per file**, a `$schema` key at the top of the file, relative to it: |
| 1789 | |
| 1790 | ```json |
| 1791 | {""$schema"": ""../../../dron/dron-collection.schema.json"", ""name"": ""invoices""} |
| 1792 | ``` |
| 1793 | |
| 1794 | The loaders ignore a `$schema` key (a collection's is dropped when the schema |
| 1795 | is normalized, the manifest's and a rules file's are never read), and the DRON |
| 1796 | schemas allow it, so adding one never breaks an install |
| 1797 | (`tests/test_dron_schema.py` proves it through the real loaders). The |
| 1798 | shipped packages do not carry one: it would change every file's content hash |
| 1799 | and restore-point baseline for no change in behaviour, so they rely on the |
| 1800 | editor mapping above. |
| 1801 | |
| 1802 | `tests/test_dron_schema.py` validates every shipped file against these |
| 1803 | schemas, so a file that an editor flags is a file CI flags. A fragment that |
| 1804 | the schema cannot judge on its own (a `required_when` naming a field the |
| 1805 | collection does not have, two nav entries with one id) is still refused by the |
| 1806 | loader at install; the test lists each such case. |
| 1807 | |
| 1808 | ## Start From A Scaffold |
| 1809 | |
| 1810 | ```sh |
| 1811 | python scripts/new_package.py app-tickets |
| 1812 | python scripts/try_package.py app-tickets --user ann --user bob --brief \ |
| 1813 | --call 'ann POST /collections/tickets/records {""title"": ""first"", ""owner_id"": ""ann""}' \ |
| 1814 | --call 'bob GET /collections/tickets/records' --rows 'ann /tickets' |
| 1815 | ``` |
| 1816 | |
| 1817 | `scripts/new_package.py <id>` (standard library, writes only the new |
| 1818 | directory, refuses to overwrite one) creates `packages/<id>/` with a working |
| 1819 | package: a manifest, one schema (collection name = the id without `app-`, dashes |
| 1820 | to underscores; `--collection` overrides), the owner rule from the recipes |
| 1821 | below, a seeded list page at `/<collection>` and a menu entry. It depends on |
| 1822 | `app-nav` and `app-views` because it ships both. It installs as it stands and |
| 1823 | passes `tests/test_dron_schema.py`'s checks, so every later edit starts from a |
| 1824 | package that works: change one thing, run `try_package.py`, repeat. Next steps |
| 1825 | are the [recipes](#recipes) (add a field, a role, a queue, a freeze), then the |
| 1826 | workflow below. Pass `--dir` to write somewhere other than `packages/`; give the |
| 1827 | same directory to `try_package.py --packages-dir`. |
| 1828 | |
| 1829 | ## Authoring Workflow |
| 1830 | |
| 1831 | 1. Create the package directory and manifest (or start from the |
| 1832 | [scaffold](#start-from-a-scaffold)). |
| 1833 | 2. Write the objects (see [`object-authoring.md`](/docs/object-authoring) for method shape, state, logs, |
| 1834 | `request[""_identity""]`, and HTML form patterns). |
| 1835 | 3. Write each schema JSON (`{""fields"": [{""name"": ""id""}, ...]}` — see the |
| 1836 | schemas section of [`http-api-contract.md`](/docs/http-api-contract) for validation and field |
| 1837 | permission options). |
| 1838 | 4. Seed TSV: first row is the header, tab-separated, and must include `id`. |
| 1839 | 5. Try it before you install anywhere real: |
| 1840 | [`scripts/try_package.py`](#try-your-change) installs the package into a |
| 1841 | scratch directory and calls it as users with roles, enforcement on. |
| 1842 | Then dry-run: |
| 1843 | |
| 1844 | ```http |
| 1845 | GET /packages/{package_id}?dry_run=true |
| 1846 | Authorization: Token <token> |
| 1847 | ``` |
| 1848 | |
| 1849 | The plan reports what would be created, replaced, merged, applied, or |
| 1850 | skipped, with warnings. Nothing is written. |
| 1851 | 6. Install (requires `DBBASIC_ENABLE_PACKAGE_INSTALLS=true` plus the admin |
| 1852 | gate): |
| 1853 | |
| 1854 | ```http |
| 1855 | POST /packages/{package_id}/install |
| 1856 | Authorization: Token <token> |
| 1857 | ``` |
| 1858 | |
| 1859 | 7. Verify: run the objects, read the records, check |
| 1860 | `GET /packages/{package_id}/changes` for the install changelog, and use |
| 1861 | `POST /packages/{package_id}/restore` if the install needs to be rolled |
| 1862 | back (requires `DBBASIC_ENABLE_PACKAGE_RESTORE=true`). |
| 1863 | |
| 1864 | ## What A Schema's `version` Does |
| 1865 | |
| 1866 | `""version"": 7` in a collection schema is a **label**, a whole number you |
| 1867 | raise by hand. Exactly what it does: |
| 1868 | |
| 1869 | - It is stored and echoed: `GET /schemas/<collection>` (admin) and the schema |
| 1870 | listings report it, so a person can tell which shipped shape a box holds. |
| 1871 | It is absent from `GET /api/schema/<collection>`, the public structure-only |
| 1872 | view the generated forms read. A schema with no `version` reads as `1`; one |
| 1873 | that is not a whole number of at least 1 is refused when the schema loads. |
| 1874 | - **Nothing compares it.** Install decides what to do by comparing content |
| 1875 | hashes of the shipped file, the live file and the last installed copy, so an |
| 1876 | edit you forgot to bump still installs (the number is part of the content, |
| 1877 | so a bump alone installs too, as an update). It runs no migration, rewrites |
| 1878 | no record, and does not touch a cache (the schema cache follows the file |
| 1879 | itself). |
| 1880 | - On an upgrade of a customised schema (`merged`, above), fields are merged |
| 1881 | and everything else, the number included, is taken from the shipped file. |
| 1882 | - It is not the schema history. `PUT /schemas/<collection>` records a numbered |
| 1883 | version of its own under `data/schema_versions/` (that is what |
| 1884 | `?versions=true` lists and what rollback restores); a package install does |
| 1885 | not write to it, and the two numbers are unrelated. A package install is |
| 1886 | undone by its restore point. |
| 1887 | |
| 1888 | So: raise it when you change a schema's shape, as a note to the next reader; |
| 1889 | the engine does not need it. **A test must not pin the number to prove a |
| 1890 | change.** Assert the fields, the rules and the views the test is about, or |
| 1891 | `schema[""version""] >= N` when the history is the point. Two package tests |
| 1892 | (`tests/test_app_contacts_package.py`, `tests/test_app_tasks_package.py`) |
| 1893 | pinned the exact number, so every schema edit meant editing a test for no |
| 1894 | reason; every `tests/test_app_*_package.py` now says `>=`. If a test of |
| 1895 | yours fails only on the number after you bumped it, the test is what is wrong. |
| 1896 | |
| 1897 | **A failing pin on a pure addition is a test bug.** Adding a field to a |
| 1898 | form, a column to `list_fields`, a value to an enum, a dependency, a second |
| 1899 | permission file, a schema or a seed to a package, or bumping a version, must |
| 1900 | not turn a test red. The `tests/test_app_*_package.py` files used to say |
| 1901 | `forms.default.fields == [...]`, `dependencies == [{""id"": ""app-projects""}]` |
| 1902 | and `package[""version""] == ""0.6.0""`, so each of those additions broke a test |
| 1903 | that only meant to say ""these are still here"". They now assert what matters: |
| 1904 | `tests/package_pins.py` has `assert_includes_in_order(actual, expected)` (every |
| 1905 | expected member present, in the order named, extras allowed) and |
| 1906 | `version_at_least`, and sets are compared with `>=`. If your addition fails an |
| 1907 | exact-equality pin on a list, a set of collections or a version, relax the |
| 1908 | pin the same way; do not add your value to the expected list. **Keep exact |
| 1909 | equality for what must not change**: a permission rule, a `transitions` |
| 1910 | target set, a hidden field, a money amount. Those are behaviour and |
| 1911 | security, and an addition that touches them should fail until a person |
| 1912 | decides it is intended. |
| 1913 | |
| 1914 | ### Which version to bump |
| 1915 | |
| 1916 | The `version` in `dbbasic-package.json` is a different thing from a schema's: |
| 1917 | the package's release, recorded in its install baseline and in the install |
| 1918 | changelog. Bump it on any content change. Neither number is compared by the |
| 1919 | installer (content hashes decide what changes), so these are conventions the |
| 1920 | next reader relies on: |
| 1921 | |
| 1922 | | You changed | Package `version` | Schema `version` | |
| 1923 | |---|---|---| |
| 1924 | | a field added to `deals.json` (the recipe above) | `0.1.0` to `0.2.0` | `1` to `2` | |
| 1925 | | only an object's code, a seeded row or a rule's `reason` | `0.2.0` to `0.2.1` | unchanged | |
| 1926 | | only a permission rule or a view's blocks | `0.2.1` to `0.3.0` if behaviour changed for someone, else `0.2.2` | unchanged | |
| 1927 | | a field renamed or removed, a rule tightened over rows that already exist | `0.3.0` to `0.4.0` (or `1.0.0` once you have promised stability), and say in `description` what an operator must do | `2` to `3` | |
| 1928 | |
| 1929 | Patch for a fix nobody has to react to, minor for something added or changed |
| 1930 | that people can see, and the description for anything an operator must act on. |
| 1931 | Then reinstall with `allow_replace` (an install of a package that already has |
| 1932 | objects or schemas on disk is refused without it). |
| 1933 | |
| 1934 | ## Upgrading A Package: Data, Backfill, And An Upgrade Test |
| 1935 | |
| 1936 | An upgrade is a reinstall of a higher version over the box's live data |
| 1937 | (`allow_replace`). What it does to each layer: |
| 1938 | |
| 1939 | | Layer | On upgrade | |
| 1940 | |---|---| |
| 1941 | | records | **untouched.** Data lives outside the package, keyed by collection | |
| 1942 | | the schema | replaced, or merged with the operator's local additions ([what `version` does](#what-a-schemas-version-does)) | |
| 1943 | | a newly added field | old rows read **empty** for it. **There is no data backfill on upgrade:** `migrations` is parsed and refused (a package that lists one does not install), so nothing rewrites old rows for you | |
| 1944 | | a `default` | fills **new writes** only, never an existing row | |
| 1945 | | seed rows | merged by id; a live row an operator changed is kept | |
| 1946 | |
| 1947 | The recommended pattern, since nothing migrates for you: |
| 1948 | |
| 1949 | 1. **Make changes additive.** Add a field; do not rename, retype or remove one |
| 1950 | (a rename is a new field plus a backfill, with the old one left in place). |
| 1951 | 2. **Write every reader to cope with empty.** A page, a check or a handler that |
| 1952 | reads the new field treats blank as ""the default"" (`row.get(""priority"") or |
| 1953 | ""normal""`); a `where` filter on the new field simply does not match old rows |
| 1954 | (`?priority=normal` omits them), so a filter that must include old rows |
| 1955 | waits for the backfill. |
| 1956 | 3. **Backfill as a separate, repeatable step**, not inside the install: an |
| 1957 | admin loop of `PUT /collections/<c>/records/<id>` with the new value for |
| 1958 | each row that lacks one (it is idempotent: a second run finds nothing to |
| 1959 | do), or a one-off script using `object_records.update_collection_record`. |
| 1960 | 4. **Only then tighten:** make the field `required`, add `required_when`, |
| 1961 | `unique` or a lock. A rule added on a field that old rows lack refuses |
| 1962 | those rows' next write until they conform ([what happens to rows already |
| 1963 | there](#add-a-field-and-show-it-in-a-list-page)). |
| 1964 | |
| 1965 | **Test the upgrade before you ship it.** Install the old version, write data |
| 1966 | as a real person, change the package's files to the new version, install it |
| 1967 | over the same data with `Sandbox.reinstall` and read the old data back. Save as |
| 1968 | a pytest file in your checkout and run it from the repository root; the data |
| 1969 | directory is a throwaway, nothing is left running. (`tests/test_package_recipes.py` |
| 1970 | runs this exact block.) |
| 1971 | |
| 1972 | <!-- recipe: upgrade-test --> |
| 1973 | ```python |
| 1974 | import json |
| 1975 | import shutil |
| 1976 | |
| 1977 | from scripts import new_package |
| 1978 | from scripts.try_package import Sandbox |
| 1979 | |
| 1980 | |
| 1981 | def test_the_upgrade_keeps_old_rows_and_gives_new_rows_the_default(tmp_path): |
| 1982 | root = tmp_path / ""packages"" |
| 1983 | for name in (""app-nav"", ""app-views""): |
| 1984 | shutil.copytree(f""packages/{name}"", root / name) |
| 1985 | new_package.create_package(""app-tickets"", packages_dir=root) # version 1 |
| 1986 | records = ""/collections/tickets/records"" |
| 1987 | with Sandbox([""app-tickets""], packages_dir=root) as box: |
| 1988 | box.add_user(""ann"") |
| 1989 | status, body = box.call(""ann"", ""POST"", records, {""title"": ""old"", ""owner_id"": ""ann""}) |
| 1990 | assert status == 201 |
| 1991 | old_id = body[""record""][""id""] |
| 1992 | |
| 1993 | schema_path = root / ""app-tickets"" / ""schemas"" / ""tickets.json"" # ship version 2 |
| 1994 | schema = json.loads(schema_path.read_text()) |
| 1995 | schema[""fields""].append({""name"": ""priority"", ""type"": ""enum"", ""default"": ""normal"", |
| 1996 | ""enum"": [""low"", ""normal"", ""high""]}) |
| 1997 | schema[""version""] = 2 |
| 1998 | schema_path.write_text(json.dumps(schema)) |
| 1999 | box.reinstall(""app-tickets"") |
| 2000 | |
| 2001 | old = box.call(""ann"", ""GET"", f""{records}/{old_id}"")[1][""record""] |
| 2002 | assert old[""title""] == ""old"" # the row survived |
| 2003 | assert not old.get(""priority"") # and was not backfilled |
| 2004 | status, body = box.call(""ann"", ""POST"", records, {""title"": ""new"", ""owner_id"": ""ann""}) |
| 2005 | assert body[""record""][""priority""] == ""normal"" # new writes get the default |
| 2006 | assert box.call(""ann"", ""GET"", records)[1][""total""] == 2 |
| 2007 | ``` |
| 2008 | |
| 2009 | Customisations an operator made (extra fields, edited objects, rules) survive |
| 2010 | an upgrade by the three-way rules in |
| 2011 | [upgrade-and-customization.md](/docs/upgrade-and-customization); test those with |
| 2012 | the same pattern, making the change between the two installs. |
| 2013 | |
| 2014 | ## Try Your Change |
| 2015 | |
| 2016 | A rule or a schema is only half checked by reading it; the other half is what |
| 2017 | the API answers a person with that role, with permission enforcement on. |
| 2018 | `scripts/try_package.py` does that in one command: it installs packages into |
| 2019 | a throwaway data directory, creates users with the roles you name and an API |
| 2020 | key for each, and sends the requests you list, as those users, through the |
| 2021 | real application. Standard library only, no network, no port opened, nothing |
| 2022 | left running; the scratch directory is removed when it finishes |
| 2023 | (`--data-dir DIR` keeps the data instead). |
| 2024 | |
| 2025 | ```sh |
| 2026 | python scripts/try_package.py deals \ |
| 2027 | --user ann --user bob --user carol:auditor \ |
| 2028 | --call 'ann POST /collections/deals/records {""title"": ""Ann one"", ""owner_id"": ""ann""}' \ |
| 2029 | --call 'ann PUT /collections/deals/records/$last_id {""title"": ""Ann 1""}' \ |
| 2030 | --call 'bob GET /collections/deals/records' \ |
| 2031 | --call 'carol GET /collections/deals/records' \ |
| 2032 | --call 'anon GET /collections/deals/records' |
| 2033 | ``` |
| 2034 | |
| 2035 | - A package name that lists `dependencies` found beside it installs those |
| 2036 | first (`app-nav`, `app-views`, ...). Other packages directories: |
| 2037 | `--packages-dir`. To see what your change did, run the same calls against the |
| 2038 | unchanged package: `git worktree add ../before HEAD` gives you the old |
| 2039 | tree, `--packages-dir ../before/packages` runs the old version while the |
| 2040 | plain command runs your edited one, and a diff of the two outputs (add |
| 2041 | `--brief`) is the behaviour change. The packages beside the one you name |
| 2042 | (its dependencies) come from the same directory. |
| 2043 | - `--user NAME[:ROLE,ROLE]` makes a user. A role is just a name; a rule's |
| 2044 | `""principal"": ""role:auditor""` matches users whose roles include `auditor`. |
| 2045 | Roles live on the user record (`data/identity/users.tsv`): set them when the |
| 2046 | user is created, as here, with `POST /identity/users` (`""roles"": [...]`), |
| 2047 | with `object_identity_cli.py create-user --roles a,b`, or in Python with |
| 2048 | `object_identity.create_user({""user_id"": ""carol"", ""roles"": [""auditor""]})`. |
| 2049 | The deployment policy's `user_roles` map (`{""carol"": [""auditor""]}`, written |
| 2050 | with `PUT /permissions/policy`) assigns roles too, and the two add together. |
| 2051 | `admin` and `superuser` are the admin roles, and the admin token bypasses |
| 2052 | every rule. |
| 2053 | - A call is `USER METHOD PATH [JSON]`; USER is a `--user` name, `admin` (the |
| 2054 | admin token) or `anon` (no credentials). Each answer prints as its status and |
| 2055 | JSON. `$last_id` in a path is the id of the record the previous call returned. |
| 2056 | - **`--brief`** prints one line per call instead of the JSON: |
| 2057 | `ann POST /collections/deals/records -> 400 Record field 'title' is required`, |
| 2058 | the status, then the error (and its `code`, when it has one). Use it for a |
| 2059 | run of many calls; leave it off to read one full answer. |
| 2060 | - **`--rows 'USER ROUTE'`** shows what a seeded page's list blocks would put on |
| 2061 | screen for that person: for each `list` block, the rows the person may read |
| 2062 | and the title and subtitle each row would carry (`title_field`, |
| 2063 | `subtitle_field`, `subtitle_label`, else the first non-empty of `title`, |
| 2064 | `name`, `label`, `subject`, `body`, `text`, `content`, `message`, |
| 2065 | `description`, `email`, then the id). Pages are drawn in the browser by |
| 2066 | JavaScript, which this does not run, so the script computes the labels with a |
| 2067 | Python copy of the list renderer's rules (a test fails if the two default |
| 2068 | orders drift apart). It checks the data and the labels, not the layout: a |
| 2069 | `table` collection prints its `list_fields` columns instead (a table ignores |
| 2070 | `title_field` and `subtitle_field`), board, tree and calendar modes are not |
| 2071 | previewed, and the search box is not reproduced. For anything visual, open |
| 2072 | the page in a browser. Example: |
| 2073 | `--rows 'ann /notes'` after `--call 'ann POST /collections/notes/records {""content"": ""hi"", ""owner_id"": ""ann""}'`. |
| 2074 | - **Pages need `DBBASIC_ENABLE_SITE_ROUTES=true`.** A seeded view is served |
| 2075 | through a `site_routes` row, and routes are off by default, so without the |
| 2076 | variable `ann GET /notes` is `404 Not found`. Run |
| 2077 | `DBBASIC_ENABLE_SITE_ROUTES=true python scripts/try_package.py ...` (and |
| 2078 | start a real server with it set) to get the page. What comes back is the page |
| 2079 | shell, not the rows, which the browser fetches afterwards; `--rows` does not |
| 2080 | need the variable, because it reads the `views` records directly. |
| 2081 | - **`owner_id` on a create is yours unless your role says otherwise.** Leave |
| 2082 | it out (or send your own id) and the server fills in the caller before the |
| 2083 | rules are asked, so an own-rows rule (`{""owner_id"": ""$user_id""}`) allows it. |
| 2084 | Someone else's id is refused with `403`, `""field"": ""owner_id""`, and is never |
| 2085 | rewritten: only an admin role or a rule with `""on_behalf"": true` (staff |
| 2086 | entering records for others) may create a row another user owns |
| 2087 | (docs/permissions-model.md, ""Who owns a record you create""). The server fills |
| 2088 | in only `owner_id`; any other field a rule filters on must be sent, and a |
| 2089 | create without it is answered `403 {""error"": ""no matching role rule""}`, |
| 2090 | which reads as ""no permission"" and is really ""your record does not match |
| 2091 | your own grant"". |
| 2092 | - Enforcement is on; `--no-enforce` turns it off, and then only the admin token |
| 2093 | gets in. Event handlers, schedules and the attention rollup are daemon work and |
| 2094 | do not run here (they are off on a stock install too). |
| 2095 | |
| 2096 | From Python, for a test of your own (this is what |
| 2097 | `tests/test_try_package.py` does): |
| 2098 | |
| 2099 | ```python |
| 2100 | from scripts.try_package import Sandbox |
| 2101 | |
| 2102 | with Sandbox([""deals""]) as box: |
| 2103 | box.add_user(""ann"") |
| 2104 | box.add_user(""carol"", roles=[""auditor""]) |
| 2105 | status, body = box.call(""ann"", ""POST"", ""/collections/deals/records"", |
| 2106 | {""title"": ""Ann one"", ""owner_id"": ""ann""}) |
| 2107 | status, body = box.call(""carol"", ""GET"", ""/collections/deals/records"") |
| 2108 | ``` |
| 2109 | |
| 2110 | Putting your package under `packages/` also lets the DRON test check it |
| 2111 | (`python -m pytest tests/test_dron_schema.py -k deals`), which finds a |
| 2112 | misspelt key before an install does (the installer refuses one too). |
| 2113 | |
| 2114 | ## What A Record Looks Like On The Wire |
| 2115 | |
| 2116 | Records are stored in TSV files, so **every value a record API returns is a |
| 2117 | string**. This is the storage representation, not a bug in one endpoint, and it is |
| 2118 | what every record surface returns today: |
| 2119 | |
| 2120 | ```text |
| 2121 | POST {""title"": ""x"", ""amount_cents"": 500, ""is_public"": true} |
| 2122 | -> {""record"": {""title"": ""x"", ""amount_cents"": ""500"", ""is_public"": ""true"", ...}} |
| 2123 | ``` |
| 2124 | |
| 2125 | - **Integers and numbers** come back as `""500""`, `""5.5""`; **booleans** as |
| 2126 | exactly `""true""` or `""false""`. A field never written is absent from a |
| 2127 | single record and an empty string `""""` in a list: treat both as empty. |
| 2128 | Dates and datetimes are ISO strings. |
| 2129 | - **What you may send** is looser than what you get back: a JSON number |
| 2130 | or a numeric string for an `integer` field (`500` or `""500""`; `""5.5""` is |
| 2131 | refused `400 ... must be an integer`), and for a `boolean` a JSON boolean or |
| 2132 | `""true""`, `""yes""` or `1`, which are all stored as `""true""`. |
| 2133 | - **Filters and the counts that use them** compare the stored text: |
| 2134 | `?amount_cents=500` and `{""status"": ""open""}` match exactly. Ordered |
| 2135 | filters (`?amount_cents.gte=100`) parse the cell by the field's type. Never |
| 2136 | compare `""10""` and `""9""` as strings in a client; convert first. |
| 2137 | - **Clients convert using the schema.** `GET /api/schema/<collection>` lists |
| 2138 | every field with its `type` (`integer`, `number`, `boolean`, `date`, |
| 2139 | `datetime`, `enum`, `text`, ...). A generic client reads it once and |
| 2140 | converts: `parseInt` for `integer` (money is integer cents; do not use |
| 2141 | floats), `value === ""true""` for `boolean`, `new Date` for dates. The shipped |
| 2142 | list and form pages read the same endpoint for their cell formatting. |
| 2143 | - Responses carry a few real numbers beside the records (`total`, `count`, |
| 2144 | `limit`, `offset`); those are JSON numbers. |
| 2145 | |
| 2146 | `tests/test_package_recipes.py` checks each claim above against the `deals` |
| 2147 | package and `app-notes`. |
| 2148 | |
| 2149 | ## Recipes |
| 2150 | |
| 2151 | Four things people ask for first, each as a small change to one package, |
| 2152 | `deals`, with what to expect. Create the three files, then run any recipe's |
| 2153 | commands with `scripts/try_package.py` above. (`tests/test_package_recipes.py` |
| 2154 | builds the package from these exact blocks and checks every result stated here, |
| 2155 | so they stay true.) The first three blocks are whole files. Every later block |
| 2156 | is **a fragment, and the sentence above it says which file it goes in and |
| 2157 | where**: ""append to `rules`"" means add the object to that array, and ""add these |
| 2158 | keys"" means merge them into the file's top-level object beside the keys that |
| 2159 | are already there (a key you add that exists, such as `dependencies` or |
| 2160 | `objects`, replaces it). The blocks are valid JSON on their own and are not |
| 2161 | meant to be saved as a file. (Or start from the [scaffold](#start-from-a-scaffold), |
| 2162 | which writes the same shape under your own names.) |
| 2163 | |
| 2164 | `packages/deals/dbbasic-package.json`: |
| 2165 | |
| 2166 | <!-- recipe: deals-manifest --> |
| 2167 | ```json |
| 2168 | { |
| 2169 | ""id"": ""deals"", |
| 2170 | ""name"": ""Deals"", |
| 2171 | ""version"": ""0.1.0"", |
| 2172 | ""description"": ""Deals, each owned by one person"", |
| 2173 | ""compatibility"": {""dbbasic_object_server"": "">=0.1.0""}, |
| 2174 | ""dependencies"": [], |
| 2175 | ""objects"": [], |
| 2176 | ""schemas"": [{""collection"": ""deals"", ""path"": ""schemas/deals.json""}], |
| 2177 | ""permissions"": [{""path"": ""permissions/rules.json""}], |
| 2178 | ""seed"": [], |
| 2179 | ""migrations"": [] |
| 2180 | } |
| 2181 | ``` |
| 2182 | |
| 2183 | `packages/deals/schemas/deals.json`: |
| 2184 | |
| 2185 | <!-- recipe: deals-schema --> |
| 2186 | ```json |
| 2187 | { |
| 2188 | ""name"": ""deals"", |
| 2189 | ""title"": ""Deals"", |
| 2190 | ""version"": 1, |
| 2191 | ""fields"": [ |
| 2192 | {""name"": ""id""}, |
| 2193 | {""name"": ""title"", ""type"": ""text"", ""required"": true}, |
| 2194 | {""name"": ""description"", ""type"": ""textarea""}, |
| 2195 | {""name"": ""status"", ""type"": ""enum"", ""enum"": [""open"", ""won"", ""lost""], |
| 2196 | ""default"": ""open"", ""transitions"": {""open"": [""won"", ""lost""]}}, |
| 2197 | {""name"": ""amount_cents"", ""type"": ""integer""}, |
| 2198 | {""name"": ""assigned_to"", ""type"": ""text""}, |
| 2199 | {""name"": ""owner_id"", ""type"": ""text""} |
| 2200 | ], |
| 2201 | ""forms"": {""default"": {""fields"": [""title"", ""description"", ""status"", ""amount_cents"", ""assigned_to""]}}, |
| 2202 | ""views"": {""list_mode"": ""table"", ""list_fields"": [""title"", ""status"", ""amount_cents""]}, |
| 2203 | ""search"": {""fields"": [""title"", ""description""]} |
| 2204 | } |
| 2205 | ``` |
| 2206 | |
| 2207 | `packages/deals/permissions/rules.json`: |
| 2208 | |
| 2209 | <!-- recipe: deals-rules --> |
| 2210 | ```json |
| 2211 | { |
| 2212 | ""rules"": [ |
| 2213 | {""effect"": ""allow"", ""principal"": ""registered"", |
| 2214 | ""actions"": [""create"", ""read"", ""update"", ""delete""], |
| 2215 | ""collection"": ""deals"", ""row_filter"": {""owner_id"": ""$user_id""}, |
| 2216 | ""reason"": ""people manage their own deals""} |
| 2217 | ] |
| 2218 | } |
| 2219 | ``` |
| 2220 | |
| 2221 | As it stands, `ann` sees and changes her own deals, and nobody else's. |
| 2222 | |
| 2223 | ### A role reads every row while only owners write |
| 2224 | |
| 2225 | **Append this object to the `rules` array** in `permissions/rules.json`: the |
| 2226 | role's grant has **no `row_filter`**, and a grant with no filter is every row. |
| 2227 | |
| 2228 | <!-- recipe: deals-auditor-rule --> |
| 2229 | ```json |
| 2230 | {""effect"": ""allow"", ""principal"": ""role:auditor"", ""actions"": [""read""], |
| 2231 | ""collection"": ""deals"", |
| 2232 | ""reason"": ""auditors read every deal and change none""} |
| 2233 | ``` |
| 2234 | |
| 2235 | Rules add up: a request is allowed when any allow rule matches, and each rule |
| 2236 | brings its own row filter. So an auditor reads every row through this rule and, |
| 2237 | being signed in, still owns whatever she creates through the first. With |
| 2238 | `ann` (two deals), `bob` (one) and `carol` (role `auditor`): |
| 2239 | |
| 2240 | | Request | Answer | |
| 2241 | |---|---| |
| 2242 | | `ann GET /collections/deals/records` | `200`, `total: 2`, her rows | |
| 2243 | | `bob GET /collections/deals/records` | `200`, `total: 1`, his row | |
| 2244 | | `carol GET /collections/deals/records` | `200`, `total: 3`, everyone's | |
| 2245 | | `carol GET ...records?limit=2&offset=2` | `200`, `count: 1`, `total: 3`, `has_more: false` | |
| 2246 | | `carol GET ...records?owner_id=ann` | `200`, `total: 2`: filters apply after the grant | |
| 2247 | | `carol GET /api/search?q=Ann&collections=deals` | `200`, Ann's deals | |
| 2248 | | `carol PUT` or `DELETE` on Ann's deal | `403 no matching role rule` | |
| 2249 | | `bob PUT` on Ann's deal | `403 no matching role rule` | |
| 2250 | | `ann POST` with `owner_id: ""ann""`, or without it | `201`, owned by `ann`; with `""bob""`: `403` | |
| 2251 | |
| 2252 | Listing, paging and filtering are all done after the permission filter, so |
| 2253 | `total` is the number of rows the caller may read. |
| 2254 | |
| 2255 | ### A count over rows I own **or** am assigned |
| 2256 | |
| 2257 | `where` is a row filter: its entries are ANDed, and **there is no OR and no |
| 2258 | NOT** (adding either is a design decision that has not been taken). Write two |
| 2259 | entries, one per condition, in the manifest. A queue declared with `collection` |
| 2260 | and `where` is counted **for the viewer, over the rows the viewer may read**, so |
| 2261 | the second queue also needs a read grant on the assigned rows, or the assignee |
| 2262 | sees 0, and a zero is never shown. |
| 2263 | |
| 2264 | <!-- recipe: deals-attention --> |
| 2265 | ```json |
| 2266 | { |
| 2267 | ""dependencies"": [""app-nav""], |
| 2268 | ""attention"": [ |
| 2269 | {""id"": ""deals_i_own"", ""collection"": ""deals"", |
| 2270 | ""where"": {""status"": ""open"", ""owner_id"": ""$user_id""}, |
| 2271 | ""label"": ""Open deals I own"", ""path"": ""/deals"", ""group"": ""Work""}, |
| 2272 | {""id"": ""deals_assigned_to_me"", ""collection"": ""deals"", |
| 2273 | ""where"": {""status"": ""open"", ""assigned_to"": ""$user_id"", |
| 2274 | ""owner_id"": {""op"": ""ne"", ""value"": ""$user_id""}}, |
| 2275 | ""label"": ""Open deals assigned to me"", ""path"": ""/deals"", ""group"": ""Work""} |
| 2276 | ] |
| 2277 | } |
| 2278 | ``` |
| 2279 | |
| 2280 | (**Merge both keys into the top level of `dbbasic-package.json`**, replacing |
| 2281 | its empty `""dependencies"": []`. `app-nav` must be installed: it owns the |
| 2282 | registry the entries are written to, and without it they are skipped with a |
| 2283 | note. See [the `app-nav` rule](#depend-on-app-nav).) |
| 2284 | |
| 2285 | The second queue excludes rows the viewer owns (`""owner_id"": {""op"": ""ne"", |
| 2286 | ""value"": ""$user_id""}`), so a deal that is both owned by and assigned to the |
| 2287 | same person is counted **once**, in ""I own"". Without that condition it would |
| 2288 | count in both queues and the badge would double-count it. (`ne` matches a deal |
| 2289 | with no owner at all, and the queue still needs one literal condition, here |
| 2290 | `status`.) And **append this object to the `rules` array** in |
| 2291 | `permissions/rules.json`: |
| 2292 | |
| 2293 | <!-- recipe: deals-assignee-rule --> |
| 2294 | ```json |
| 2295 | {""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""], |
| 2296 | ""collection"": ""deals"", ""row_filter"": {""assigned_to"": ""$user_id""}, |
| 2297 | ""reason"": ""assignees read the deals assigned to them""} |
| 2298 | ``` |
| 2299 | |
| 2300 | Read the result the way the menu does: `GET /objects/action_nav_entries`, |
| 2301 | as each person, and look at `attention`. With Ann owning two open deals that |
| 2302 | are assigned to Bob, and Bob owning one: |
| 2303 | |
| 2304 | | Viewer | `attention` | |
| 2305 | |---|---| |
| 2306 | | `ann` | `deals_i_own` count `2` | |
| 2307 | | `bob` | `deals_assigned_to_me` count `2`, `deals_i_own` count `1` | |
| 2308 | | `carol` (auditor, owns none) | nothing: both queues are 0 | |
| 2309 | |
| 2310 | The two queues do not overlap, so the union ""owned or assigned"" is their sum |
| 2311 | with nothing counted twice (a deal Bob both owns and is assigned counts once, |
| 2312 | under ""I own""). Reach for a provider object (`COUNT`), below, only when the |
| 2313 | rule is more than conditions can say. |
| 2314 | |
| 2315 | To put the number on the app list too, give the package a door: **merge this |
| 2316 | `nav` key into the top level of `dbbasic-package.json`**, and add |
| 2317 | `""nav_id"": ""deals""` to each of the two `attention` entries above: |
| 2318 | |
| 2319 | <!-- recipe: deals-nav --> |
| 2320 | ```json |
| 2321 | {""nav"": [{""id"": ""deals"", ""label"": ""Deals"", ""path"": ""/deals"", ""group"": ""Work""}]} |
| 2322 | ``` |
| 2323 | |
| 2324 | `GET /objects/action_nav_entries` then returns the Deals entry with `count` `2` |
| 2325 | for `ann` and `3` for `bob` (2 assigned + 1 owned): **the badge is the sum of |
| 2326 | every queue that names the door**, while `attention` keeps the two rows apart. |
| 2327 | |
| 2328 | ### Freeze some fields once a record is settled |
| 2329 | |
| 2330 | `locked_when` freezes a record while its **stored** state matches `when`. Two |
| 2331 | ways to say which fields stay free, and a rule uses one of them: |
| 2332 | |
| 2333 | - `""except"": [...]` freezes everything **except** the listed fields. Fields you |
| 2334 | add to the schema later are frozen too, which is the safe direction for money |
| 2335 | and the surprising one for a note field nobody thought about. |
| 2336 | - `""fields"": [...]` freezes **only** the listed fields; every other field, |
| 2337 | including ones added later, stays editable. Use it when most of the record |
| 2338 | is allowed to keep changing. The names must be declared fields (not `id`), |
| 2339 | and a rule with both `except` and `fields` is refused at schema load. |
| 2340 | |
| 2341 | <!-- recipe: deals-locked-when --> |
| 2342 | ```json |
| 2343 | { |
| 2344 | ""locked_when"": [ |
| 2345 | {""when"": {""status"": [""won"", ""lost""]}, |
| 2346 | ""fields"": [""title"", ""description"", ""amount_cents""], |
| 2347 | ""message"": ""A settled deal's title, description and amount are frozen.""} |
| 2348 | ] |
| 2349 | } |
| 2350 | ``` |
| 2351 | |
| 2352 | (**Merge that key into the top level of `schemas/deals.json`**, beside |
| 2353 | `fields` and `forms`.) With a `won` deal: |
| 2354 | |
| 2355 | | Request | Answer | |
| 2356 | |---|---| |
| 2357 | | `PUT` `{""assigned_to"": ""carol""}` | `200`: not a frozen field | |
| 2358 | | `PUT` `{""title"": ""late""}` | `409 {""code"": ""record_locked"", ""fields"": [""title""], ""error"": ""A settled deal's ...""}` | |
| 2359 | | `PUT` `{""title"": ""<its current title>""}` | `200`: sending a frozen field back unchanged is not a change | |
| 2360 | | `DELETE` | `409 record_locked`, `fields: []` (`allow_delete` defaults to `false`) | |
| 2361 | | the admin token does the same `PUT` | `409`: nobody is exempt | |
| 2362 | | `PUT` `{""status"": ""open""}` | `400 ... cannot move from 'won' to 'open' (allowed: none)` | |
| 2363 | |
| 2364 | The last row is not the lock: it is the `transitions` map. **`done`, `won`, |
| 2365 | `closed` mean nothing to the platform.** A status is terminal only because it |
| 2366 | has no entry in `transitions` (values missing from the map are terminal); a |
| 2367 | status you can leave is a status you listed moves for. The `fields` form does |
| 2368 | not name `status`, so the transitions alone decide where a settled deal may |
| 2369 | go. In the `except` form you would list `status` to let the lock be left, and |
| 2370 | leave it out to make the state final. Details: ""Locked when settled"" in |
| 2371 | [`validation-and-logic.md`](/docs/validation-and-logic). |
| 2372 | |
| 2373 | ### Add a field and show it in a list page |
| 2374 | |
| 2375 | Five places know about a field; the list page needs the first and one of the |
| 2376 | next two: |
| 2377 | |
| 2378 | 1. `fields`: `{""name"": ""priority"", ""type"": ""enum"", ""enum"": [""low"", ""normal"", |
| 2379 | ""high""], ""default"": ""normal"", ""label"": ""Priority""}`. The record API accepts, |
| 2380 | validates and returns it from here. Rules a field can carry, each in |
| 2381 | [`validation-and-logic.md`](/docs/validation-and-logic): `required`, `enum`, |
| 2382 | `validation.min_length` / `max_length` / `pattern`, `validation.min` / |
| 2383 | `max` and `exclusive_min` / `exclusive_max` ([strict bounds](/docs/validation-and-logic#strict-bounds-and-conditional-required-fields)), |
| 2384 | `validation.required_when` (non-blank only while the record is in a given |
| 2385 | state, same section), and a root-level `unique` key |
| 2386 | ([uniqueness](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock)). |
| 2387 | 2. `forms.default.fields`: add `""priority""`. When a schema lists form fields, |
| 2388 | a field not listed is not on the form. |
| 2389 | 3. `views.list_fields`: add `""priority""`. This is what the **table** list |
| 2390 | shows as columns and what the **board** shows on each card. The list page |
| 2391 | itself is a seeded view record over the schema's `views.list_mode` (see |
| 2392 | [Seeded views and site routes](#seeded-views-and-site-routes)); the plain |
| 2393 | row list (`list_mode` absent, `cards` or `feed`) and the tree and calendar |
| 2394 | modes do not show `list_fields` at all, only a title and a date. To put a |
| 2395 | field on a row list, name it as the list block's `subtitle_field`. A row |
| 2396 | with no value for that field draws no subtitle line (never a bare |
| 2397 | ""Pinned:""), and a field the schema types `boolean` reads Yes/No instead of |
| 2398 | `true`/`false` (the list generator fetches the schema for this; with |
| 2399 | `list_modes_enabled` turned off it does not, and values show as stored). |
| 2400 | 4. `views.detail_fields`, if the schema declares one, for the detail page; |
| 2401 | `search.fields` to make it searchable text; `views.filter_fields` for a |
| 2402 | filter select (enums and booleans). |
| 2403 | 5. Bump `version`, and reinstall with `allow_replace` |
| 2404 | (`POST /packages/deals/install` with `{""allow_replace"": true}`, or |
| 2405 | `install_package(..., allow_replace=True)` in Python): the schema comes back |
| 2406 | `updated`. |
| 2407 | |
| 2408 | What to expect afterwards: `GET /api/schema/deals` lists `priority` under |
| 2409 | `fields` and in `views.list_fields`; a deal created from now on without a |
| 2410 | priority reads `normal`; **a deal written before the change has no value** (a |
| 2411 | `default` fills new writes, not old rows), so `?priority=normal` does not list |
| 2412 | it. Backfill old rows with an update if the page should show a value for them. |
| 2413 | A value outside the enum is refused `400 Record field 'priority' must be one of: low, normal, high`. |
| 2414 | |
| 2415 | **Required fields must be in every create.** A field with `""required"": true` |
| 2416 | makes a create without it a `400`, and the generated form is not the only |
| 2417 | caller: your `try_package.py --call` is too. On a real package: |
| 2418 | |
| 2419 | ```sh |
| 2420 | python scripts/try_package.py app-contacts --user ann --brief \ |
| 2421 | --call 'ann POST /collections/contacts/records {""last_name"": ""Lee"", ""owner_id"": ""ann""}' \ |
| 2422 | --call 'ann POST /collections/contacts/records {""first_name"": ""Ada"", ""owner_id"": ""ann""}' |
| 2423 | # ann POST /collections/contacts/records -> 400 Record field 'first_name' is required |
| 2424 | # ann POST /collections/contacts/records -> 201 |
| 2425 | ``` |
| 2426 | |
| 2427 | A field you make `required` later therefore breaks every caller that does not |
| 2428 | send it yet; add it as optional, backfill, then require it. |
| 2429 | |
| 2430 | **What happens to rows that are already there when you add a rule.** None |
| 2431 | is rewritten, and none is removed: |
| 2432 | |
| 2433 | - `unique` **compares exactly as stored, case included**: `""Acme""` and |
| 2434 | `""acme""` are two keys unless the constraint says `""ignore_case"": true` |
| 2435 | (which folds the key fields, not `scope`). Values are **trimmed** first, so |
| 2436 | `""Acme""` and `""Acme ""` are one key: trimming is leading and trailing |
| 2437 | whitespace only (Python `str.strip`), not whitespace inside the value. |
| 2438 | A blank key field means the row has no key and is exempt. Tested in |
| 2439 | `tests/test_package_recipes.py`; full rules in |
| 2440 | [validation-and-logic.md](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock). |
| 2441 | - `unique`: existing duplicates stay and stay editable; no further holder of |
| 2442 | the key is admitted. `object_records.find_unique_violations(collection, |
| 2443 | base_dir=...)` lists them; run it before you ship the declaration and merge |
| 2444 | or delete what it reports. |
| 2445 | - `required_when`, `min` / `max`: a row that already breaks the rule stays on |
| 2446 | file but is **refused on its next write**, whatever that write changes, |
| 2447 | until it conforms ([validation-and-logic.md](/docs/validation-and-logic#strict-bounds-and-conditional-required-fields)). |
| 2448 | - `locked_when`: it looks at the stored state, so a row already in a matching |
| 2449 | state is frozen from the moment the rule lands. |
| 2450 | |
| 2451 | ## What Can't Be Declared |
| 2452 | |
| 2453 | Schemas, permission rules, `where` filters and seeded views say a great deal |
| 2454 | without code. They do not say these, and a package that needs one is not |
| 2455 | doing something wrong: it needs the tool in the right-hand column. |
| 2456 | |
| 2457 | | You want | Why a declaration cannot say it | Use | |
| 2458 | |---|---|---| |
| 2459 | | ""close date must not be in the past"", ""after its date"", ""older than X"" as a rule on a write | no schema rule, `required_when`, `locked_when` or permission filter reads the clock | a **locked check** that reads the record and the clock (below) | |
| 2460 | | the same, as a **count** (""invoices over a week old"") | | an `attention` declaration with `{""op"": ""older_than_days"", ""value"": 7}` (counts only; [Declared counts](#declared-counts-collection--where)) | |
| 2461 | | a status that changes **by itself** when time passes (`open` to `overdue`) | nothing runs on a record because time passed | a scheduled object in the daemon (time-driven state belongs to the daemon, [`logic-decisions.md`](/docs/logic-decisions)); a check only decides at write time | |
| 2462 | | `OR` / `NOT` in a `where` or a `row_filter` | entries are ANDed. There is no OR and no NOT, by decision; do not ask a package to work around it | two entries (two queues, two rules: rules already add up), `ne` conditions for ""not one of these"", or a provider object | |
| 2463 | | comparing two fields (`end_on > start_on`, `taken <= capacity`) | a bound is a constant | a locked check on the record's own fields | |
| 2464 | | ""forbidden when"" (a lost deal must have **no** reason code) | `required_when` asks for non-blank, never blank | a locked check | |
| 2465 | | a rule that needs rows of **other** collections (a sum against a ceiling) | | a locked check with `reads` ([Locked checks](/docs/validation-and-logic#locked-checks--a-decision-across-collections-made-inside-the-write-lock)) | |
| 2466 | | `required_when` whose condition is in **another** collection (""a PO number when the deal's type says so"") | `required_when` reads only the record | stamp the condition onto the record with a hook, keep `required_when` on the stamp, and refuse a wrong stamp with a locked check ([below](#a-requirement-another-collection-decides)) | |
| 2467 | | a rule about **who** may do it, that no row filter can state | | a pre-write hook, which gets the caller; a check never does | |
| 2468 | |
| 2469 | ### A check that reads the record and the clock |
| 2470 | |
| 2471 | A locked check is a function the schema names and the platform calls inside |
| 2472 | the write lock, for every writer (HTTP, MCP, handlers, the daemon, imports), |
| 2473 | and a refusal writes nothing. This one refuses a deal whose `close_on` is in |
| 2474 | the past. Three files change. |
| 2475 | |
| 2476 | **1. `dbbasic-package.json`**: merge this key into the top level, replacing the |
| 2477 | empty `""objects"": []`: |
| 2478 | |
| 2479 | <!-- recipe: deals-close-date-manifest --> |
| 2480 | ```json |
| 2481 | {""objects"": [{""id"": ""hook_deals"", ""path"": ""objects/hook/deals.py""}]} |
| 2482 | ``` |
| 2483 | |
| 2484 | **2. `schemas/deals.json`**: append this field object to the `fields` array: |
| 2485 | |
| 2486 | <!-- recipe: deals-close-date-field --> |
| 2487 | ```json |
| 2488 | {""name"": ""close_on"", ""type"": ""date"", ""label"": ""Close on""} |
| 2489 | ``` |
| 2490 | |
| 2491 | and merge this key into the schema's top level (beside `fields`): |
| 2492 | |
| 2493 | <!-- recipe: deals-close-date-checks --> |
| 2494 | ```json |
| 2495 | { |
| 2496 | ""locked_checks"": [ |
| 2497 | {""name"": ""close_date"", ""object"": ""hook_deals"", ""function"": ""LOCKED_CHECK"", |
| 2498 | ""on"": {""create"": true, ""update"": [""close_on""], ""delete"": false}} |
| 2499 | ] |
| 2500 | } |
| 2501 | ``` |
| 2502 | |
| 2503 | **3. `packages/deals/objects/hook/deals.py`** (a new file): |
| 2504 | |
| 2505 | <!-- recipe: deals-close-check --> |
| 2506 | ```python |
| 2507 | from datetime import date |
| 2508 | |
| 2509 | |
| 2510 | def LOCKED_CHECK(request): |
| 2511 | close_on = (request.get(""record"") or {}).get(""close_on"", """") |
| 2512 | if close_on and close_on < date.today().isoformat(): |
| 2513 | return {""error"": ""A deal cannot close in the past."", ""status"": 409} |
| 2514 | return None |
| 2515 | ``` |
| 2516 | |
| 2517 | #### Comparing a datetime with now |
| 2518 | |
| 2519 | A `date` is a bare `YYYY-MM-DD` with no zone, compared above with the server's |
| 2520 | local date. A `datetime` field needs three decisions, and the platform's |
| 2521 | convention is **UTC**: |
| 2522 | |
| 2523 | - **What is stored is whatever the writer sent, if it parses.** The platform |
| 2524 | validates with `datetime.fromisoformat` after turning a trailing `Z` into |
| 2525 | `+00:00`, and stores the string as sent. So a stored value may be **aware** |
| 2526 | (`2026-07-27T09:39:00Z`, `...+02:00`) or **naive** (`2026-07-27T09:39:00`, no |
| 2527 | offset). The generated form sends UTC with a `Z` and **no fractional seconds** |
| 2528 | (the browser's `datetime-local` answer, read as the viewer's wall clock, is |
| 2529 | converted to UTC before it is sent); a server-filled `created_at` is UTC with |
| 2530 | microseconds and a `Z`. An API client may send any of them. |
| 2531 | - **Comparing aware with naive raises `TypeError`.** Normalise first: read a |
| 2532 | naive value as UTC (that is the platform's own rule: attention's |
| 2533 | `older_than_days` does the same), convert an aware one to UTC, and compare |
| 2534 | with `datetime.now(timezone.utc)`. |
| 2535 | - **A value you cannot parse is a check that cannot decide, so fail closed.** |
| 2536 | Do not `return None` (allow) from an `except`. Let the exception out: the |
| 2537 | platform turns any exception raised by a check into `503 |
| 2538 | check_unavailable` and writes nothing. Return `{""error"": ""..."", ""status"": |
| 2539 | 503}` yourself if you want your own message. |
| 2540 | |
| 2541 | Add a second field and a second check. Append to `fields` in |
| 2542 | `schemas/deals.json`: |
| 2543 | |
| 2544 | <!-- recipe: deals-follow-up-field --> |
| 2545 | ```json |
| 2546 | {""name"": ""follow_up_at"", ""type"": ""datetime"", ""label"": ""Follow up at""} |
| 2547 | ``` |
| 2548 | |
| 2549 | append to the `locked_checks` array you just added: |
| 2550 | |
| 2551 | <!-- recipe: deals-follow-up-check-entry --> |
| 2552 | ```json |
| 2553 | {""name"": ""follow_up"", ""object"": ""hook_deals"", ""function"": ""FOLLOW_UP_CHECK"", |
| 2554 | ""on"": {""create"": true, ""update"": [""follow_up_at""], ""delete"": false}} |
| 2555 | ``` |
| 2556 | |
| 2557 | and add this to `objects/hook/deals.py`, below `LOCKED_CHECK`: |
| 2558 | |
| 2559 | <!-- recipe: deals-follow-up-check --> |
| 2560 | ```python |
| 2561 | from datetime import datetime, timezone |
| 2562 | |
| 2563 | |
| 2564 | def as_utc(text): |
| 2565 | """"""A stored datetime as an aware UTC datetime. Raises ValueError if it is not one."""""" |
| 2566 | when = datetime.fromisoformat(text.strip().replace(""Z"", ""+00:00"")) |
| 2567 | if when.tzinfo is None: |
| 2568 | return when.replace(tzinfo=timezone.utc) # naive means UTC here |
| 2569 | return when.astimezone(timezone.utc) |
| 2570 | |
| 2571 | |
| 2572 | def FOLLOW_UP_CHECK(request): |
| 2573 | text = (request.get(""record"") or {}).get(""follow_up_at"", """") |
| 2574 | if not text: |
| 2575 | return None # the field is optional |
| 2576 | if as_utc(text) <= datetime.now(timezone.utc): # an unparseable value raises: 503 |
| 2577 | return {""error"": ""A follow-up must be in the future."", ""status"": 409} |
| 2578 | return None |
| 2579 | ``` |
| 2580 | |
| 2581 | With that, `Z`, `+02:00` and offset-less values all compare correctly, a past |
| 2582 | one is `409 check_refused`, and a value `as_utc` cannot read is `503 |
| 2583 | check_unavailable`, never a quiet allow. |
| 2584 | |
| 2585 | What to know, each verified in `object_records` and by |
| 2586 | `tests/test_package_recipes.py`: |
| 2587 | |
| 2588 | - **A check may read the current time.** It is ordinary Python, loaded |
| 2589 | without a sandbox; the only things it may not do are write or run another |
| 2590 | object. Dates are `YYYY-MM-DD` strings, which sort in date order, and the |
| 2591 | `record` it receives holds strings (see [the wire](#what-a-record-looks-like-on-the-wire)). |
| 2592 | - **`record` is the row as it will be stored** (on an update, the stored row |
| 2593 | with the changes applied); `existing` is the row on file, read under the |
| 2594 | lock (`None` on a create). Return `None` to allow, or `{""error"": ""..."", |
| 2595 | ""status"": 409}` (any 4xx) to refuse. The refusal reaches the client as `409 |
| 2596 | {""code"": ""check_refused"", ""check"": ""close_date"", ""error"": ""A deal cannot |
| 2597 | close in the past.""}`. |
| 2598 | - **It decides at write time only**, and only for writes `on` selects. Here |
| 2599 | `update: [""close_on""]` means a deal whose date has since passed can still |
| 2600 | have its title changed, and is judged again the moment its date is touched. |
| 2601 | A rule that must hold as time passes is not a write rule. |
| 2602 | - **The object does not have to live in the same package** as the schema: it |
| 2603 | is looked up by id among the installed objects. Shipping it beside the schema |
| 2604 | is the convention, and a check in another package needs that package in |
| 2605 | `dependencies`. Install does **not** check that the object exists; a check |
| 2606 | whose object is missing refuses every write it selects with `503 |
| 2607 | check_unavailable`, which is why the recipe is tried before it is shipped. |
| 2608 | - A check with `reads` (other collections) also takes a lock that every write |
| 2609 | to those collections takes; a check of the record's own fields needs none |
| 2610 | and costs one `flock` round trip. Details, failure modes and cost: |
| 2611 | [Locked checks](/docs/validation-and-logic#locked-checks--a-decision-across-collections-made-inside-the-write-lock). |
| 2612 | |
| 2613 | ### A requirement another collection decides |
| 2614 | |
| 2615 | ""A purchase order number is required when the deal's **type** says so"" is a |
| 2616 | `required_when` whose condition lives in another collection, and |
| 2617 | `required_when` reads only the record. The way through, used by app-finance's |
| 2618 | expense categories (`expense-substantiation.md`), |
| 2619 | is to **copy the condition onto the record** and let three tools each do the |
| 2620 | part only it can: |
| 2621 | |
| 2622 | 1. a pre-write hook **stamps** what the other collection says |
| 2623 | (`po_required`) on every API write, so nobody has to type it; |
| 2624 | 2. `required_when` on the stamped field makes it **binding**, declared, for |
| 2625 | every writer; |
| 2626 | 3. a locked check **refuses a stamp that disagrees** with the other |
| 2627 | collection, inside the write lock and for every writer, so a writer below |
| 2628 | the hook (an import, an action) cannot skip the rule by leaving the stamp |
| 2629 | out. |
| 2630 | |
| 2631 | The stamp is also the point-in-time record of the rule that applied |
| 2632 | ([`logic-decisions.md`](/docs/logic-decisions) #1). Six changes to the base |
| 2633 | `deals` package. |
| 2634 | |
| 2635 | **1. `packages/deals/schemas/deal_types.json`** (a new file): |
| 2636 | |
| 2637 | <!-- recipe: deals-type-schema --> |
| 2638 | ```json |
| 2639 | { |
| 2640 | ""name"": ""deal_types"", |
| 2641 | ""title"": ""Deal Types"", |
| 2642 | ""version"": 1, |
| 2643 | ""fields"": [ |
| 2644 | {""name"": ""id""}, |
| 2645 | {""name"": ""name"", ""type"": ""text"", ""required"": true}, |
| 2646 | {""name"": ""requires_po"", ""type"": ""boolean"", ""default"": ""false""} |
| 2647 | ] |
| 2648 | } |
| 2649 | ``` |
| 2650 | |
| 2651 | **2. `dbbasic-package.json`**: merge these keys into the top level (they |
| 2652 | replace `objects` and `schemas`; `deal_types` is listed first so its schema |
| 2653 | exists before a deal points at it): |
| 2654 | |
| 2655 | <!-- recipe: deals-type-manifest --> |
| 2656 | ```json |
| 2657 | { |
| 2658 | ""objects"": [{""id"": ""hook_deal_po"", ""path"": ""objects/hook/deal_po.py""}], |
| 2659 | ""schemas"": [{""collection"": ""deal_types"", ""path"": ""schemas/deal_types.json""}, |
| 2660 | {""collection"": ""deals"", ""path"": ""schemas/deals.json""}] |
| 2661 | } |
| 2662 | ``` |
| 2663 | |
| 2664 | **3. `permissions/rules.json`**: append this object to the `rules` array: |
| 2665 | |
| 2666 | <!-- recipe: deals-type-rule --> |
| 2667 | ```json |
| 2668 | {""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""], |
| 2669 | ""collection"": ""deal_types"", |
| 2670 | ""reason"": ""everybody filing a deal needs to see the types and what each requires""} |
| 2671 | ``` |
| 2672 | |
| 2673 | **4. `schemas/deals.json`**: append these three field objects to the `fields` |
| 2674 | array: |
| 2675 | |
| 2676 | <!-- recipe: deals-type-fields --> |
| 2677 | ```json |
| 2678 | [ |
| 2679 | {""name"": ""deal_type_id"", |
| 2680 | ""relation"": {""collection"": ""deal_types"", ""display_field"": ""name"", ""requires"": ""read""}}, |
| 2681 | {""name"": ""po_required"", ""type"": ""boolean""}, |
| 2682 | {""name"": ""po_number"", ""type"": ""text"", |
| 2683 | ""validation"": {""required_when"": {""po_required"": ""true"", ""status"": [""won""]}}} |
| 2684 | ] |
| 2685 | ``` |
| 2686 | |
| 2687 | **5. `schemas/deals.json`**: merge these keys into the schema's top level: |
| 2688 | |
| 2689 | <!-- recipe: deals-type-keys --> |
| 2690 | ```json |
| 2691 | { |
| 2692 | ""hooks"": {""before_write"": ""hook_deal_po""}, |
| 2693 | ""locked_checks"": [ |
| 2694 | {""name"": ""po_stamp"", ""object"": ""hook_deal_po"", ""function"": ""LOCKED_CHECK"", |
| 2695 | ""reads"": [""deal_types""], |
| 2696 | ""on"": {""create"": true, ""update"": [""deal_type_id"", ""po_required""], ""delete"": false}} |
| 2697 | ] |
| 2698 | } |
| 2699 | ``` |
| 2700 | |
| 2701 | **6. `packages/deals/objects/hook/deal_po.py`** (a new file): |
| 2702 | |
| 2703 | <!-- recipe: deals-type-hook --> |
| 2704 | ```python |
| 2705 | import os |
| 2706 | |
| 2707 | import object_records |
| 2708 | |
| 2709 | |
| 2710 | def requires_po(deal_type_id, base): |
| 2711 | """"""""true"" or ""false"", as the deal type says. Raises if the type cannot be read."""""" |
| 2712 | if not deal_type_id: |
| 2713 | return ""false"" |
| 2714 | row = object_records.get_collection_record(""deal_types"", deal_type_id, base_dir=base) |
| 2715 | return ""true"" if row.get(""requires_po"") == ""true"" else ""false"" |
| 2716 | |
| 2717 | |
| 2718 | def BEFORE_WRITE(request): |
| 2719 | if request[""action""] not in (""create"", ""update""): |
| 2720 | return None |
| 2721 | record = dict(request[""record""]) |
| 2722 | base = os.environ.get(""DBBASIC_DATA_DIR"", ""data"") |
| 2723 | record[""po_required""] = requires_po(record.get(""deal_type_id"", """"), base) |
| 2724 | return {""record"": record} |
| 2725 | |
| 2726 | |
| 2727 | def LOCKED_CHECK(request): |
| 2728 | record = request[""record""] |
| 2729 | wanted = requires_po(record.get(""deal_type_id"", """"), request[""base_dir""]) |
| 2730 | if (record.get(""po_required"") or ""false"") != wanted: |
| 2731 | return {""error"": f""po_required must be {wanted}, as the deal type says."", ""status"": 409} |
| 2732 | return None |
| 2733 | ``` |
| 2734 | |
| 2735 | With a type ""Enterprise"" (`requires_po: true`) made by an admin: |
| 2736 | |
| 2737 | | Request | Answer | |
| 2738 | |---|---| |
| 2739 | | `ann POST` a deal of that type | `201`, `po_required: ""true""` (stamped; she did not send it) | |
| 2740 | | `ann PUT` `{""status"": ""won""}` | `400 Record field 'po_number' is required when po_required is true and status is won` | |
| 2741 | | `ann PUT` `{""status"": ""won"", ""po_number"": ""PO-1""}` | `200` | |
| 2742 | | `ann POST` a deal with no type, then `PUT` won | `200`: `po_required` is `false` | |
| 2743 | | a writer below the hook creates one with `po_required: ""false""` | `CheckRefusedError` (over HTTP: `409 check_refused`), nothing written | |
| 2744 | | an admin later sets `requires_po: false` on the type | deals already written keep `po_required: ""true""` until their next write through the API restamps them | |
| 2745 | |
| 2746 | This hook restamps on every write, which is the simple choice. app-finance's |
| 2747 | expense hook restamps only when the stamp is *judged* (a new category or |
| 2748 | amount, a move into submitted or approved), so an approved expense keeps the |
| 2749 | rule it was approved under for good; `object_expense_rules.stamps_are_judged` |
| 2750 | is that decision written down. |
| 2751 | |
| 2752 | The check `reads` `deal_types`, so every write to a deal type waits on the |
| 2753 | same lock: a type changed in the middle of a deal's write cannot slip |
| 2754 | between the check and the append. A hook that cannot read the type raises, |
| 2755 | which refuses the write (fail closed); so does the check (`503`). |
| 2756 | |
| 2757 | ### An action that is the grant |
| 2758 | |
| 2759 | Some actions exist to write what their caller may not write over the record |
| 2760 | API. app-counter's are the example: a cashier records a payment, a credit |
| 2761 | note, a refund or a waste stock move whose relation declares `requires: |
| 2762 | update` on an invoice, payment or product the cashier may only read. That |
| 2763 | is deliberate (giving cashiers update on invoices would let them reprice |
| 2764 | and void bills), so these role-granted actions are exempt from |
| 2765 | `Access.relation_refusal`: asking it would refuse the very write the action |
| 2766 | is for. The action is the grant, and therefore it must check, itself, what |
| 2767 | the relation check and the record API would otherwise have checked: |
| 2768 | |
| 2769 | - **The caller's role.** The server asks the `execute` rule only with |
| 2770 | enforcement on. Ask it inside the action too, from the rules that already |
| 2771 | name the roles (`object_corrections.staff_refusal(access, object_id, |
| 2772 | doing=...)` counts only role grants, admins and denies), so it holds with |
| 2773 | enforcement off and a plain user is refused. Where only some of the |
| 2774 | action's roles may do the expensive part, ask |
| 2775 | `object_corrections.role_grants(access, action, collection=..., |
| 2776 | record=...)`: the same role-only question for any action, with the owner |
| 2777 | fallback off, so owning the row never reads as holding the role. |
| 2778 | app-disputes' resolve action pays out only for a role that may update |
| 2779 | every dispute (manager, owner), while a cashier may close their own as |
| 2780 | `no_action`. |
| 2781 | - **The record's state.** Only the states the action is for: a counter |
| 2782 | payment only for an issued invoice (not a draft, a void, a quote or a |
| 2783 | credit note) with money open, whichever way the record was named. |
| 2784 | - **Scope.** Read a record whose reach the caller's own read decides (the |
| 2785 | order, the invoice) through `object_access` as the caller. Where the |
| 2786 | action itself is the grant for a record the role does not read (the |
| 2787 | product a cashier writes off), read it under the action's authority only |
| 2788 | after the role check, still honour a deny rule that names the caller |
| 2789 | (`object_corrections.denied_by_rule`), and do not widen the role's read |
| 2790 | grants to make the lookup work. Either way a refused record gets the |
| 2791 | answer a missing one gets, without echoing the id, so the action is no |
| 2792 | oracle for ids. When the action pays out of a record the caller may only |
| 2793 | read, check that the records it combines belong together: app-disputes |
| 2794 | pays out of an order only through that order's own bill and payments, |
| 2795 | of the order's own account (`orders.invoice_id` is not a validated |
| 2796 | pointer), instead of asking for an update right on the order that no |
| 2797 | staff role should hold. |
| 2798 | - **Limits.** Anything the caller may do alone only up to a setting (a |
| 2799 | refund amount, a waste quantity) needs an approval above it that names |
| 2800 | the item it approves and is spent once; an approval that names no item is |
| 2801 | refused when it is written and not honoured if one is already on file. |
| 2802 | A limit that is unset or unreadable fails closed unless the shop's |
| 2803 | ordinary work needs a small default, and the description says which. |
| 2804 | |
| 2805 | Refuse before the first write, and say in the action's docstring which of |
| 2806 | these it relies on. |
| 2807 | |
| 2808 | ## Seeded Views And Site Routes |
| 2809 | |
| 2810 | Most app pages are not code. A page is a record in the `views` collection |
| 2811 | whose `blocks` column says what to draw, and a row in `site_routes` that points |
| 2812 | a URL at the renderer. A package ships both as seed files. |
| 2813 | |
| 2814 | `seed/views.tsv` (first row is the header, tab-separated): |
| 2815 | |
| 2816 | | Column | Meaning | |
| 2817 | |---|---| |
| 2818 | | `id` | the record id; unique across every package, so prefix it (`view_deals`) | |
| 2819 | | `title` | required; the page heading | |
| 2820 | | `route` | the path the page answers, e.g. `/deals` or `/deals/{deal_id}`. At most one `{name}` capture; that captured id is what `$record_id` means in the blocks | |
| 2821 | | `layout` | `single` (default), `two_column` or `grid` | |
| 2822 | | `blocks` | a JSON list of blocks, on one line (below) | |
| 2823 | | `owner_id` | leave blank for a package's page | |
| 2824 | | `is_public` | `true` lets anyone read the **view record**. What its blocks show is still decided by the viewer's own permissions, so a public view over private rows renders an empty frame for a stranger | |
| 2825 | | `pinned` | `true` puts it in the nav app switcher | |
| 2826 | | `created_at` | any timestamp | |
| 2827 | |
| 2828 | `seed/site_routes.tsv`: |
| 2829 | |
| 2830 | | Column | Meaning | |
| 2831 | |---|---| |
| 2832 | | `id` | the row id | |
| 2833 | | `pattern` | `/deals`, `/deals/{deal_id}` or `/deals/{deal_id:uuid}` (`:uuid` only matches a UUID) | |
| 2834 | | `object_id` | `site_view_render` for a view | |
| 2835 | | `priority` | an integer; the lowest wins, and a tie goes to the pattern with more literal segments | |
| 2836 | | `host` | optional; the row applies to that host only | |
| 2837 | |
| 2838 | ```text |
| 2839 | id pattern object_id priority |
| 2840 | route_deals /deals site_view_render 20 |
| 2841 | route_deals_detail /deals/{deal_id} site_view_render 10 |
| 2842 | ``` |
| 2843 | |
| 2844 | ```text |
| 2845 | id title route layout blocks owner_id is_public pinned created_at |
| 2846 | view_deals Deals /deals single [{""kind"": ""list"", ""collection"": ""deals"", ""search"": true, ""sort"": true, ""add"": true, ""owner_scoped"": true, ""title_field"": ""title"", ""add_label"": ""+ New Deal""}] true false 2026-01-01T00:00:00 |
| 2847 | view_deals_detail Deal /deals/{deal_id} single [{""kind"": ""detail"", ""collection"": ""deals"", ""record_id"": ""$record_id"", ""editable"": true, ""deletable"": true, ""delete_redirect"": ""/deals""}] true false 2026-01-01T00:00:00 |
| 2848 | ``` |
| 2849 | |
| 2850 | To wire them in: add both seed files to the manifest (`{""collection"": ""views"", |
| 2851 | ""path"": ""seed/views.tsv""}` and the same for `site_routes`), list `app-views` in |
| 2852 | `dependencies` (it ships the `views` schema and the `site_view_render` object, |
| 2853 | and it is not installed for you), and run the server with |
| 2854 | `DBBASIC_ENABLE_SITE_ROUTES=true` (routes are off by default; see |
| 2855 | [`site-routing.md`](/docs/site-routing)). Each view's `route` and its |
| 2856 | `site_routes` row must say the same pattern: the renderer finds the view by |
| 2857 | matching the request against the views' `route` columns. Two reminders: a |
| 2858 | changed row of a shipped view reaches boxes that already have it by the rule |
| 2859 | in the next section (keep the `id`), and the TSV cannot hold a tab or a |
| 2860 | newline inside `blocks`, so keep each block list on one line. |
| 2861 | |
| 2862 | ### Changing a seeded row in a new version |
| 2863 | |
| 2864 | Keep the row's `id`, put the new value in the seed file, bump the package |
| 2865 | `version` and reinstall as for any upgrade (`allow_replace`). Do **not** add a |
| 2866 | second row for the same route: two views answering one `route` collide, and |
| 2867 | the renderer takes the first it finds. The install decides **column by column**, so a |
| 2868 | box's own edits are never lost: |
| 2869 | |
| 2870 | - At every install it records, for each seeded row and column, a hash of what |
| 2871 | the package shipped and of what the row held right after it was written |
| 2872 | (`data/package_baselines/<package>.json`, key `seed_rows`; hashes, never |
| 2873 | the values). `id`, `created_at` and `updated_at` are not tracked. |
| 2874 | - A column the new version changed, whose live value is still what the last |
| 2875 | install wrote, is **replaced**. The seed entry of the install result lists |
| 2876 | those ids under `replaced`, and its `status` is `merged`. |
| 2877 | - A column the new version changed, whose live value is something else (an |
| 2878 | operator edited it through the API or a form), is **kept**. It is listed |
| 2879 | under `kept` (`id`, `columns`, `reason: ""edited""`) and as a warning in the |
| 2880 | result, and the install goes on. The same column the package did *not* |
| 2881 | change is never touched, edited or not, and says nothing. |
| 2882 | - A box installed before rows were tracked has no baseline, and an edit looks |
| 2883 | exactly like an old default. A row there that already equals the new value |
| 2884 | is adopted silently; one that differs is **kept** with `reason: ""no |
| 2885 | baseline""`. Once it matches (edit it by hand, e.g. `PUT |
| 2886 | /collections/views/records/view_notes` with the new `blocks`, or delete it |
| 2887 | and reinstall so the shipped row comes back) later versions flow. |
| 2888 | - A row the collection refuses to update is kept with the refusal's code, and |
| 2889 | never fails the install. |
| 2890 | |
| 2891 | Example: `view_notes` ships `[{""kind"": ""list"", ""collection"": ""notes""}]`. Version |
| 2892 | 0.2.0 adds `""subtitle_field"": ""owner_id""` to its `blocks`. A box that never |
| 2893 | touched the row gets the new `blocks` on reinstall; a box whose operator |
| 2894 | retitled the page keeps that title and still gets the new `blocks`; a box |
| 2895 | whose operator rewrote `blocks` keeps theirs and the install says so. A page |
| 2896 | and its route are two seed rows (`views` and `site_routes`): if you change a |
| 2897 | `route`, change both, and each is decided on its own. A row removed from the |
| 2898 | seed file stays on boxes that have it, and a row an operator deleted is |
| 2899 | added back by the next install, as before. `tests/test_seed_row_upgrade.py` |
| 2900 | runs every case above. Check what your own change does with `--rows` (see |
| 2901 | [Try Your Change](#try-your-change)) on a box built from the old version. |
| 2902 | |
| 2903 | **Blocks.** `kind` is one of `list`, `form`, `detail`, `related`, `thread`, |
| 2904 | `count`, `aggregate`, `markdown`, `reader`, `object`. An unknown kind or key is |
| 2905 | not an error at runtime, it is a placeholder card or silently ignored, so check |
| 2906 | them with the DRON schema instead: `dron/dron-view.schema.json` describes every |
| 2907 | kind and option with a sentence each, and `tests/test_dron_schema.py` validates |
| 2908 | every shipped `views.tsv` against it, and every `site_routes.tsv`, so a |
| 2909 | misspelt option fails there (`python -m pytest tests/test_dron_schema.py -k |
| 2910 | deals`). The `list` block's options: |
| 2911 | |
| 2912 | | Option | Does | |
| 2913 | |---|---| |
| 2914 | | `collection` | required | |
| 2915 | | `title` | a heading above the list | |
| 2916 | | `search` | `true`: a search box (text search over the schema's `search.fields`) | |
| 2917 | | `sort` | `true`: a Newest/Oldest select; `""oldest""` starts oldest first; always by `created_at` | |
| 2918 | | `sort_by`, `sort_dir` | sort by this field instead, `asc` or `desc` (default `desc`) | |
| 2919 | | `add`, `add_label` | `true`: a button that opens the generated create form | |
| 2920 | | `owner_scoped` | `true`: ask only for the viewer's own rows. A request, not access control | |
| 2921 | | `where` | a standing narrowing, `{field: ""value""}`, equality only, applied after the permission filter; keeps the table, filter bar and realtime | |
| 2922 | | `title_field`, `subtitle_field`, `subtitle_label` | which fields label a row (default: the first of `title`, `name`, `label`, `subject`, `body`, `text`, `content`, `message`, `description`, `email`, then the id) | |
| 2923 | | `href_template`, `href_field` | where a row title links, when not `/<collection>/<id>` | |
| 2924 | | `row_actions: false`, `link: false` | no edit/delete buttons, no detail link: for logs and reports | |
| 2925 | | `row_limit` | rows drawn before ""Show all"" (default 50) | |
| 2926 | | `filters`, `limit` | **avoid**: they swap in a bare list of titles with none of the above. Use `where` and `row_limit` | |
| 2927 | |
| 2928 | **Which list modes show `list_fields`.** The mode is `views.list_mode` in the |
| 2929 | collection's schema, not in the block. |
| 2930 | |
| 2931 | | `list_mode` | Shows | |
| 2932 | |---|---| |
| 2933 | | `table` | one column per `views.list_fields` entry (every field when none is listed), relation columns by label, headers sort | |
| 2934 | | `board` | cards grouped by an enum (`views.board.group_field`; default the schema's `flow` field, else the first enum with `transitions`, else the first enum), each card's extra lines from `views.board.card_fields` else `views.list_fields`; a collection with `list_fields` also gets a Board / Table toggle | |
| 2935 | | `tree` | a title per node, nested by `views.tree.parent_field` (default `parent_id`); **no `list_fields`** | |
| 2936 | | `calendar` | a title per day, by `views.calendar.date_field`; **no `list_fields`** | |
| 2937 | | absent, `cards`, `feed` | rows of avatar, title, created date and tags, plus the block's `subtitle_field`; **no `list_fields`** | |
| 2938 | |
| 2939 | A mode whose field cannot be found (no enum for a board, no self-relation for a |
| 2940 | tree) falls back to the row list with a notice. `views.filter_fields` (enum and |
| 2941 | boolean fields) adds a filter bar above every mode. |
| 2942 | |
| 2943 | ## Semantics At A Glance |
| 2944 | |
| 2945 | Small facts that were guessed at, in one place. The fuller account is linked. |
| 2946 | |
| 2947 | - **`older_than_days: N` is inclusive**: a row matches when its age is `N` or |
| 2948 | more days (`age >= N`). A date-only value (`2026-11-20`) ages in calendar days |
| 2949 | against the server's local date, so a date `N` days back matches today; a |
| 2950 | datetime ages in elapsed whole days. A blank, unparseable or future value |
| 2951 | never matches. (""Due before today"" is `older_than_days: 1` on a date.) |
| 2952 | [Declared counts](#declared-counts-collection--where). |
| 2953 | - **`unique` compares trimmed values and ignores blank ones.** `""evt-1""` and |
| 2954 | `""evt-1 ""` collide; a record whose key field is blank has no key. A violation |
| 2955 | is `409 {""code"": ""unique_violation"", ""error"": <your `message`, else a |
| 2956 | generated sentence>, ""fields"": [...], ""scope"": [...]}`; the id of the |
| 2957 | record holding the key is not returned. `ignore_case` is opt-in. |
| 2958 | ([`validation-and-logic.md`](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock)) |
| 2959 | - **`locked_when` refuses with `409 record_locked`**, and `fields` lists the |
| 2960 | frozen fields the write tried to change (`[]` for a delete). `allow_delete` |
| 2961 | defaults to `false`: a settled record cannot be deleted. Judged by the stored |
| 2962 | record, for every writer, the admin token included. |
| 2963 | - **No status means ""done"".** Only the `transitions` map says where a value may |
| 2964 | go; a value with no entry is terminal. `done`, `closed`, `won` are your words. |
| 2965 | - **Roles are assigned on the user** (`roles` when the user is created) and in |
| 2966 | the policy's `user_roles`; rules match them as `role:<name>`. |
| 2967 | [Try Your Change](#try-your-change). |
| 2968 | - **Schema validation of your package** is `tests/test_dron_schema.py`, with no |
| 2969 | `jsonschema` package needed. **Searching** is `GET /api/search?q=...&collections=<c>`; |
| 2970 | `GET /collections/<c>/records` takes `limit`, `offset` and field filters |
| 2971 | (`field=value`, `field.op=value`; ops `eq ne in gte lte gt lt`), and |
| 2972 | `?search=ann` is refused `400` as an unknown field. `q` and `sort` are |
| 2973 | reserved there and ignored. |
| 2974 | |
| 2975 | ## A Minimal Working Example |
| 2976 | |
| 2977 | `packages/hello-world/` in this repository is the smallest complete package. |
| 2978 | `packages/admin-write-probe/` is the smallest complete *app-shaped* package: |
| 2979 | one HTML page object, one schema, one seed file, exercising records end to |
| 2980 | end. `packages/app-projects/` and `packages/app-notes/` are the reference |
| 2981 | *user apps*: an owner-scoped schema with `search` metadata, permission |
| 2982 | rules granting signed-in users their own rows (`row_filter` on |
| 2983 | `$user_id`), and a signed-in page that reads and writes records with the |
| 2984 | visitor's session cookie. Start a new app package from `app-notes`. |
| 2985 | |
| 2986 | `app-notes` also shows the public/private pattern: a boolean `is_public` |
| 2987 | field plus a second permission rule (`principal: public`, `row_filter: |
| 2988 | {""is_public"": ""true""}`) makes shared records readable by anyone across |
| 2989 | every surface — pages, records API, MCP, and search — with no |
| 2990 | visibility code in the app itself. Its permalink page (`site_note_view`) |
| 2991 | expects a `site_routes` record mapping `/notes/{note_id:uuid}` to it; |
| 2992 | route records are site data, so each deployment adds them next to its |
| 2993 | other routes. |
| 2994 | |
| 2995 | Object files inside packages are normal DBBASIC objects. A package page that |
| 2996 | renders per-user content reads `request[""_identity""]`; a package form posts to |
| 2997 | its own object id and writes records through the object runtime. Signed-in |
| 2998 | browser users carry their session cookie automatically. |
| 2999 | |
| 3000 | ## Rules For Generated Packages |
| 3001 | |
| 3002 | - Never put secrets, tokens, real hostnames, or private paths in package |
| 3003 | content — packages are meant to be shareable source. |
| 3004 | - Keep one package per app primitive; use `dependencies` to declare (not yet |
| 3005 | resolve) cross-package needs. |
| 3006 | - Bump the manifest's `version` on any content change so install changelogs and |
| 3007 | restore points stay meaningful. (A schema's own `version` is a label, not a |
| 3008 | switch: [what it does](#what-a-schemas-version-does).) |
| 3009 | - Prefer seed data that demonstrates the schema without pretending to be real |
| 3010 | data. |
| 3011 | - Dry-run output is the review artifact: a package that cannot explain itself |
| 3012 | in a dry-run plan is not ready to install. |
| 3013 | " |
| 3014 | schema-forms Schema Field Contract: Generated Forms and Views Building on DBBASIC 220 How one schema document drives desktop forms, web forms, MCP agents, and record-write validation from the same declared field semantics. "This is the contract that lets user interfaces generate themselves from |
| 3015 | schemas. One schema drives every surface at once: Scroll's desktop forms, a |
| 3016 | server-rendered web form, an agent reading constraints over MCP, and the |
| 3017 | record-write APIs enforcing the same rules for all of them. |
| 3018 | |
| 3019 | The governing principle: **schemas declare semantics, never widgets.** A |
| 3020 | field says ""one of these values"" or ""points at a projects record"" — each |
| 3021 | interface maps that meaning onto its own idiom (a dropdown, a picker, a |
| 3022 | JSON constraint, a spoken prompt). New kinds of interface plug in later |
| 3023 | without touching the data. |
| 3024 | |
| 3025 | Everything here is enforced by the server on record writes today. None of |
| 3026 | it is a DSL — it is keys in the schema JSON document, checked by explicit |
| 3027 | code, versioned and rolled back through the normal schema history. |
| 3028 | |
| 3029 | ## Field Keys |
| 3030 | |
| 3031 | ```json |
| 3032 | { |
| 3033 | ""name"": ""urgency"", |
| 3034 | ""type"": ""enum"", |
| 3035 | ""required"": true, |
| 3036 | ""label"": ""Urgency"", |
| 3037 | ""help"": ""How soon this needs attention"", |
| 3038 | ""placeholder"": ""Choose…"", |
| 3039 | ""default"": ""normal"", |
| 3040 | ""enum"": [""low"", ""normal"", ""high"", ""critical""] |
| 3041 | } |
| 3042 | ``` |
| 3043 | |
| 3044 | - `name` — required; letters/digits/underscores. |
| 3045 | - `type` — `text` (default), `textarea`, `integer`, `number`, `boolean`, |
| 3046 | `date`, `datetime`, `enum`, `computed`. Types are validated on write |
| 3047 | (integers must parse, dates must be ISO, enums must match, and so on). |
| 3048 | Boolean fields accept several spellings on input (`True`, `1`, `yes`) |
| 3049 | but are stored canonically as `true`/`false`, so permission row |
| 3050 | filters like `{""is_public"": ""true""}` match reliably. |
| 3051 | - `required` — empty values rejected on write. |
| 3052 | - `label`, `help`, `placeholder` — presentation text for generated forms. |
| 3053 | - `default` — filled in when the field is not submitted. |
| 3054 | - `enum` — allowed values; writes outside the list are rejected. Renders as |
| 3055 | a dropdown/segment control in form UIs. |
| 3056 | - `computed` / `read_only` — the server rejects client writes to these |
| 3057 | fields; forms render them display-only. |
| 3058 | - `transitions` — for lifecycle fields, which values each current value |
| 3059 | may move to. Enforced on record update; values missing from the map |
| 3060 | are terminal. (`done`, `closed`, `won` mean nothing to the platform: a |
| 3061 | status is final only because nothing lists a move out of it.) This is data plus one check, not a state machine |
| 3062 | framework — no hooks, no callbacks, no side effects: |
| 3063 | |
| 3064 | ```json |
| 3065 | {""name"": ""status"", ""type"": ""enum"", |
| 3066 | ""enum"": [""open"", ""assigned"", ""done""], |
| 3067 | ""transitions"": {""open"": [""assigned""], ""assigned"": [""done"", ""open""]}} |
| 3068 | ``` |
| 3069 | |
| 3070 | Form UIs can offer only the moves allowed from the record's current |
| 3071 | value; the server rejects everything else either way. |
| 3072 | |
| 3073 | A list entry can also be a guarded object instead of a plain string, |
| 3074 | adding *who* on top of *whether*: |
| 3075 | |
| 3076 | ```json |
| 3077 | {""transitions"": { |
| 3078 | ""assigned"": [{""to"": ""open"", ""when"": {""assigned_to"": ""$user_id""}}] |
| 3079 | }} |
| 3080 | ``` |
| 3081 | |
| 3082 | The move is allowed only once every `when` clause matches the record's |
| 3083 | current stored values against the resolved subject variable |
| 3084 | (`$user_id`, `$account_id`, `$accessible_projects`, `$owned_projects`, |
| 3085 | `$writable_projects`) or a literal string — the same closed set and |
| 3086 | matching rules row filters use (see `docs/permissions-model.md`). Guards |
| 3087 | are only evaluated where a request subject is available (the HTTP |
| 3088 | update path); direct library callers still get the plain validity |
| 3089 | check (the move's `to` must be in the list) but not the guard. |
| 3090 | - `relation` — a validated pointer to another collection: |
| 3091 | |
| 3092 | ```json |
| 3093 | {""name"": ""project_id"", ""relation"": {""collection"": ""projects"", ""display_field"": ""name""}} |
| 3094 | ``` |
| 3095 | |
| 3096 | On write, the value must be an existing record id in that collection |
| 3097 | (`projects/p999` missing → 400). `display_field` tells form UIs which |
| 3098 | field of the target record to show in pickers. A bare string |
| 3099 | (`""relation"": ""projects""`) is shorthand. This is deliberately a pointer |
| 3100 | plus a display hint, not an association framework — no joins, no lazy |
| 3101 | loading, no cascades. `""requires"": ""read""` or `""update""` makes an API |
| 3102 | writer prove they may see (or act on) the record the pointer names |
| 3103 | before the write lands; see ""Pointing at a record you may not act on"" in |
| 3104 | docs/permissions-model.md. |
| 3105 | - `validation` — explicit bounds, all enforced on write: |
| 3106 | |
| 3107 | ```json |
| 3108 | {""validation"": {""min_length"": 3, ""max_length"": 80, ""pattern"": ""^[a-z-]+$"", ""min"": 0, ""max"": 100}} |
| 3109 | ``` |
| 3110 | |
| 3111 | `pattern` is **full-matched** against the whole value (`re.fullmatch`), |
| 3112 | not searched — so it must describe the entire field, not a prefix. A URL |
| 3113 | check is `^https?://\S+$`, not `^https?://` (that would only match the |
| 3114 | literal scheme and reject every real URL). The `^`/`$` anchors are |
| 3115 | therefore redundant but fine to keep for readability. |
| 3116 | A pattern is written in the DRON dialect, a subset Python and JavaScript |
| 3117 | read alike: no lookbehind, named groups, inline flags (`(?i)`), |
| 3118 | backreferences or `\b`; `\d` and `\w` are ASCII. A package with a pattern |
| 3119 | outside it is refused at install with what to write instead. See |
| 3120 | ""Regular expressions"" in dron.md. |
| 3121 | |
| 3122 | ## Schema Root Keys |
| 3123 | |
| 3124 | Presentation metadata lives beside the fields and versions with them — |
| 3125 | Scroll's ""Save Layout"" persists here, so form design has history and |
| 3126 | rollback like source code: |
| 3127 | |
| 3128 | ```json |
| 3129 | { |
| 3130 | ""fields"": [...], |
| 3131 | ""forms"": { |
| 3132 | ""default"": {""fields"": [""title"", ""description"", ""project_id"", ""urgency"", ""due_date"", ""assigned_to""]} |
| 3133 | }, |
| 3134 | ""views"": { |
| 3135 | ""list_mode"": ""table"", |
| 3136 | ""list_fields"": [""title"", ""urgency"", ""due_date"", ""assigned_to""] |
| 3137 | } |
| 3138 | } |
| 3139 | ``` |
| 3140 | |
| 3141 | - `forms.default.fields` — field order for the generated record form. |
| 3142 | Additional named forms can define alternate layouts. |
| 3143 | - `views.list_mode` — how the generated list renders. The shared list |
| 3144 | renderer (`window.dbbasicList`) resolves it from the schema: |
| 3145 | - `table` — a dense, sortable HTML table over `list_fields`; cells format by |
| 3146 | type (money `_cents`, boolean, relative dates, enum badges), and relation |
| 3147 | columns show the target's label, not the raw id. |
| 3148 | - `board` — a kanban grouped by an enum field, drag-to-transition (the drag |
| 3149 | issues the ordinary status write, so `flow` transitions still gate it). A |
| 3150 | board collection that also has `list_fields` gets a **Board ⇄ Table** |
| 3151 | toggle (the choice persists per collection). |
| 3152 | - `tree` — nests a self-relation (`parent_id`) into a hierarchy. |
| 3153 | - `calendar` — buckets by a date field. |
| 3154 | - absent / `cards` / `feed` — the plain rich-row list. |
| 3155 | |
| 3156 | Every mode shares one fetch/sort/cap/search/realtime pipeline, so all of |
| 3157 | them inherit filtering, the 50-row cap, and live updates. A mode whose |
| 3158 | required field can't be derived falls back to the row list with a visible |
| 3159 | notice — never a blank page. |
| 3160 | - `views.list_fields` — the columns of a `table` list and the extra lines on |
| 3161 | each `board` card (a board's own `views.board.card_fields` wins). **Only those |
| 3162 | two modes use it**: the plain row list (`list_mode` absent, `cards` or |
| 3163 | `feed`), `tree` and `calendar` show a title (and, for rows, a created date) |
| 3164 | and ignore it; a row list takes its title and subtitle from the view block's |
| 3165 | `title_field` and `subtitle_field` instead. Relation fields resolve to the |
| 3166 | referenced record's label. To add a field to a list page, see the recipe in |
| 3167 | [`package-authoring.md`](/docs/package-authoring#add-a-field-and-show-it-in-a-list-page). |
| 3168 | - `views.filter_fields` — fields to expose as a **filter bar** above the list |
| 3169 | (enum → a select of its options, boolean → Yes/No). A pick narrows the fetch |
| 3170 | server-side (`field=value`, after the permission row filter) and composes |
| 3171 | with the search box; works in every mode. |
| 3172 | - `search` — opts the collection into global search (`GET /api/search` |
| 3173 | and the `global_search` MCP tool): |
| 3174 | |
| 3175 | ```json |
| 3176 | {""search"": {""fields"": [""title"", ""content""], ""result_fields"": [""id"", ""title""]}} |
| 3177 | ``` |
| 3178 | |
| 3179 | `fields` are the searchable fields; `result_fields` (optional) trims |
| 3180 | what each search hit returns, defaulting to `id` plus |
| 3181 | `views.list_fields`. Collections without a `search` section never |
| 3182 | appear in search results. Search runs inside the permission engine, so |
| 3183 | row filters and field permissions bound what any caller can find. |
| 3184 | - `formula` / `rollup` (on a `type: computed` field) — derived values, |
| 3185 | materialized on write: a formula computes from sibling fields |
| 3186 | (`""first_name + \"" \"" + last_name""`); a rollup aggregates a child |
| 3187 | collection (`{""collection"": ""fin_journal_lines"", ""fk_field"": ""journal_id"", |
| 3188 | ""op"": ""sum"", ""field"": ""debit_cents""}`). Stored like any field, so every |
| 3189 | view/filter/sort sees them; kept current by the write path. See |
| 3190 | [`validation-and-logic.md`](/docs/validation-and-logic). |
| 3191 | - `capabilities` — generic per-collection *behaviors* on top of this display |
| 3192 | layer: `{""comments"": true}`, `{""attachments"": true}`, `{""shareable"": true}` |
| 3193 | grow a comment thread, attachment list, and owner-checked sharing on the |
| 3194 | detail page from one flag each. See [`capabilities.md`](/docs/capabilities). |
| 3195 | |
| 3196 | ## Worked Example: tasks |
| 3197 | |
| 3198 | The acceptance test for this contract is Scroll's New Task screen, |
| 3199 | expressed entirely as data: |
| 3200 | |
| 3201 | ```json |
| 3202 | { |
| 3203 | ""fields"": [ |
| 3204 | {""name"": ""id""}, |
| 3205 | {""name"": ""title"", ""type"": ""text"", ""required"": true, ""label"": ""Title"", |
| 3206 | ""validation"": {""min_length"": 1, ""max_length"": 200}}, |
| 3207 | {""name"": ""description"", ""type"": ""textarea"", ""label"": ""Description""}, |
| 3208 | {""name"": ""project_id"", ""label"": ""Project"", |
| 3209 | ""relation"": {""collection"": ""projects"", ""display_field"": ""name""}}, |
| 3210 | {""name"": ""urgency"", ""type"": ""enum"", ""label"": ""Urgency"", ""default"": ""normal"", |
| 3211 | ""enum"": [""low"", ""normal"", ""high"", ""critical""]}, |
| 3212 | {""name"": ""due_date"", ""type"": ""date"", ""label"": ""Due Date""}, |
| 3213 | {""name"": ""assigned_to"", ""label"": ""Assigned To"", |
| 3214 | ""relation"": {""collection"": ""users"", ""display_field"": ""display_name""}} |
| 3215 | ], |
| 3216 | ""forms"": {""default"": {""fields"": [""title"", ""description"", ""project_id"", |
| 3217 | ""urgency"", ""due_date"", ""assigned_to""]}}, |
| 3218 | ""views"": {""list_mode"": ""table"", |
| 3219 | ""list_fields"": [""title"", ""urgency"", ""due_date"", ""assigned_to""]} |
| 3220 | } |
| 3221 | ``` |
| 3222 | |
| 3223 | A form renderer walks `forms.default.fields`, looks up each field's |
| 3224 | semantics, and emits the right control. The record POST enforces every |
| 3225 | rule the form promised — and the same rules bind a record created over |
| 3226 | MCP or raw HTTP, so no surface can bypass what another surface displays. |
| 3227 | " |
| 3228 | business-logic-patterns Business Logic Patterns: Where Every Rule Goes Building on DBBASIC 230 A placement guide and decision procedure for where each kind of business rule belongs in the primitive stack, illustrated with worked examples from tax, aging, dunning, refunds, inventory, and bank reconciliation. "Every business rule has one correct home in the primitive stack. This page is |
| 3229 | the placement guide: the decision procedure, the map, and four worked examples |
| 3230 | (sales tax, payment aging, dunning, refunds) that most systems get wrong. |
| 3231 | The placement *decisions* and their reasons accumulate in |
| 3232 | [`logic-decisions.md`](/docs/logic-decisions), the way UI behavior accumulates in |
| 3233 | [`ui-decisions.md`](/docs/ui-decisions). |
| 3234 | |
| 3235 | The method behind all of it (see logic-decisions #4): build each module's |
| 3236 | rules **concretely** in the cheapest correct primitive — a hook is three lines |
| 3237 | of real code — and only promote a pattern to a declarative schema key after it |
| 3238 | has repeated in two or three real modules. Concrete → pattern → primitive, |
| 3239 | never primitive-first. Systems that build the workflow/rules engine first die |
| 3240 | when reality doesn't fit it; ours extracts engines from reality. |
| 3241 | |
| 3242 | ## Where does this rule go? |
| 3243 | |
| 3244 | ```mermaid |
| 3245 | flowchart TD |
| 3246 | Q[""a business rule""] --> D1{""Derivable from<br/>stored data?""} |
| 3247 | D1 -->|same record| F[""formula field""] |
| 3248 | D1 -->|child records| R[""rollup field""] |
| 3249 | D1 -->|no| D2{""Does it GATE<br/>a write?""} |
| 3250 | D2 -->|shape / bounds / FK| V[""schema validation""] |
| 3251 | D2 -->|legal state moves + who| T[""transitions + when guards""] |
| 3252 | D2 -->|cross-record or computed gate| H[""pre-write hook<br/>(reject or stamp)""] |
| 3253 | D2 -->|no| D3{""Does TIME<br/>cause it?""} |
| 3254 | D3 -->|yes| DM[""daemon: scheduled pass /<br/>auto-transition""] |
| 3255 | D3 -->|no| D4{""Is it a REACTION<br/>to a change?""} |
| 3256 | D4 -->|notify / email| N[""notify_rules (after write)""] |
| 3257 | D4 -->|run code| TR[""trigger → target object""] |
| 3258 | D4 -->|external system| C[""connector<br/>(desired state + reconcile)""] |
| 3259 | D4 -->|no| O[""plain object<br/>(page / API / worker)""] |
| 3260 | ``` |
| 3261 | |
| 3262 | ## The placement map |
| 3263 | |
| 3264 | | Kind of rule | Primitive | Lives in | Example | |
| 3265 | |---|---|---|---| |
| 3266 | | Shape, type, bounds, enum, FK-exists | schema validation | `object_records` write path | amount is integer cents; project must exist | |
| 3267 | | Same-record derivation | `formula` (materialized) | `object_computed` via `object_records` | `tax_cents = amount_cents * tax_rate` | |
| 3268 | | Aggregation over children | `rollup` (materialized, live) | same | `invoice.paid_cents = sum(payments)` | |
| 3269 | | Legal state moves, and who may move | `transitions` + `when` | `object_records` | `draft → posted`, owner only | |
| 3270 | | A value that may appear once (a key, a code, an idempotency marker) | schema `unique` | `object_records`, **inside the write lock**, every writer | one usage event per `event_id` per owner; a `generated_from` marker used once | |
| 3271 | | A sum that must not pass a ceiling, or any rule that reads other collections, under overlapping writes | schema `locked_checks`: a read-only function + the collections it `reads` + a named `lock` | `object_records`, **inside the write lock and the check lock**, every writer | payments ≤ invoice, refunds ≤ payment (`ledger` lock); nothing written into a closed period (`fin_periods` lock) | |
| 3272 | | A record that is settled: frozen fields, no delete | schema `locked_when` | `object_records`, **inside the write lock**, every writer | approved time may change only `status`, `invoice_id`, `notes` | |
| 3273 | | Cross-record gate, computed gate, point-in-time stamp | **pre-write hook** | `hooks.before_write` → `object_server` write path | journal must balance; stamp `tax_rate` | |
| 3274 | | Time-driven state | daemon scheduled pass / `after_hours` auto-transition | `object_daemon` | `sent → overdue` when past due | |
| 3275 | | Reaction: notify, email | `notify_rules` | daemon, **after** the write | dunning email on `overdue` | |
| 3276 | | Reaction: run code | trigger → target object | daemon | recompute, follow-on records | |
| 3277 | | External side effect | connector | desired-state records + reconcile | payment-provider refund call | |
| 3278 | | Correction to money / inventory | append-only compensating record | `storage: append` collections | refunds, stock moves, journal reversals | |
| 3279 | | Everything else | a plain object | anywhere | bespoke report, integration, one-off page | |
| 3280 | |
| 3281 | Two hard boundaries hold the map together: |
| 3282 | |
| 3283 | - **Gates before the write; reactions after.** A hook may reject or stamp but |
| 3284 | never send email or call out — a gate with side effects leaks that a write |
| 3285 | was attempted and couples saves to SMTP. A reaction may notify or spawn work |
| 3286 | but never block the write that already happened. |
| 3287 | ([`event-hooks-decisions.md`](/docs/event-hooks-decisions)) |
| 3288 | - **Derived values are non-authoritative; gates are authoritative.** A broken |
| 3289 | formula stores `""""` and the write succeeds; a broken hook fails closed and |
| 3290 | the write is rejected. Never let a gate read only a derived value it could |
| 3291 | recompute — the journal-balance hook sums the lines itself even though |
| 3292 | rollup totals exist. |
| 3293 | |
| 3294 | One placement the map gets wrong if read quickly: **""has this already been |
| 3295 | written?"" is not a hook.** A hook that looks for an existing row runs before |
| 3296 | the write lock, so two overlapping writes both find nothing; and handlers and |
| 3297 | scheduled jobs write below the hook entirely. Declare the key `unique` |
| 3298 | ([`validation-and-logic.md`](/docs/validation-and-logic)) and let the writer |
| 3299 | that loses catch `UniqueConstraintError`. |
| 3300 | |
| 3301 | ## Worked example 1: sales tax (the one everyone leaves out) |
| 3302 | |
| 3303 | Why it's left out: it hides a doctrine most systems never articulate — |
| 3304 | **stamp point-in-time facts; derive live facts** (logic-decisions #1). |
| 3305 | The tax *rate* is a fact about the transaction moment: rates change, and the |
| 3306 | invoice must forever carry the rate it was issued under. |
| 3307 | |
| 3308 | 1. **Rates are data**: a `tax_rates` collection — `region`, `category`, |
| 3309 | `rate`, `valid_from`. Editable like any records; history visible. |
| 3310 | 2. **Stamping is a hook**: `hooks.before_write` on invoice lines looks up the |
| 3311 | applicable rate and *stamps* `tax_rate` onto the line — same posture as the |
| 3312 | server stamping `owner_id`. The client never supplies it; later rate |
| 3313 | changes never rewrite history. |
| 3314 | 3. **Amounts are formulas/rollups**: `line.tax_cents = amount_cents * |
| 3315 | tax_rate` (formula); `invoice.tax_total_cents` (rollup). Materialized, so |
| 3316 | they appear on every list/detail/report and update live. |
| 3317 | |
| 3318 | ## Worked example 2: payment aging (time makes the state) |
| 3319 | |
| 3320 | The trap: an invoice becomes overdue with **no write happening** — time did |
| 3321 | it. Any system that computes ""is it late?"" ad hoc in the UI grows a dozen |
| 3322 | disagreeing copies of that check. |
| 3323 | |
| 3324 | 1. `balance_cents` is a **rollup** (`total_cents` minus `sum(payments)`). |
| 3325 | 2. `sent → overdue` is a **daemon scheduled pass** through the ordinary |
| 3326 | transition machinery, when `due_date < today` and `balance_cents > 0` — |
| 3327 | so the state is *stored*, permission-checked, realtime-pushed, and every |
| 3328 | surface agrees (logic-decisions #2: time-driven state belongs to the |
| 3329 | daemon, never to read-time checks). |
| 3330 | 3. Aging buckets (30/60/90) are a rollup/report over stored state. |
| 3331 | |
| 3332 | ## Worked example 3: dunning (reactions compose on state) |
| 3333 | |
| 3334 | Dunning is nothing new — it is the composition of the two layers above: |
| 3335 | |
| 3336 | 1. The daemon flips the state (`overdue`, later `overdue_30`, …). |
| 3337 | 2. `notify_rules` reacts: state change → email template to the invoice's |
| 3338 | contact. The rule is data; the daemon delivers after the write. |
| 3339 | 3. Escalation (""again at 30 days unless paid"") is *more time-driven state*, |
| 3340 | not a special notification feature — each escalation step is a transition |
| 3341 | the daemon makes, each with its own notify rule. |
| 3342 | |
| 3343 | ## Worked example 4: refunds (money moves, never mutates) |
| 3344 | |
| 3345 | **Money never mutates; it moves** (logic-decisions #3). A refund is not an |
| 3346 | edit to a payment — it is a new, append-only compensating record, exactly like |
| 3347 | a stock move or a journal reversal. |
| 3348 | |
| 3349 | 1. `refunds` is an `storage: append` collection pointing at the payment. |
| 3350 | 2. The invariant is a **hook**: `refund ≤ payment − prior refunds` — a |
| 3351 | cross-record gate, summed from the records themselves. |
| 3352 | 3. `payment.refunded_cents` / `net_cents` are **rollup/formula** — display |
| 3353 | truth, derived. |
| 3354 | 4. ""Correctly credited"" is the balanced journal entry the refund composes — |
| 3355 | enforced by the journal-balance hook that already ships. The chain closes: |
| 3356 | append-only record → hook invariant → rollup display → balanced books. |
| 3357 | |
| 3358 | ## Worked example 5: inventory shrinkage (the events nobody codes for) |
| 3359 | |
| 3360 | Waste, breakage, theft, expiry, damage, disaster: systems are easy to build |
| 3361 | when quantities just flow buy → stock → sell; real usage is losses. Naming |
| 3362 | them is the point — ""adjustment"" is the euphemism that hides exactly what |
| 3363 | operators and auditors need to see. |
| 3364 | |
| 3365 | 1. **Losses are movements** (logic-decisions #3): a loss is an append-only |
| 3366 | stock move with a loss `reason`, out of a location, to nowhere — never an |
| 3367 | edit to an on-hand number (levels stay derived). |
| 3368 | 2. **The hook stamps and gates**: `unit_cost_cents` is stamped from the |
| 3369 | product at the moment of movement (#1 — tomorrow's cost edit must not |
| 3370 | reprice yesterday's loss); a loss must leave a real location and can have |
| 3371 | no destination. |
| 3372 | 3. **The composer books the shadow**: a loss move composes a posted journal — |
| 3373 | DR shrinkage-expense / CR inventory-asset — with per-reason account |
| 3374 | overrides as settings (theft to its own account for the insurance claim). |
| 3375 | 4. **Count reconciliation is the same machinery**: a physical count writes |
| 3376 | one compensating adjustment move for the variance (out for shortage, in |
| 3377 | for overage) plus the mirror journal. The count is an *event*, not an |
| 3378 | edit. |
| 3379 | |
| 3380 | This was also the composer pattern's third repeat, which triggered the |
| 3381 | doctrine-#4 extraction: every generated journal now goes through |
| 3382 | `object_finance.compose_posted_journal` (idempotent by `generated_from`, |
| 3383 | verify-then-post), and the payment/refund/recurring/reversal composers |
| 3384 | shrank onto it. |
| 3385 | |
| 3386 | ## Worked example 6: bank reconciliation (evidence, not data entry) |
| 3387 | |
| 3388 | Comparing the books to a bank statement is the strongest practical control a |
| 3389 | small business has, and the reason is not arithmetic — it is that the bank's |
| 3390 | copy was written by someone with no stake in our numbers. Every design |
| 3391 | choice follows from protecting that independence (logic-decisions #8). |
| 3392 | |
| 3393 | 1. **Imported lines are append-only and keep their original text** in `raw`; |
| 3394 | parsed fields are a view of it. A pre-write hook makes the factual fields |
| 3395 | immutable on update — corrections come from re-importing a corrected |
| 3396 | statement, never from editing a line to agree with the books. |
| 3397 | 2. **The statement checks itself.** Opening + lines = closing (tie-out), and |
| 3398 | this opening = the last statement's closing (continuity). Both run at |
| 3399 | import and *set* the import's status; a truncated or edited file fails |
| 3400 | arithmetic. The flags record which checks **ran**, so a balance-less CSV |
| 3401 | never reads as trustworthy as a verified one. |
| 3402 | 3. **Reading a bank's format is data**, not code: a saved column map, |
| 3403 | authored once with AI help and executed deterministically thereafter. AI |
| 3404 | at configuration time, code at run time — a control cannot be |
| 3405 | nondeterministic. |
| 3406 | 4. **The matcher proposes; a person disposes.** Suggestions are derived and |
| 3407 | non-authoritative; confirming is an ordinary attributed update, so the |
| 3408 | change log names who reconciled what. Only a two-signal match |
| 3409 | (reference *and* amount) is auto-confirmable, and even that is |
| 3410 | configurable to off. |
| 3411 | 5. **The unmatched tail is where the business logic lives**: fees, interest, |
| 3412 | own-account transfers, NSF bounces — each a resolution verb composing a |
| 3413 | posted journal through the shared composer, stamped with the line's id so |
| 3414 | resolving twice books once. These are exactly the entries small books |
| 3415 | never record, which is why their cash balance drifts until they stop |
| 3416 | reconciling at all. |
| 3417 | |
| 3418 | ## State-dependent behavior generally |
| 3419 | |
| 3420 | `transitions` + `when` guards define the machine; the board's drag is its UI; |
| 3421 | hooks gate specific moves with computed conditions (the balance check gates |
| 3422 | `draft → posted`); the daemon makes time-based moves. The known missing |
| 3423 | declarative is **""state freezes fields""** (a posted invoice's amounts are |
| 3424 | immutable). Per the method: express it in each module's hook first; promote it |
| 3425 | to a schema key (`locked_when`) only after the shape repeats |
| 3426 | (logic-decisions #5). |
| 3427 | |
| 3428 | ## What this implies we build next |
| 3429 | |
| 3430 | The examples above want one substrate piece that doesn't exist yet: a |
| 3431 | **payments collection** (plain records — provider integration is a connector |
| 3432 | later). It unblocks aging, dunning, and refunds at once. Then: `tax_rates` + |
| 3433 | the stamping hook; then a delay/repeat notion for `notify_rules` if escalation |
| 3434 | schedules outgrow ""each step is its own transition."" |
| 3435 | |
| 3436 | ## Related |
| 3437 | |
| 3438 | - [`validation-and-logic.md`](/docs/validation-and-logic) — the enforcement |
| 3439 | reference for each primitive (validation table, hooks contract, |
| 3440 | formulas/rollups, the automation substrate). |
| 3441 | - [`logic-decisions.md`](/docs/logic-decisions) — the living log of placement |
| 3442 | decisions and doctrines. |
| 3443 | - [`storage-modes.md`](/docs/storage-modes) — append-only collections, the |
| 3444 | substrate for money-moves. |
| 3445 | " |
| 3446 | validation-and-logic Validation and Business Logic Building on DBBASIC 240 How DBBASIC Object Server enforces field validation and runs business rules from the schema alone, with no per-app code required. "Two things a schema-driven system has to get right without per-app code: |
| 3447 | rejecting bad writes, and running the business rules a record's lifecycle |
| 3448 | implies. DBBASIC does both from the schema, enforced on the server — the form |
| 3449 | is a convenience, not the gate. |
| 3450 | |
| 3451 | ## Validation — declared once, enforced on every write |
| 3452 | |
| 3453 | The write path (create and update) validates each field against the schema, |
| 3454 | server-side, regardless of which surface issued the write (web form, API, MCP |
| 3455 | agent, AI). A form's client-side checks are a nicety on top; they are not what |
| 3456 | protects the data. |
| 3457 | |
| 3458 | What is enforced today: |
| 3459 | |
| 3460 | | Check | Declared as | Enforced | |
| 3461 | |-------|-------------|----------| |
| 3462 | | Type parses | `type` (integer, number, date, datetime, boolean, enum) | ✅ | |
| 3463 | | Required present | `required: true` | ✅ | |
| 3464 | | Enum membership | `enum: [...]` | ✅ (value must be in the list) | |
| 3465 | | Length bounds | `validation.min_length` / `max_length` | ✅ | |
| 3466 | | Numeric range | `validation.min` / `max` | ✅ (every writer; `payments.amount_cents` and `refunds.amount_cents` declare `min: 1`) | |
| 3467 | | Strict numeric bound | `validation.exclusive_min` / `exclusive_max` | ✅ (every writer; ""greater than zero"" — see below) | |
| 3468 | | Required once a state holds | `validation.required_when` | ✅ (every writer; ""a matched line names its target"" — see below) | |
| 3469 | | Pattern | `validation.pattern` (regex: Python `re` syntax, matched against the whole value; a package whose pattern does not compile is refused at install, see `dron.md`) | ✅ | |
| 3470 | | Referential integrity | `relation: {collection}` | ✅ (id must exist in the target) | |
| 3471 | | State transition | field `transitions` map / `flow` | ✅ (status can only move where allowed) | |
| 3472 | | Read-only / computed | `read_only` / `type: computed` | ✅ (client value rejected) | |
| 3473 | | Uniqueness | root-level `unique: [{fields, scope}]` | ✅ (inside the write lock, for every writer — see below) | |
| 3474 | | Frozen once settled | root-level `locked_when: [{when, except}]` or `[{when, fields}]` | ✅ (update and delete, inside the write lock, for every writer — see below) | |
| 3475 | | Storable in TSV | (substrate) | ✅ (size, no NUL/control chars) | |
| 3476 | |
| 3477 | Referential integrity and enforced state transitions are the notable ones — |
| 3478 | most no-code tools skip both. A relation is a *validated pointer*: you cannot |
| 3479 | point a `project_id` at a project that doesn't exist. A status field with a |
| 3480 | `transitions` map is a state machine: an order can go `open → cancelled` only |
| 3481 | if the schema says so. |
| 3482 | |
| 3483 | ### Strict bounds and conditional required fields |
| 3484 | |
| 3485 | ```json |
| 3486 | {""name"": ""quantity"", ""type"": ""number"", ""required"": true, |
| 3487 | ""validation"": {""exclusive_min"": 0}}, |
| 3488 | |
| 3489 | {""name"": ""matched_to"", ""type"": ""text"", |
| 3490 | ""validation"": {""required_when"": {""match_status"": [""matched""]}}} |
| 3491 | ``` |
| 3492 | |
| 3493 | **`exclusive_min` / `exclusive_max`** say *strictly* greater / less than a |
| 3494 | number. `min` and `max` are inclusive, so `min: 0` admits a zero and ""usage is |
| 3495 | positive"" or ""a stock move moves something"" could not be said without code. |
| 3496 | Use `min: 1` for a whole-number count (`payments.amount_cents`); use |
| 3497 | `exclusive_min: 0` where fractions are real (`quantity`, which may be 1.5 or |
| 3498 | 0.0000001). The comparison is exact (decimal, not float), the field must be |
| 3499 | numeric, and a blank value is left to `required`, as it is for `min`. The |
| 3500 | refusal reads `Record field 'quantity' must be greater than 0`. They combine |
| 3501 | with `min` / `max`; a range that allows nothing (`exclusive_min: 5` with |
| 3502 | `max: 5`) is refused at schema load. |
| 3503 | |
| 3504 | **`required_when`** says the field must be non-blank (not empty, not only |
| 3505 | spaces) while the record matches **every** condition, in the shape |
| 3506 | `locked_when.when` uses: `{field: value}` or `{field: [values]}`, where a field |
| 3507 | holds one of its values (compared exactly, as stored; booleans as `true` / |
| 3508 | `false`). It is judged on the record **as it will be stored**: on an update, |
| 3509 | the stored row with the submitted changes applied. So the write that sets |
| 3510 | `match_status` to `matched` must also set `matched_to` (or find it already |
| 3511 | set), a write that blanks `matched_to` while the line is matched is refused, |
| 3512 | and moving the line out of `matched` frees the field. The refusal reads |
| 3513 | `Record field 'matched_to' is required when match_status is matched`. |
| 3514 | |
| 3515 | Both are checked by `object_records` with the other field rules, on create |
| 3516 | and update, for every writer: HTTP, MCP, handlers, the daemon, imports. A |
| 3517 | refusal is the ordinary validation **400** (`InvalidRecordPayloadError`) and |
| 3518 | nothing is written. A row that already breaks a rule when a declaration is |
| 3519 | added stays on file, but is refused on its next write whatever that write |
| 3520 | changes — the same as `min`. |
| 3521 | |
| 3522 | **Refused at schema load** (`ValueError`, never ""no rule""): a bound that is not |
| 3523 | a finite number, an exclusive bound on a non-numeric field, bounds that leave |
| 3524 | no value, a `required_when` that is empty, names a field the schema does not |
| 3525 | declare (a typo would never apply), names the field itself, has a value that is |
| 3526 | not a string or a non-empty list of strings, or sits on a computed or |
| 3527 | read-only field. |
| 3528 | |
| 3529 | **What they do not do.** They cannot say ""forbidden when"" (a loss move must have |
| 3530 | *no* destination) or compare two fields (`taken <= capacity`), and `required_when` |
| 3531 | asks for non-blank, not for a particular value. Those stay in a hook or a |
| 3532 | [locked check](#locked-checks--a-decision-across-collections-made-inside-the-write-lock). The whole list of what a declaration cannot say, and the tool for each, is |
| 3533 | [What can't be declared](/docs/package-authoring#what-cant-be-declared). |
| 3534 | |
| 3535 | ### Known gaps |
| 3536 | |
| 3537 | - **Numeric range is declared field by field, and most money fields do not |
| 3538 | declare it yet.** `validation.min`/`max` is enforced, but a price can still |
| 3539 | go negative wherever no schema says otherwise. The collections where it |
| 3540 | mattered first (payments, refunds) declare `min: 1`, and the quantities of |
| 3541 | usage events, stock moves and shipment lines declare `exclusive_min: 0`; the |
| 3542 | others still rely on their hook, which only the public write surface reaches. |
| 3543 | - **Declarative cross-field rules** — no formula language yet for |
| 3544 | ""end_date > start_date"" (`visible_when` handles conditional *visibility*, |
| 3545 | not validation). The general mechanism exists, though: a **pre-write hook** |
| 3546 | (below) expresses any cross-field or cross-collection rule in real code. A |
| 3547 | Salesforce-style declarative rule (formula + message) remains the ergonomic |
| 3548 | follow-on for the common cases. |
| 3549 | - **Inline client feedback** — the form pre-checks `required`; length/pattern |
| 3550 | errors currently surface after a server round-trip, and messages are |
| 3551 | technical (""longer than max_length""). Friendlier, inline feedback is a |
| 3552 | UX polish item, not a safety gap. |
| 3553 | |
| 3554 | ## Uniqueness — declared in the schema, enforced inside the write lock |
| 3555 | |
| 3556 | ```json |
| 3557 | { |
| 3558 | ""name"": ""usage_events"", |
| 3559 | ""unique"": [ |
| 3560 | {""fields"": [""event_id""], ""scope"": [""owner_id""]}, |
| 3561 | {""fields"": [""code""], ""ignore_case"": true, ""message"": ""That code is already in use.""} |
| 3562 | ], |
| 3563 | ""fields"": [ ... ] |
| 3564 | } |
| 3565 | ``` |
| 3566 | |
| 3567 | Each entry says: no two records may hold the same `fields` values — within |
| 3568 | the same `scope` values, when a scope is given. |
| 3569 | |
| 3570 | | key | meaning | |
| 3571 | |---|---| |
| 3572 | | `fields` | Required. The key: one or more field names. With several, records collide only when **all** match. | |
| 3573 | | `scope` | Optional. Field names the key is unique *within* (""per owner"", ""per bank account""). | |
| 3574 | | `ignore_case` | Optional, default `false`. Compare the `fields` values without regard to case. | |
| 3575 | | `message` | Optional. The error text for a violation, in place of the generated sentence. | |
| 3576 | |
| 3577 | How two records are compared: |
| 3578 | |
| 3579 | - **Values are compared trimmed.** `""evt-1""` and `""evt-1 ""` are one key. |
| 3580 | - **A blank `fields` value means the record has no key and is exempt.** Most |
| 3581 | wallets have no gift-card code and a bank line from a CSV has no bank |
| 3582 | transaction id; uniqueness is a property of the keys that exist. Make the |
| 3583 | field `required` if every record must have one. |
| 3584 | - **A blank `scope` value is an ordinary value.** Two ownerless records with |
| 3585 | the same key *do* collide. (Admin-token writes are not owner-stamped; if a |
| 3586 | blank scope were exempt, they could duplicate freely.) |
| 3587 | - `ignore_case` folds the `fields` values, not the scope. |
| 3588 | |
| 3589 | **Why this is a schema key and not a hook.** A duplicate check in a pre-write |
| 3590 | hook reads the collection, finds nothing and allows the write — but hooks run |
| 3591 | *before* the write lock, so two overlapping requests both find nothing and |
| 3592 | both land. A handler or scheduled job that asks ""have I done this already?"" |
| 3593 | before writing has the same gap, and never reaches a hook at all. This is how |
| 3594 | one usage event was billed twice, one wallet top-up credited twice and one |
| 3595 | setting configured twice. `unique` is checked by `object_records` under the |
| 3596 | same lock that performs the append, so the second writer sees the first one's |
| 3597 | row. It applies to **every writer**: HTTP, MCP, handlers, the daemon, imports, |
| 3598 | seeds. There is no bypass flag. |
| 3599 | |
| 3600 | **What a violation looks like.** Nothing is written and no change-log entry |
| 3601 | is made. |
| 3602 | |
| 3603 | - From `object_records.create_collection_record` / `update_collection_record`: |
| 3604 | `object_records.UniqueConstraintError` (a `ValueError`), with `.collection`, |
| 3605 | `.fields`, `.scope` and `.existing_id` — the record that holds the key. A |
| 3606 | storage-level writer that must be idempotent catches it and treats it as |
| 3607 | ""already done"": |
| 3608 | |
| 3609 | ```python |
| 3610 | try: |
| 3611 | object_records.create_collection_record(""wallet_entries"", entry, base_dir=base, actor=ACTOR) |
| 3612 | except object_records.UniqueConstraintError: |
| 3613 | return {""status"": ""already_posted""} # the marker was used; post nothing |
| 3614 | ``` |
| 3615 | |
| 3616 | - Over HTTP: **409** with `""code"": ""unique_violation""` and the constraint's |
| 3617 | `fields` and `scope`. The id of the record that holds the key is *not* |
| 3618 | returned — the caller may not be allowed to read it. |
| 3619 | |
| 3620 | **Updates.** An update is checked only for a key it *changes*. A record may |
| 3621 | keep its own key and change anything else. |
| 3622 | |
| 3623 | **Data that was already there.** Declaring a constraint over a collection |
| 3624 | that already holds duplicates does not remove them and does not fail. The |
| 3625 | existing records stay and stay editable; no *further* holder of that key is |
| 3626 | admitted, and deleting one duplicate does not free a key another still holds. |
| 3627 | `object_records.find_unique_violations(collection, base_dir=...)` lists them |
| 3628 | (`[{""fields"", ""scope"", ""values"", ""ids""}]`) — run it before declaring a |
| 3629 | constraint, and merge or delete what it reports. |
| 3630 | |
| 3631 | **What is refused at schema load** (a `ValueError`, so an unenforceable |
| 3632 | constraint never loads as ""no constraint""): an entry that is not an object (a |
| 3633 | bare list of names is ambiguous — one compound key, or several?), unknown |
| 3634 | keys, `id`, a `computed` field, a `store: extra` field, a field named twice. |
| 3635 | A field does not have to be declared in `fields` to be constrained. |
| 3636 | |
| 3637 | **Cost.** Collections without `unique` pay one cached schema lookup per |
| 3638 | write. A constrained collection keeps an in-memory index of who holds each |
| 3639 | key; it is built once (one pass over the cached rows) and then updated by |
| 3640 | each write, so a write costs a dictionary lookup, not a scan. Measured at |
| 3641 | 100,000 rows in append mode, three runs of 200 creates: 1.2–1.4 ms per create |
| 3642 | without a constraint, 1.25–1.5 ms with one; the one write that builds the |
| 3643 | index took about 170 ms longer, most of it reading the file because the |
| 3644 | collection was cold. The index is rebuilt after anything else changes the file — |
| 3645 | another process's write, a compaction, a restore — so several processes |
| 3646 | taking turns writing one collection each pay a rebuild per turn. A collection |
| 3647 | too large for the records cache still holds its keys in memory. |
| 3648 | |
| 3649 | **What it does not do.** It compares stored values for equality. It cannot |
| 3650 | express ""one *received* payment per order"" (a conditional key) or ""amounts |
| 3651 | must not exceed a ceiling"" (a sum). `unique` is not exposed by `/api/schema`. |
| 3652 | |
| 3653 | **A ceiling is not a `unique` key.** ""Payments must not exceed the |
| 3654 | invoice"", ""refunds must not exceed the payment"" are sums over rows that |
| 3655 | several writers add to, with inputs in other collections. `payments.v3` and |
| 3656 | `refunds.v3` approximated it with a per-parent sequence number declared |
| 3657 | `unique` (each hooked writer stamped the next number from the read it |
| 3658 | summed), which serialized writers that came through the hook and nobody |
| 3659 | else: a webhook's payment carried no number, an admin's edit kept its old |
| 3660 | one, and an invoice line cut in the meantime was not seen. Declare a |
| 3661 | ceiling as a [locked check](#locked-checks--a-decision-across-collections-made-inside-the-write-lock) |
| 3662 | instead; it holds for every writer and for inputs in other collections. |
| 3663 | The v3 columns `invoice_seq` / `payment_seq` remain as data, unconstrained |
| 3664 | and no longer stamped. |
| 3665 | |
| 3666 | ## Locked when settled — declared in the schema, enforced inside the write lock |
| 3667 | |
| 3668 | ```json |
| 3669 | { |
| 3670 | ""name"": ""time_logs"", |
| 3671 | ""locked_when"": [ |
| 3672 | {""when"": {""status"": [""approved"", ""billed""]}, |
| 3673 | ""except"": [""status"", ""invoice_id"", ""notes""], |
| 3674 | ""message"": ""Approved time is settled. Correct it with a new entry.""} |
| 3675 | ], |
| 3676 | ""fields"": [ ... ] |
| 3677 | } |
| 3678 | ``` |
| 3679 | |
| 3680 | Each rule says: while the **stored** record has `when`, an update may change |
| 3681 | only the `except` fields, and the record cannot be deleted. Or, written the |
| 3682 | other way round with `fields`, an update may change anything **but** the |
| 3683 | listed fields (below). |
| 3684 | |
| 3685 | | key | meaning | |
| 3686 | |---|---| |
| 3687 | | `when` | Required, at least one field. `{field: value}` or `{field: [values]}`; the rule applies when *every* named field holds one of its values (compared exactly, as stored). | |
| 3688 | | `except` | Optional, default `[]`. The fields an update may still change while the rule applies. Everything else is frozen — including fields added to the schema later, and fields the schema does not declare. | |
| 3689 | | `fields` | Optional, instead of `except`. The only fields the rule freezes while it applies; every other field, including ones added to the schema later, stays editable. A non-empty list of declared fields, never `id`. A rule that names both `except` and `fields` is refused when the schema loads, as is an empty list or a name the schema does not declare (a typo would leave the field editable, the unsafe direction). | |
| 3690 | | `allow_delete` | Optional, default `false`. `true` freezes the fields but still lets the record be deleted. | |
| 3691 | | `message` | Optional. The error text for a refusal, in place of the generated sentence. | |
| 3692 | |
| 3693 | Which form to use: `except` is the safe default for a record that is *money or |
| 3694 | evidence* (a new field is frozen until someone decides otherwise). `fields` is |
| 3695 | for a record that is mostly still alive once settled, where only a few fields |
| 3696 | are the settled fact: |
| 3697 | |
| 3698 | ```json |
| 3699 | {""when"": {""status"": [""won"", ""lost""]}, |
| 3700 | ""fields"": [""title"", ""description"", ""amount_cents""], |
| 3701 | ""message"": ""A settled deal's title, description and amount are frozen.""} |
| 3702 | ``` |
| 3703 | |
| 3704 | The two forms are judged the same way in everything below, inside the same |
| 3705 | lock, for every writer; only the question ""is this field frozen?"" differs. |
| 3706 | `allow_delete` is independent of the form and defaults to `false`: a settled |
| 3707 | record cannot be deleted whichever fields are frozen. A refusal is `409 |
| 3708 | record_locked` with `fields` naming the frozen fields the write tried to |
| 3709 | change (`[]` for a delete), and a `message` becomes its `error`. |
| 3710 | |
| 3711 | How a write is judged: |
| 3712 | |
| 3713 | - **By the stored record, not by what the write would produce.** The write |
| 3714 | that moves a draft to `approved` may change anything — the stored row is a |
| 3715 | draft. A write to an approved row may change only the `except` fields, even |
| 3716 | if it also moves the row out of `approved`: unlocking and editing take two |
| 3717 | writes. |
| 3718 | - **A change is a submitted field whose value would differ.** Sending a frozen |
| 3719 | field back unchanged is fine (a form posts everything it shows). |
| 3720 | - **Computed and read-only fields are never frozen.** A client cannot submit |
| 3721 | either; what changes them is the server — a rollup recomputed on a posted |
| 3722 | journal, a trusted writer's stamp. |
| 3723 | - **Every matching rule applies**, and each can only restrict. |
| 3724 | - **Nobody is exempt**: not the owner, not an admin, not the admin token, not |
| 3725 | a storage-level writer, and there is no bypass argument. A trusted writer |
| 3726 | that must touch a settled record (the invoice generator moving `approved` to |
| 3727 | `billed` and stamping `invoice_id`) does it through the `except` fields. |
| 3728 | - **Creates are not affected**: a record may be created already in the state. |
| 3729 | |
| 3730 | **The state field decides whether the lock can be left.** Put the field that |
| 3731 | `when` tests in `except` and the `transitions` map decides which moves out of |
| 3732 | the state are legal; leave it out and the state is terminal. |
| 3733 | |
| 3734 | **Why this is a schema key and not a hook.** Three hooks each carried their |
| 3735 | own `_ALLOWED_AFTER_…` set (time logs, expenses, scans), which is the point |
| 3736 | [`logic-decisions.md`](/docs/logic-decisions) #5 said to promote the pattern. |
| 3737 | They also shared three gaps a hook cannot close: the hook did not run on |
| 3738 | delete, so the frozen record could be removed; the hook reads the record |
| 3739 | *before* the write lock, so an edit that overlaps the approval is checked |
| 3740 | against the draft and written onto the approved row; and storage-level |
| 3741 | writers never reach a hook. `locked_when` is checked by `object_records` |
| 3742 | against the row read under the lock. |
| 3743 | |
| 3744 | **What a refusal looks like.** Nothing is written and no change-log entry is |
| 3745 | made. |
| 3746 | |
| 3747 | - From `object_records.update_collection_record` / `delete_collection_record`: |
| 3748 | `object_records.RecordLockedError` (a `ValueError`), with `.collection`, |
| 3749 | `.record_id`, `.action` (`""update""` or `""delete""`), `.fields` (the frozen |
| 3750 | fields the update tried to change; `[]` for a delete) and `.when`. |
| 3751 | - Over HTTP: **409** with `""code"": ""record_locked""` and `fields`. |
| 3752 | |
| 3753 | **What it does not do.** It reads one record. It cannot freeze a journal's |
| 3754 | *lines* because the *journal* is posted — that rule is about another |
| 3755 | collection, and stays in the line's hook (`hook_fin_journal_lines`, where it |
| 3756 | is advisory against a concurrent post, and where it has to ask about the |
| 3757 | journal a line is *leaving* as well as the one it joins: a hook that read |
| 3758 | only the new `journal_id` let a line be moved out of a posted journal). |
| 3759 | Retention pruning (`prune_collection_records`) rewrites the file rather than |
| 3760 | deleting row by row, so it cannot apply the rule per record; it refuses a |
| 3761 | collection that declares `locked_when` outright (its one caller ages out |
| 3762 | `page_views`, which declares none). `locked_when` is not exposed by `/api/schema`, |
| 3763 | so the generated form does not yet grey out frozen fields; it learns from the |
| 3764 | 409. |
| 3765 | |
| 3766 | ## Locked checks — a decision across collections, made inside the write lock |
| 3767 | |
| 3768 | ```json |
| 3769 | { |
| 3770 | ""name"": ""payments"", |
| 3771 | ""locked_checks"": [ |
| 3772 | {""name"": ""overpayment"", |
| 3773 | ""object"": ""hook_payments"", |
| 3774 | ""function"": ""LOCKED_CHECK"", |
| 3775 | ""reads"": [""invoices"", ""invoice_lines"", ""refunds"", ""app_settings""], |
| 3776 | ""lock"": ""ledger"", |
| 3777 | ""on"": {""create"": true, ""update"": [""amount_cents"", ""invoice_id"", ""status""], ""delete"": true}} |
| 3778 | ], |
| 3779 | ""fields"": [ ... ] |
| 3780 | } |
| 3781 | ``` |
| 3782 | |
| 3783 | Each entry says: before any write that `on` selects lands in this |
| 3784 | collection, call `function` of the installed object `object`, holding the |
| 3785 | named `lock`, and do not write unless it allows. `unique` and `locked_when` |
| 3786 | are rules about one collection; a locked check is for the rule that needs |
| 3787 | rows from **other** collections — a sum against a ceiling (""payments on an |
| 3788 | invoice do not exceed what the invoice is worth""), a headroom (""refunds do |
| 3789 | not exceed the payment""), a parent that must still be in a state. |
| 3790 | |
| 3791 | | key | meaning | |
| 3792 | |---|---| |
| 3793 | | `object` | Required. The installed object that ships the check (usually the collection's hook object). | |
| 3794 | | `function` | Optional, default `LOCKED_CHECK`. A function of that object, not one of its request verbs (`GET`, `POST`, …) or `BEFORE_WRITE` — those are refused at schema load. | |
| 3795 | | `name` | Optional, default the object id. Named in errors (`check`) and in the 409. Unique within the schema. | |
| 3796 | | `reads` | Collections the check reads besides this one. **Every write to them takes the lock too** — that is what holds them still. List every collection whose rows the verdict depends on. | |
| 3797 | | `lock` | Optional, default this collection's name. A lock name (`[a-z0-9_]+`). Checks that read each other's collections should share one (`payments` and `refunds` both use `ledger`). | |
| 3798 | | `on` | Optional, default all three. `create` / `delete`: `true` or `false`. `update`: `true` (any field changes), `false`, or a list of fields — the check runs only when a write changes one of them. | |
| 3799 | |
| 3800 | Unknown keys, a misspelled collection in `reads`, an `on` that selects |
| 3801 | nothing: refused at schema load (a `ValueError`), so a check that cannot be |
| 3802 | enforced never loads as ""no check"". Not exposed by `/api/schema`. |
| 3803 | |
| 3804 | **Why a declaration and a function, not a declarative sum.** The owner |
| 3805 | prefers configuration, and `""ceilings"": [{""sum"": ..., ""group_by"": ..., |
| 3806 | ""max_from"": ...}]` was the first candidate. It cannot state the ceilings |
| 3807 | that ship: the overpayment ceiling is the smaller of the invoice's stamped |
| 3808 | total and what its lines say (subtotal by `object_lines`, plus the larger of |
| 3809 | line and document tax), and the refund headroom is the payment's amount net |
| 3810 | of the *other* refunds, refused outright for a bounced payment. A |
| 3811 | declarative form would need an expression language to say that, or it would |
| 3812 | change what the ceiling is computed from. So the *locking* is declared — |
| 3813 | which collections, which lock, which writes — and the *verdict* is a named, |
| 3814 | read-only function the package ships beside its hook, sharing the hook's |
| 3815 | code so the early answer and the locked answer cannot drift. |
| 3816 | |
| 3817 | **When it runs.** `object_records.create/update/delete_collection_record` |
| 3818 | call it for every writer — HTTP and MCP, actions, handlers, webhooks, the |
| 3819 | daemon, imports (`object_import`), materialize, merged seeds — after schema |
| 3820 | validation, transitions, `locked_when` and `unique`, and before anything is |
| 3821 | written. There is no bypass argument. Its request: |
| 3822 | |
| 3823 | | key | create | update | delete | |
| 3824 | |---|---|---|---| |
| 3825 | | `record` | the row to be stored | the stored row with the changes applied | the row being removed | |
| 3826 | | `existing` | `None` | the stored row, read **under the lock** | the same row | |
| 3827 | | `collection`, `action`, `check`, `reads`, `base_dir` | | | | |
| 3828 | |
| 3829 | There is no `subject`: a locked check states a fact about the data, not a |
| 3830 | permission. Who may do what stays in the hook. |
| 3831 | |
| 3832 | **What it answers.** `None` (or `{}`) allows. `{""error"": ""..."", ""status"": |
| 3833 | 409}` refuses (any 4xx; the default is 409); `{""error"": ..., ""status"": |
| 3834 | 503}` says it could not decide. Anything else is a broken check. |
| 3835 | |
| 3836 | | outcome | `CheckRefusedError` `.status` / `.code` | over HTTP | |
| 3837 | |---|---|---| |
| 3838 | | the check refused | 409 (or its 4xx) / `check_refused` | 409 `{""code"": ""check_refused"", ""check"": name, ""error"": its sentence}` | |
| 3839 | | it said 503, raised, is not installed, or its lock was not free within `DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS` (default 30) | 503 / `check_unavailable` | 503 — retry | |
| 3840 | | it answered outside the contract, or tried to write or to run another object | 500 / `check_failed` | 500 | |
| 3841 | |
| 3842 | Nothing is written and no change-log entry is made in any of these. |
| 3843 | `CheckRefusedError` is a `ValueError` (like `UniqueConstraintError`), with |
| 3844 | `.collection`, `.check`, `.status`, `.code`. A storage-level writer that |
| 3845 | records money which has already moved must decide what a refusal means for |
| 3846 | it — the Stripe webhook answers 409 with `needs_attention` (not |
| 3847 | acknowledged, so Stripe redelivers once a person makes room); checkout's |
| 3848 | gift-card payment reverses the wallet debit it just made. |
| 3849 | |
| 3850 | **What a check may do.** Read, through `object_records`, and decide. It |
| 3851 | runs holding locks other writers wait on, so: |
| 3852 | |
| 3853 | - it may not write (`create/update/delete_collection_record`, retention) |
| 3854 | or run another object (`object_execution.execute_object`) — both raise |
| 3855 | `LockedCheckWriteError`, answered 500, nothing written; |
| 3856 | - it must fail closed on a read it cannot make: return 503, or let the |
| 3857 | exception escape (also 503) — never treat ""unreadable"" as ""nothing |
| 3858 | there""; |
| 3859 | - it should be quick: its cost is paid inside the lock by every writer of |
| 3860 | every collection the lock covers. A check that hangs makes the others |
| 3861 | time out with 503 after `DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS` rather than |
| 3862 | wait forever; the platform does not interrupt the check itself. |
| 3863 | |
| 3864 | **The lock, and why it cannot deadlock.** A check lock is an `flock` on |
| 3865 | `<data>/.locks/<lock>.lock`, so it holds across threads and processes like |
| 3866 | the collection file locks. The rules: |
| 3867 | |
| 3868 | 1. A write plans its locks **before taking any**: every lock whose check is |
| 3869 | declared on, or reads, the collection it writes — plus those of the |
| 3870 | collections its rollups refresh, because that refresh writes them while |
| 3871 | this write's file lock is held. |
| 3872 | 2. It takes those check locks **in sorted order**, then its collection file |
| 3873 | lock. A lock this thread already holds is not taken again (a rollup |
| 3874 | refresh nested in a write finds its locks held). |
| 3875 | 3. A thread **never waits for a check lock while holding a file lock**. If a |
| 3876 | nested write needs one it does not hold (only possible if the schemas |
| 3877 | changed between the outer write's plan and the inner write), it gets |
| 3878 | `CheckLockOrderError` instead; a rollup refresh is best-effort and skips. |
| 3879 | |
| 3880 | So a thread waiting for a check lock holds only check locks that sort |
| 3881 | before it and no file lock, and a thread waiting for a file lock already |
| 3882 | holds every check lock it will ever take in that write. Waits among check |
| 3883 | locks follow one total order (no cycle); no thread holding a file lock waits |
| 3884 | on a check lock (no cycle through both kinds); waits among file locks are |
| 3885 | the existing child → rollup-parent order, unchanged. Multiple named locks are |
| 3886 | supported and tested (a write to a collection two checks read takes both). |
| 3887 | |
| 3888 | What the lock buys and costs: every write to a covered collection waits for |
| 3889 | any other covered write in flight — for payments that is every write to |
| 3890 | payments, refunds, invoices, invoice lines and settings, one at a time, |
| 3891 | for the length of one check and one append. It is one lock per name, not |
| 3892 | one per invoice; the ledger's writes are few and short, and a per-key lock |
| 3893 | would need the key of every input (a line's invoice, a refund's payment's |
| 3894 | invoice, both sides of a re-point) to be planned before the write, which a |
| 3895 | name does not. |
| 3896 | |
| 3897 | **Nobody routes around it.** |
| 3898 | |
| 3899 | - Every storage write goes through the three functions above. |
| 3900 | - Retention (`prune_collection_records`) refuses a collection a check is |
| 3901 | declared on or reads, as it refuses one with `locked_when`. |
| 3902 | - A package's seed into a collection that already has records is merged row |
| 3903 | by row through `create_collection_record` (checked, as before); a |
| 3904 | **fresh** seed is normally a byte copy, but into a collection that |
| 3905 | declares a locked check it is written row by row as well, and refused |
| 3906 | rows are listed in the install result (`code: check_refused`). |
| 3907 | - `compact_collection` rewrites a file without changing what it holds and |
| 3908 | takes no check lock. A backup **restore** replaces files wholesale, as it |
| 3909 | does for `unique` and `locked_when`: it is an operator's act on a stopped |
| 3910 | or quiet server, not a writer. |
| 3911 | - A server running code from before this key ignores it (unknown root keys |
| 3912 | are dropped at schema load), as it would ignore `unique`. |
| 3913 | |
| 3914 | **Cost.** Collections no check covers pay one look at the schema index |
| 3915 | (already made for rollups; shared). A covered write pays one `flock` round |
| 3916 | trip (open, lock, unlock, close) and waits for other covered writes; a write |
| 3917 | the check is selected for also pays the check's reads, inside the lock. Measured on one machine, append mode, |
| 3918 | storage-level creates, median of 200 (50 at 100,000 rows); ""rows"" is the |
| 3919 | number of payments, with a tenth as many invoices and refunds and a fifth |
| 3920 | as many invoice lines: |
| 3921 | |
| 3922 | | write | 1,000 rows: without / with the declaration | 100,000 rows: without / with | |
| 3923 | |---|---|---| |
| 3924 | | a collection nothing covers (vs 246b3e5, before the mechanism) | 0.68 / 0.68 ms | 2.50 / 2.50 ms | |
| 3925 | | `invoice_lines` create (takes the `ledger` lock, not checked) | 1.27 / 1.32 ms | 41.8 / 39.3 ms | |
| 3926 | | `payments` create (takes the lock, runs `overpayment`) | 2.37 / 3.06 ms | 133.8 / 143.4 ms | |
| 3927 | |
| 3928 | The check costs about 0.7 ms at 1,000 payments and 10 ms at 100,000 (it |
| 3929 | reads one invoice's payments, refunds and lines through |
| 3930 | `read_collection_records_where`; the field index it uses is rebuilt after |
| 3931 | each write to the collection). Most of a payment write at 100,000 rows is |
| 3932 | not the check: it is the `invoices` rollup refresh, which reads every |
| 3933 | payment, and was there before. |
| 3934 | |
| 3935 | **Shipped:** `payments.overpayment` (`hook_payments.LOCKED_CHECK`) and |
| 3936 | `refunds.refundable` (`hook_refunds.LOCKED_CHECK`), both on the `ledger` |
| 3937 | lock; `fin_journals.closed_period` and `fin_journal_lines.closed_period` |
| 3938 | (`hook_fin_journals` / `hook_fin_journal_lines.LOCKED_CHECK`) on the |
| 3939 | `fin_periods` lock, reading `fin_closed_periods` -- nothing is written, |
| 3940 | edited, moved or deleted in a closed period by any writer. That rule had |
| 3941 | lived in the two hooks, and every journal composer writes below them, so |
| 3942 | a payment recorded after its month was closed posted into the closed |
| 3943 | month. What a composer does instead is `object_finance. |
| 3944 | compose_posted_journal`'s policy: the first open day after the period, |
| 3945 | with `occurred_on` and `period_review=pending` saying so |
| 3946 | (`tests/test_closed_period_composers.py`). Tests: `tests/test_locked_checks.py` (the mechanism, on a toy |
| 3947 | package: every writer, every failure mode, the lock order, six processes |
| 3948 | writing every covered collection in random order), |
| 3949 | `tests/test_money_gates_locked_ceilings.py` and |
| 3950 | `tests/test_money_gates_ceiling_races.py` (the money). Also `expenses.category_stamps` (`hook_expenses`, reading |
| 3951 | `expense_categories`: an expense's stamped requirements and deductible share |
| 3952 | must be what its category says when it is created, recategorised, submitted |
| 3953 | or approved), `mileage_logs.mileage_rules` (`hook_mileage_logs`, reading |
| 3954 | `mileage_rates` and `vehicles` and the other trips on the vehicle: no |
| 3955 | backwards or overlapping odometer readings, no approval at a rate other than |
| 3956 | the year's) and `fringe_benefits.fringe_period`; see |
| 3957 | `expense-substantiation.md`. |
| 3958 | |
| 3959 | ## Pre-write hooks — code inside the write path |
| 3960 | |
| 3961 | For rules the schema can't express, a collection declares a **hook object**: |
| 3962 | |
| 3963 | ```json |
| 3964 | { ""name"": ""fin_journals"", ""hooks"": { ""before_write"": ""hook_fin_journals"" } } |
| 3965 | ``` |
| 3966 | |
| 3967 | The object's `BEFORE_WRITE(request)` runs **synchronously inside the generic |
| 3968 | HTTP write path** — after permission checks, before persist — for every public |
| 3969 | create, update **and delete** on that collection. `request` carries |
| 3970 | `{collection, action, record, existing, changes, subject}`. It returns `None` |
| 3971 | to allow, `{""error"": ""..."", ""status"": 4xx}` to reject with its own message, or |
| 3972 | `{""record"": {...}}` to transform (the transformed record still passes full |
| 3973 | schema validation, and can never touch `id`, `owner_id`, or read-only/computed |
| 3974 | fields). |
| 3975 | |
| 3976 | What the request holds depends on `action`: |
| 3977 | |
| 3978 | | `action` | `existing` | `record` | `changes` | may answer | |
| 3979 | |---|---|---|---|---| |
| 3980 | | `""create""` | `None` | the row to be written | the same row | allow, reject, transform | |
| 3981 | | `""update""` | the stored row before this write | that row with the caller's changes applied | only what the caller sent | allow, reject, transform | |
| 3982 | | `""delete""` | the row about to be removed | the same row | `{}` | allow, reject | |
| 3983 | |
| 3984 | `subject` is `{""user_id"": ..., ""roles"": [...]}` in all three. |
| 3985 | |
| 3986 | **Branch on `action` first.** A hook is called for all three and every rule in |
| 3987 | it has to say which it is about. The delete path ran no hook until a review |
| 3988 | found that ""approved time is frozen"" stopped an edit and not a `DELETE`; when |
| 3989 | deletes started arriving, two shipped hooks that decided ""is this being |
| 3990 | approved?"" from the record's status mistook the removal of an approved row for |
| 3991 | an approval, and answered with the self-approval refusal. A hook that has no |
| 3992 | rule about deletes starts with |
| 3993 | `if request[""action""] not in (""create"", ""update""): return None`. |
| 3994 | |
| 3995 | A delete cannot be transformed — there is nothing to persist — so a hook that |
| 3996 | answers one with `{""record"": ...}` is treated as broken (`500`, nothing |
| 3997 | deleted), like any other answer outside the contract. |
| 3998 | |
| 3999 | `existing` is read before the write lock is taken, so everything a hook checks |
| 4000 | is advisory against a concurrent writer: two requests can both pass the same |
| 4001 | hook and both write. A hook is the right place for a rule about one request; |
| 4002 | it cannot make a rule hold under a race. ""This value appears once"" is declared |
| 4003 | as `unique` (above) and enforced inside the lock; ""this sum stays under what |
| 4004 | another collection says"" is a `locked_checks` entry (above), whose function |
| 4005 | the hook can share so its early answer and the locked one agree; ""this record |
| 4006 | has not changed since I read it"" is `If-Match` / `expected_rev`. |
| 4007 | |
| 4008 | The contract is deliberately strict: |
| 4009 | |
| 4010 | - **Fail closed** — a declared hook that is missing, raises, or returns a |
| 4011 | non-contract shape rejects the write. A gate that silently passes on error |
| 4012 | is not a gate. |
| 4013 | - **Every surface that writes on a caller's behalf** — the collection routes, |
| 4014 | MCP's record tools (which call them), and the file routes (`/api/files`, |
| 4015 | WebDAV), which create and delete `files` records through their own helpers |
| 4016 | and ask the `files` hook the same way. |
| 4017 | - **A gate's own reads fail closed too.** A hook that reads other records to |
| 4018 | decide must not treat ""I could not read"" as ""nothing there"". Five shipped |
| 4019 | gates did, and with the ledger unreadable the duplicate gate passed the |
| 4020 | duplicate. `object_records.read_collection_records` raises on a failed |
| 4021 | read; what a gate may fold to ""no rows"" is only a collection that is *not |
| 4022 | installed*, which is a fact rather than an unknown: |
| 4023 | |
| 4024 | ```python |
| 4025 | try: |
| 4026 | rows = object_records.read_collection_records(""refunds"", base_dir=base) |
| 4027 | except object_collections.CollectionNotFoundError: |
| 4028 | rows = [] # app-payments' refunds not installed: none exist |
| 4029 | except Exception: |
| 4030 | return {""error"": ""Refund history is unreadable; refusing to record "" |
| 4031 | ""against an unknown history."", ""status"": 503} |
| 4032 | ``` |
| 4033 | |
| 4034 | A hook that simply lets the exception escape is also closed (`500 |
| 4035 | hook_failed`, no write); returning its own `503` just says why. The shared |
| 4036 | readers gates call take `strict=True` for the same behaviour — |
| 4037 | `object_banking.existing_line_keys`, `is_duplicate_line`, |
| 4038 | `find_import_by_file_hash`, `previous_import`, `run_gates`, and |
| 4039 | `object_finance.closed_period_for` — and are lenient by default only |
| 4040 | until each caller is moved over. Moved so far: both bank statement |
| 4041 | importers (every gate read strict; an import that fails part-way is |
| 4042 | resumed by re-importing the file), `action_reverse_journal`'s |
| 4043 | closed-period check, and the hooks that gate on these reads |
| 4044 | (`hook_bank_lines`, `hook_fin_journals`, `hook_fin_journal_lines`). |
| 4045 | |
| 4046 | The server relays a hook's status when it is a 4xx or `503` |
| 4047 | (`_apply_before_write_hook`); anything else a refusing hook returns |
| 4048 | reaches the client as `400`. So ""I could not read"" arrives as something |
| 4049 | to retry, not as a bad request, and a hook still cannot call a refused |
| 4050 | write a success or a server fault of its own. |
| 4051 | - **After permissions** — a denied subject never reaches the hook. |
| 4052 | - **Opt-in per collection** — collections without `hooks` pay one cached dict |
| 4053 | lookup; the original latency concern that deferred this feature |
| 4054 | ([`event-hooks-decisions.md`](/docs/event-hooks-decisions)) stays bounded. |
| 4055 | - **Public surface only** — trusted server-side writers (the daemon, |
| 4056 | migrations, seed-merge) call the storage layer directly and bypass hooks. |
| 4057 | |
| 4058 | This is what keeps the generative form working when custom logic arrives: the |
| 4059 | form still POSTs to `/collections/{c}/records`; the rule lives server-side. |
| 4060 | First adopter: `fin_journals` refuses to post a journal whose lines don't |
| 4061 | balance — a cross-collection rule (it sums `fin_journal_lines`) no schema key |
| 4062 | could express. |
| 4063 | |
| 4064 | ## Business logic — the automation substrate |
| 4065 | |
| 4066 | Business rules run without per-app code through a set of declarative |
| 4067 | primitives, driven by a background daemon and the change log: |
| 4068 | |
| 4069 | ```mermaid |
| 4070 | flowchart LR |
| 4071 | W[""record write""] --> CL[""change log""] |
| 4072 | CL --> DAEMON[""daemon: poll triggers""] |
| 4073 | DAEMON --> NOTIFY[""notify_rules → notification / email""] |
| 4074 | DAEMON --> TARGET[""trigger object → target object""] |
| 4075 | W --> TRANS[""transition guards (flow: when clauses)""] |
| 4076 | SCHED[""schedule""] --> DAEMON |
| 4077 | DAEMON --> COMPUTE[""computed / materialize fields""] |
| 4078 | DAEMON --> CONN[""connectors → external systems + reconcile""] |
| 4079 | ``` |
| 4080 | |
| 4081 | - **Transitions with guards** — a `flow`/`transitions` map is a conditional |
| 4082 | state machine; a `when` clause gates whether a move is allowed. The board's |
| 4083 | drag and every status write run through it. |
| 4084 | - **notify_rules** — declarative ""a record changed → send a notification / |
| 4085 | email."" Data, not code. |
| 4086 | - **Trigger → target objects** — the daemon polls trigger objects and executes |
| 4087 | target objects: the event-handler path (see |
| 4088 | `runtime-contract.md` and |
| 4089 | [`event-hooks-decisions.md`](/docs/event-hooks-decisions)). |
| 4090 | - **Computed / materialized fields** — derived values (`type: computed`, |
| 4091 | `materialize_definitions`). |
| 4092 | - **Connectors** — external side effects expressed as desired-state records |
| 4093 | with a reconcile pass. |
| 4094 | - **Scheduled passes** — the daemon runs periodic work (compaction, |
| 4095 | auto-transitions). |
| 4096 | |
| 4097 | This is the same family as Salesforce flows/validation-rules, Hasura event |
| 4098 | triggers, and Directus Flows — declarative automation over a data store, here |
| 4099 | on plain-text records. |
| 4100 | |
| 4101 | ### Formula & rollup fields — shipped |
| 4102 | |
| 4103 | The spreadsheet feature, on collections. A `type: computed` field declares |
| 4104 | either a **formula** over sibling fields or a **rollup** over a child |
| 4105 | collection: |
| 4106 | |
| 4107 | ```json |
| 4108 | {""name"": ""full_name"", ""type"": ""computed"", |
| 4109 | ""formula"": ""first_name + \"" \"" + last_name""} |
| 4110 | |
| 4111 | {""name"": ""debit_total_cents"", ""type"": ""computed"", |
| 4112 | ""rollup"": {""collection"": ""fin_journal_lines"", ""fk_field"": ""journal_id"", |
| 4113 | ""op"": ""sum"", ""field"": ""debit_cents""}} |
| 4114 | ``` |
| 4115 | |
| 4116 | Values are **materialized on write at the storage layer** — stored in the TSV, |
| 4117 | recomputed whenever inputs change (formulas on writes of the record itself; |
| 4118 | rollups when source-collection records are created, updated, or deleted — |
| 4119 | single-hop, loop-guarded). Because the value is stored, every surface works |
| 4120 | with zero changes: lists, tables, detail, search, `field=value` filters, sort, |
| 4121 | CSV, backups — and **realtime falls out free**: edit a journal line and the |
| 4122 | journal's totals update live in every open browser. `rollup.op` is |
| 4123 | `sum | count | min | max | avg`, with an optional equality `where`. The |
| 4124 | formula language is a tiny safe expression grammar (fields, strings, numbers, |
| 4125 | `+ - * /`, parens, `round(x[, places])` and `floor(x)` — never Python |
| 4126 | eval). Numbers are exact: whole numbers are integers of any size, fractions |
| 4127 | are Decimal, never float. A formula over whole numbers only fills an integer |
| 4128 | field, so a division in it is rounded half-up once at the end |
| 4129 | (`1234 * 825 / 10000` is 102); one with a fractional operand keeps its |
| 4130 | fraction. Rollups sum the same way. A broken formula stores an empty value |
| 4131 | and never fails the write — derived values are non-authoritative, the opposite |
| 4132 | posture of hooks. Definition changes are backfilled explicitly with |
| 4133 | `object_records.recompute_computed_fields(collection)` (install step, admin |
| 4134 | action, or cron — never a runtime loop). |
| 4135 | |
| 4136 | Finding a written collection's rollup parents happens after the row has |
| 4137 | landed, so it is best-effort like the refresh: a schema file in |
| 4138 | `<data>/schemas/` that does not load (invalid JSON, a name outside the |
| 4139 | schema-name rules) is skipped, exactly as the check-lock plan skips it, and |
| 4140 | the write is answered as written. Writes to that file's own collection are |
| 4141 | refused before anything is written, since its schema is what they validate |
| 4142 | against. A rollup the broken file declares is not refreshed while it is |
| 4143 | broken — nobody can read the declaration — so its parent rows are stale until |
| 4144 | the file is fixed and then either a child of that parent is written again |
| 4145 | (the refresh recomputes from every child) or |
| 4146 | `recompute_computed_fields(<parent>)` is run. The broken file itself is what |
| 4147 | to look for: `GET /schemas/<name>` answers its error. |
| 4148 | |
| 4149 | **Declarative validation rules** (cross-field formula + message) remain the |
| 4150 | natural next sugar over the hook. |
| 4151 | |
| 4152 | ## Related |
| 4153 | |
| 4154 | - [`business-logic-patterns.md`](/docs/business-logic-patterns) — WHERE each kind |
| 4155 | of rule goes (the placement flowchart) with worked examples; and |
| 4156 | [`logic-decisions.md`](/docs/logic-decisions), the doctrines behind placements. |
| 4157 | - [`schema-forms.md`](/docs/schema-forms) — the field contract these checks read. |
| 4158 | - `runtime-contract.md` — the daemon, triggers, |
| 4159 | schedules, and event contracts. |
| 4160 | - [`event-hooks-decisions.md`](/docs/event-hooks-decisions) — why event handlers |
| 4161 | are shaped the way they are. |
| 4162 | - [`storage-modes.md`](/docs/storage-modes) — append-only collections, the |
| 4163 | immutable substrate for audit-shaped data (journals, stock moves). |
| 4164 | " |
| 4165 | capabilities Capabilities: Per-Collection Behaviors, Declared Not Coded Building on DBBASIC 250 How the platform's capability layer lets any collection opt into comments, attachments, and sharing by declaring a flag instead of hand-building each behavior per app. "The schema-driven UI has two layers. The **display** layer turns a schema into |
| 4166 | a list, table, board, form, and detail page (see |
| 4167 | [`schema-forms.md`](/docs/schema-forms)). The **capability** layer sits on top of |
| 4168 | it: generic *behaviors* a collection opts into by declaring a flag, wired by the |
| 4169 | platform instead of hand-built per app. |
| 4170 | |
| 4171 | A collection declares them under a root-level `capabilities` key: |
| 4172 | |
| 4173 | ```json |
| 4174 | { |
| 4175 | ""name"": ""tasks"", |
| 4176 | ""capabilities"": { ""comments"": true, ""attachments"": true, ""shareable"": true }, |
| 4177 | ""fields"": [ ... ] |
| 4178 | } |
| 4179 | ``` |
| 4180 | |
| 4181 | and its detail page grows a comment thread, an attachment list, and a share |
| 4182 | control — with no per-view block and no per-app table. The same three flags on |
| 4183 | `contacts`, `invoices`, or any other collection give the same behaviors. |
| 4184 | |
| 4185 | This is the ""define once, project everywhere"" rule applied to what a record |
| 4186 | *does* and *connects to*, not just how it looks. It replaces the pattern where |
| 4187 | every app hand-rolled its own version of the same idea: comments existed four |
| 4188 | separate times (`task_comments`, `thread_comments`, `profile_comments`, |
| 4189 | `interactions`) before one `capabilities.comments` flag collapsed them. |
| 4190 | |
| 4191 | ## The model |
| 4192 | |
| 4193 | Each capability is one **polymorphic collection** (a row attaches to a record in |
| 4194 | *any* collection via a `parent_collection` + `parent_id` pair), one **widget** |
| 4195 | served as a static script like `/list` and `/form`, and one line in the detail |
| 4196 | renderer that mounts the widget when the flag is present. |
| 4197 | |
| 4198 | ```mermaid |
| 4199 | flowchart TD |
| 4200 | S[""schema.capabilities flag""] --> API[""/api/schema exposes it""] |
| 4201 | API --> VR[""view_render: maybeMountCapabilities()""] |
| 4202 | VR -->|flag present| W[""window.dbbasicThread / Attachments / Share .mount()""] |
| 4203 | W --> C[""polymorphic collection<br/>parent_collection + parent_id""] |
| 4204 | C -->|permission-checked read and write| STORE[""object store""] |
| 4205 | D[""detail block""] --> VR |
| 4206 | ``` |
| 4207 | |
| 4208 | The wiring is one function, `maybeMountCapabilities` in |
| 4209 | `app-views/objects/site/view_render.py`: it fetches the record's schema, reads |
| 4210 | `capabilities`, and mounts each declared widget into its own sub-element under |
| 4211 | the detail. Absent flag or unloaded widget → nothing renders, never an error. |
| 4212 | |
| 4213 | `capabilities` is whitelisted in schema normalization |
| 4214 | (`object_schemas.py`) and surfaced by `/api/schema` so the client can wire it — |
| 4215 | the same ""carried, not interpreted"" posture as `flow` and `blocks`. |
| 4216 | |
| 4217 | ## The three capabilities |
| 4218 | |
| 4219 | | Flag | Widget (route) | Backing collection | Package | |
| 4220 | |------|----------------|--------------------|---------| |
| 4221 | | `comments` | `window.dbbasicThread` (`/thread`) | `thread_comments` | `app-thread` | |
| 4222 | | `attachments` | `window.dbbasicAttachments` (`/attachments`) | `files` (+`parent_*`) | `app-files` | |
| 4223 | | `shareable` | `window.dbbasicShare` (`/share`) | `record_shares` | `app-share` | |
| 4224 | |
| 4225 | ### comments |
| 4226 | |
| 4227 | A comment thread for one record. Reads/writes `thread_comments` filtered to the |
| 4228 | `(parent_collection, parent_id)` pair, posts with a minimal payload (the server |
| 4229 | owns `created_at`; `owner_id` is set from the session and redacted from other |
| 4230 | readers, so each comment also stamps a display `author_name`), owner-only |
| 4231 | delete, and re-renders over the change log like every other surface. The |
| 4232 | widget shows only published comments (and the viewer's own); moderating them |
| 4233 | (publishing, flagging, removing) has no widget yet and is a `status` change |
| 4234 | over the record API by a user with the `moderator` role, who can change |
| 4235 | nothing else on someone else's comment and cannot moderate their own |
| 4236 | ([permissions-model.md, ""Comment moderation""](/docs/permissions-model#comment-moderation)); moderators find the pending |
| 4237 | ones listed at `/comments/pending`. |
| 4238 | |
| 4239 | ### attachments |
| 4240 | |
| 4241 | An upload/list/download/delete surface for files attached to one record. |
| 4242 | Uploads go multipart to `/api/files` — which owns `owner_id`/`size`/ |
| 4243 | `content_type` and saves the blob — carrying `parent_collection`/`parent_id` so |
| 4244 | the file lands on this record. Delete is blob-aware (`DELETE /api/files/{id}` |
| 4245 | removes the bytes *and* the metadata row; a plain record delete would orphan the |
| 4246 | blob). No per-collection foreign key on `files` is needed. |
| 4247 | |
| 4248 | ### shareable |
| 4249 | |
| 4250 | The foundational one — it changes the **permission check**, not just a widget. |
| 4251 | A record's owner grants other users read (or write) access to that individual |
| 4252 | record. See the security model below. |
| 4253 | |
| 4254 | ## Sharing: the security model |
| 4255 | |
| 4256 | Sharing is the one capability that grants access, so it is designed so that a |
| 4257 | grant can only ever *narrow* what a viewer could already reach, never widen it |
| 4258 | for the granter's own benefit. |
| 4259 | |
| 4260 | ```mermaid |
| 4261 | sequenceDiagram |
| 4262 | participant Owner |
| 4263 | participant API as /api/share |
| 4264 | participant Store as record_shares |
| 4265 | participant Grantee |
| 4266 | participant Engine as permission check |
| 4267 | |
| 4268 | Owner->>API: POST {collection, record_id, user_id} |
| 4269 | API->>API: does Owner own the TARGET record? |
| 4270 | Note right of API: cross-collection ownership check<br/>a row_filter cannot express |
| 4271 | API-->>Owner: 403 if not owner |
| 4272 | API->>Store: create grant (owner-only path) |
| 4273 | Grantee->>Engine: read record |
| 4274 | Engine->>Store: subject.shared_records[collection] |
| 4275 | Engine->>Engine: {id: $shared_records} row filter matches |
| 4276 | Engine-->>Grantee: allowed (only this record, only this collection) |
| 4277 | ``` |
| 4278 | |
| 4279 | Three properties make it safe: |
| 4280 | |
| 4281 | 1. **Grants are minted only by `/api/share`.** `record_shares` has *no* |
| 4282 | create/update/delete permission rule, so a raw collection write can't forge |
| 4283 | one. The endpoint authorizes each grant against the **target record's** |
| 4284 | `owner_id` — a cross-collection fact a row filter can't check. A non-owner |
| 4285 | gets `403 ""Only the record's owner can share it.""` |
| 4286 | 2. **Reads resolve through the subject.** Before a check runs, the server builds |
| 4287 | `subject.shared_records` (per collection) from `record_shares`, the same way |
| 4288 | it builds `project_ids` from `project_access`. A collection opts in with a |
| 4289 | `{""id"": ""$shared_records""}` read rule. |
| 4290 | 3. **`$shared_records` is collection-aware.** The collection being checked is |
| 4291 | threaded through `_record_matches_filter → _resolve_filter_value`, so a share |
| 4292 | on a *task* never matches a same-id row in another collection. (Covered by |
| 4293 | `test_shared_records_filter_is_collection_scoped`.) |
| 4294 | |
| 4295 | Revoking (`DELETE /api/share/{id}`) is allowed to the record's owner, the |
| 4296 | grant's granter or an admin. After that check it is a delete like any other |
| 4297 | (docs/dron-write-semantics.md, S30): a `before_write` hook declared on |
| 4298 | `record_shares` is asked, `locked_when` and `locked_checks` apply, a grant |
| 4299 | that changed since it was looked up is not removed (`409 conflict`, retry), |
| 4300 | and the change is published as a record change event. |
| 4301 | |
| 4302 | Verified end to end: a grantee reads a shared record (`200`), a non-grantee is |
| 4303 | denied (`403`), and a non-owner cannot create a grant (`403`). |
| 4304 | |
| 4305 | ## Adding a new capability |
| 4306 | |
| 4307 | The recipe, in order: |
| 4308 | |
| 4309 | 1. **A polymorphic collection** with `parent_collection` + `parent_id` (both |
| 4310 | *settable on create* — a field that is `required` **and** `read_only` can |
| 4311 | never be created through the HTTP write path, only a server-side |
| 4312 | `preserve_read_only` bypass). |
| 4313 | 2. **A widget** object at `site_{name}` serving `window.dbbasic{Name}` (public |
| 4314 | `execute` rule — it's a static script; the data it reads stays row-gated). |
| 4315 | 3. **Wire it** in `view_render`'s `maybeMountCapabilities` and add |
| 4316 | `<script src=""/{name}"">` to the view page. |
| 4317 | 4. **Adopt it** on a collection with `capabilities.{name}: true`. If the |
| 4318 | behavior grants access (like sharing), also add the permission rule. |
| 4319 | |
| 4320 | Leave `owner_id` to the server on create — a field with a `public: hidden` |
| 4321 | policy is server-set from the session and a client value is rejected. |
| 4322 | |
| 4323 | ## Related |
| 4324 | |
| 4325 | - [`schema-forms.md`](/docs/schema-forms) — the display layer (forms, views, list |
| 4326 | modes) capabilities sit on top of. |
| 4327 | - [`permissions-model.md`](/docs/permissions-model) — row/field filters, the |
| 4328 | `$`-variable row-filter language `$shared_records` extends, and sharing. |
| 4329 | - [`ui-decisions.md`](/docs/ui-decisions) — decisions #7–#14, the living log of the |
| 4330 | generative-UI and capability behaviors (with the gotchas found building them). |
| 4331 | " |
| 4332 | capability-objects Capability Objects: ffmpeg, OCR, and Other System Tools Building on DBBASIC 260 How to write DBBASIC objects that shell out to system binaries like tesseract and ffmpeg safely, with worked examples and a security checklist. "A DBBASIC object is plain Python running in a subprocess. There is no |
| 4333 | import sandbox and no call whitelist, so an object can do anything |
| 4334 | Python on that machine can do — including shell out to system binaries. |
| 4335 | That makes real capability work a normal object: OCR a scanned receipt |
| 4336 | with `tesseract`, transcode a clip with `ffmpeg`, render a thumbnail |
| 4337 | with ImageMagick, extract text from a PDF, call a local model. |
| 4338 | |
| 4339 | The old prototype shipped a pack of these. The runtime carries the same |
| 4340 | capability; this page documents how to write them safely. |
| 4341 | |
| 4342 | ## The execution model |
| 4343 | |
| 4344 | Each object call runs in a **spawned subprocess** with a wall-clock |
| 4345 | timeout (`DBBASIC_OBJECT_TIMEOUT_SECONDS`). Practical consequences: |
| 4346 | |
| 4347 | - The object has the full standard library, the filesystem, and the |
| 4348 | ability to launch its own subprocesses. `subprocess.run([...])` works. |
| 4349 | - A runaway object is killed at the timeout, so a hung `ffmpeg` cannot |
| 4350 | wedge the server. Set the timeout to fit the workload. |
| 4351 | - It is isolated from the parent's memory, not from the machine. There |
| 4352 | is no CPU or memory cap yet (see status), so capability |
| 4353 | objects are **operator/admin code** — your own tools on your own box, |
| 4354 | the same trust level as a cron job. Writing object source is gated; |
| 4355 | visitors run these objects, they do not author them. |
| 4356 | |
| 4357 | ## Prerequisite: install the tool |
| 4358 | |
| 4359 | Capability objects call binaries that must exist on the VM. This is a |
| 4360 | normal operator step, explicit rather than hidden: |
| 4361 | |
| 4362 | ```bash |
| 4363 | sudo apt install tesseract-ocr ffmpeg imagemagick poppler-utils |
| 4364 | ``` |
| 4365 | |
| 4366 | If a binary is missing, the object's `subprocess.run` raises |
| 4367 | `FileNotFoundError`, which surfaces as a normal object execution error |
| 4368 | in the logs and change feed — no silent failure. |
| 4369 | |
| 4370 | ## Worked example: OCR an uploaded image |
| 4371 | |
| 4372 | A browser form posting `multipart/form-data` delivers files under |
| 4373 | `request[""_files""]` with base64 content (see |
| 4374 | [object authoring](/docs/object-authoring#upload-forms)). The object |
| 4375 | writes the bytes to a temp file, runs `tesseract`, and returns the text. |
| 4376 | |
| 4377 | ```python |
| 4378 | import base64 |
| 4379 | import subprocess |
| 4380 | import tempfile |
| 4381 | from pathlib import Path |
| 4382 | |
| 4383 | |
| 4384 | def POST(request): |
| 4385 | upload = request.get(""_files"", {}).get(""image"") |
| 4386 | if upload is None: |
| 4387 | return {""status"": ""error"", ""error"": ""post an image field""} |
| 4388 | |
| 4389 | content = base64.b64decode(upload[""content_base64""]) |
| 4390 | with tempfile.TemporaryDirectory() as work: |
| 4391 | source = Path(work) / ""in.png"" |
| 4392 | source.write_bytes(content) |
| 4393 | result = subprocess.run( |
| 4394 | [""tesseract"", str(source), ""stdout""], |
| 4395 | capture_output=True, text=True, timeout=30, |
| 4396 | ) |
| 4397 | |
| 4398 | if result.returncode != 0: |
| 4399 | _logger.error(""ocr failed"", stderr=result.stderr[:500]) |
| 4400 | return {""status"": ""error"", ""error"": ""OCR failed""} |
| 4401 | |
| 4402 | text = result.stdout.strip() |
| 4403 | _logger.info(""ocr done"", chars=len(text)) |
| 4404 | return {""status"": ""ok"", ""text"": text} |
| 4405 | ``` |
| 4406 | |
| 4407 | Set that object's timeout generously (`DBBASIC_OBJECT_TIMEOUT_SECONDS`) |
| 4408 | so a large scan has room, and grant it a public `execute` rule if the |
| 4409 | form is public. |
| 4410 | |
| 4411 | ## Worked example: transcode with ffmpeg |
| 4412 | |
| 4413 | ```python |
| 4414 | import base64 |
| 4415 | import subprocess |
| 4416 | import tempfile |
| 4417 | from pathlib import Path |
| 4418 | |
| 4419 | |
| 4420 | def POST(request): |
| 4421 | upload = request.get(""_files"", {}).get(""clip"") |
| 4422 | content = base64.b64decode(upload[""content_base64""]) |
| 4423 | with tempfile.TemporaryDirectory() as work: |
| 4424 | src = Path(work) / ""in"" |
| 4425 | out = Path(work) / ""out.mp3"" |
| 4426 | src.write_bytes(content) |
| 4427 | proc = subprocess.run( |
| 4428 | [""ffmpeg"", ""-y"", ""-i"", str(src), ""-vn"", ""-b:a"", ""128k"", str(out)], |
| 4429 | capture_output=True, timeout=120, |
| 4430 | ) |
| 4431 | if proc.returncode != 0 or not out.exists(): |
| 4432 | return {""status"": ""error"", ""error"": ""transcode failed""} |
| 4433 | audio = out.read_bytes() |
| 4434 | |
| 4435 | return { |
| 4436 | ""content_type"": ""audio/mpeg"", |
| 4437 | ""body"": base64.b64encode(audio).decode(""ascii""), |
| 4438 | ""encoding"": ""base64"", |
| 4439 | } |
| 4440 | ``` |
| 4441 | |
| 4442 | Small media (receipts, short clips, single images) fits inside a |
| 4443 | request. **Long media does not** — a two-second timeout is fine for a |
| 4444 | receipt but a 2 GB video transcode belongs in a background job, not a |
| 4445 | web request. Background jobs are the next platform slice |
| 4446 | (status); until then, keep capability objects to work that |
| 4447 | finishes in seconds. |
| 4448 | |
| 4449 | ## Composing with files, records, and AI |
| 4450 | |
| 4451 | Capability objects get more useful combined with the rest of the |
| 4452 | platform: |
| 4453 | |
| 4454 | - **Files** — instead of accepting an upload each time, an object can |
| 4455 | read a stored file's bytes and OCR or transcode it, then write the |
| 4456 | result back as a new file or a record. (The clean helper for an |
| 4457 | object to read from the `files` collection by id is a small planned |
| 4458 | addition; today an object works from the request payload.) |
| 4459 | - **Records** — an OCR object can `create` a record with the extracted |
| 4460 | text so it becomes searchable through [global search](/docs/http-api-contract#global-search). |
| 4461 | - **AI + shell** — because the object is exposed as an |
| 4462 | `execute_object` MCP tool, the shell AI can call it. ""OCR my latest |
| 4463 | upload and note the total"" becomes: the AI reads the file, calls the |
| 4464 | OCR object, and creates a note — each step permission-checked and |
| 4465 | audited, no glue code. |
| 4466 | |
| 4467 | ## Safety checklist for a capability object |
| 4468 | |
| 4469 | - Set a timeout that fits the job; never rely on the default. |
| 4470 | - Validate the upload before spending CPU on it (size, content type). |
| 4471 | - Write to a `tempfile.TemporaryDirectory()` so nothing leaks between |
| 4472 | calls; never build a shell command by string-concatenating user input |
| 4473 | — pass argument lists to `subprocess.run`, never `shell=True`. |
| 4474 | - Log failures with `_logger` so they land in the change feed. |
| 4475 | - Treat these as operator-authored: source writes are gated, and a |
| 4476 | per-family ""builder role"" for scoped, non-admin object creation is a |
| 4477 | deliberate open design item, not a shipped capability. |
| 4478 | " |
| 4479 | storage-modes Collection Storage Modes Data & Storage 300 How collections choose between classic (rewrite-on-write) and append (log-structured) storage, with real numbers on write cost, compaction, and current limits. "A collection stores its records one of two ways. Both live in the same |
| 4480 | single `records.tsv`, both are served by the same API, permissions, cache, |
| 4481 | and generators, and both satisfy the invariant in |
| 4482 | [`append-only-storage-design.md`](/docs/append-only-storage): the file |
| 4483 | alone is the complete truth. |
| 4484 | |
| 4485 | ## Classic (the default) |
| 4486 | |
| 4487 | Every write atomically rewrites the whole file (temp file + rename). Every |
| 4488 | row appears exactly once. This is the right mode for what collections |
| 4489 | usually are — hundreds to tens of thousands of records — and it is what |
| 4490 | every collection uses unless its schema says otherwise. Nothing existing |
| 4491 | changed modes; there is no migration. |
| 4492 | |
| 4493 | - Write cost grows with collection size (measured: ~4ms at 1k rows, |
| 4494 | ~284ms at 100k, ~2.8s at 1M — per write). |
| 4495 | - The file never contains history; `cat` shows current state only. |
| 4496 | |
| 4497 | ## Append (opt-in per collection) |
| 4498 | |
| 4499 | Declare it in the schema: |
| 4500 | |
| 4501 | ```json |
| 4502 | { ""name"": ""events_log"", ""storage"": ""append"", ""fields"": [ ... ] } |
| 4503 | ``` |
| 4504 | |
| 4505 | The collection becomes a last-wins log inside the same file: create, |
| 4506 | update, and delete each append one row instead of rewriting. An internal |
| 4507 | first column `_op` marks ordinary rows (empty) and deletions (`del`) — it |
| 4508 | is never visible in schemas, API responses, or returned records, and no |
| 4509 | schema may declare a field named `_op`. Reads fold the log newest-wins; |
| 4510 | list order matches classic mode exactly. |
| 4511 | |
| 4512 | - Write cost is near-constant (measured: create ~4ms at 100k rows, ~34ms |
| 4513 | at 1M; update ~1–9ms — versus seconds in classic mode at that scale). |
| 4514 | - Until compaction, `cat` shows the row's full history and deletions — |
| 4515 | an inspectable audit trail, by design. |
| 4516 | - Mode transitions are just writes: adding `""storage"": ""append""` takes |
| 4517 | effect on the next write (one final rewrite adds `_op`); removing it |
| 4518 | compacts back to a classic file on the next write. |
| 4519 | |
| 4520 | ### Compaction (the VACUUM analog) |
| 4521 | |
| 4522 | Superseded rows and tombstones accumulate until compaction folds the file |
| 4523 | back to live rows only (atomic rewrite, under the writer lock): |
| 4524 | |
| 4525 | - Manually: `object_records.compact_collection(""name"", base_dir=...)` |
| 4526 | (returns rows/bytes before and after). |
| 4527 | - Automatically: when a read observes more dead rows than live ones and |
| 4528 | the file exceeds `DBBASIC_APPEND_COMPACT_MIN_ROWS` (default 10000) |
| 4529 | physical rows, the **next write** compacts instead of appending. Reads |
| 4530 | never rewrite anything. |
| 4531 | - Via HTTP (admin-gated, same posture as other mutating admin record |
| 4532 | routes): `POST /admin/collections/{collection}/compact` runs |
| 4533 | `compact_collection` and returns its rows/bytes-before/after summary |
| 4534 | plus `duration_ms`. 404 for an unknown collection, 400 for a collection |
| 4535 | not currently in append storage mode. `GET /admin/storage` reports |
| 4536 | per-collection compaction observability -- `{""physical_rows"", |
| 4537 | ""live_rows"", ""dead_rows"", ""bloat_ratio"", ""file_bytes"", |
| 4538 | ""sidecar_present"", ""compaction_flagged""}` for every append-mode |
| 4539 | collection (`object_records.append_collection_stats` / |
| 4540 | `list_append_collection_stats`). This endpoint is cheap by |
| 4541 | construction: it never folds records.tsv to answer, preferring a warm |
| 4542 | in-process cache entry or the id->offset sidecar's own row count; a |
| 4543 | collection neither can answer comes back with `""estimated"": true` and |
| 4544 | only `file_bytes` populated (`physical_rows`/`live_rows` null) rather |
| 4545 | than paying an O(file) parse on a status call. |
| 4546 | - Via the daemon (object_daemon.py, optional -- nothing else depends on |
| 4547 | it running): `process_compactions` polls every |
| 4548 | `DBBASIC_COMPACTION_INTERVAL_SECONDS` (default 3600, tracked by a |
| 4549 | `.compaction_last_run` marker file under the data dir rather than an |
| 4550 | in-process timer, so the interval survives a daemon restart) and |
| 4551 | compacts any append-mode collection whose `bloat_ratio` is at or above |
| 4552 | `DBBASIC_COMPACTION_BLOAT_RATIO` (default 1.0 -- dead rows at least |
| 4553 | matching live rows) AND whose physical row count is at or above |
| 4554 | `DBBASIC_APPEND_COMPACT_MIN_ROWS`. A failure compacting one collection |
| 4555 | is logged and skipped; it never stops the rest of the pass. |
| 4556 | |
| 4557 | ### Crash behavior |
| 4558 | |
| 4559 | A write interrupted mid-row leaves a torn final line. Readers ignore it; |
| 4560 | the next writer truncates it away before appending. Compaction and classic |
| 4561 | mode keep full temp+rename atomicity. |
| 4562 | |
| 4563 | ### Current limits (honest) |
| 4564 | |
| 4565 | - Collections larger than `DBBASIC_RECORDS_CACHE_MAX_ROWS` (default |
| 4566 | 500k) fall out of the in-process cache. Point operations (create's |
| 4567 | duplicate check, get, update, delete) no longer pay a full fold-parse |
| 4568 | above that size: an id→offset sidecar (design doc, item 4; |
| 4569 | `.records.oidx` next to `records.tsv`, derived and disposable) answers |
| 4570 | them by seek instead (measured: create/update ~1ms, get ~0.3ms at 1M |
| 4571 | rows, versus ~2.8s for a full fold-parse before the sidecar existed). |
| 4572 | The sidecar builds lazily on first use past the threshold (one |
| 4573 | sequential scan, ~2s at 1M rows) and self-heals from any inconsistency |
| 4574 | by rebuilding. **List and read-all-records stay unchanged** above the |
| 4575 | threshold: they still fold the whole file, since ordering and |
| 4576 | windowing need the full picture -- a secondary sidecar for that is |
| 4577 | future work (design doc, item 5). At or below the threshold, nothing |
| 4578 | changed: the in-process cache still serves everything, sidecar or not. |
| 4579 | - At or below the threshold, a WARM cache entry for an append-mode |
| 4580 | collection that grows in place (another process, the CLI, or a sibling |
| 4581 | worker appending — same inode, size only) is caught up with a |
| 4582 | tail-delta fold of just the new rows instead of a full re-parse of the |
| 4583 | whole file (design doc, Sidecars: ""when a stat signature changes by |
| 4584 | growth alone, parse only the tail delta""). Measured: reading a |
| 4585 | 400,000-row collection right after an external +100-row append dropped |
| 4586 | from ~742–815ms (full re-fold every time, regardless of how small the |
| 4587 | growth was) to ~74–100ms (fold just the 100 new rows) — roughly 8x at |
| 4588 | this size, and the gap widens with collection size since the old cost |
| 4589 | was O(file) and the new one is O(delta). A delta containing any |
| 4590 | deletion falls back to a full fold (deletes shift every later row's |
| 4591 | position, which the cheap merge doesn't model); growth past the cache |
| 4592 | threshold is still evicted per the existing row-count rule above. |
| 4593 | - A process's own append updates its cache entry without re-reading the |
| 4594 | file (previous entry + the one row) **only when that entry was current |
| 4595 | up to the byte where the row landed**. If another process appended |
| 4596 | first, the entry is left stale and the next read catches up with the |
| 4597 | tail-delta fold above. Until this check existed, the stale entry was |
| 4598 | extended anyway and stamped as current: the other process's record |
| 4599 | vanished from this process's lists and lookups, and a create reusing |
| 4600 | its id was accepted and overwrote it. |
| 4601 | - Cold reads of an append file cost ~1.6x a classic parse (fold |
| 4602 | overhead). Compaction restores parity. |
| 4603 | - Backup **preview/diff** interprets `_op`: for append-mode collections |
| 4604 | (backup side, live side, or both — a backup taken before a mode switch |
| 4605 | compares fine against a now-classic or now-append live file) it folds |
| 4606 | the log last-wins-by-id before diffing, so `_op` never appears as a |
| 4607 | field and a tombstoned id is treated as absent, not live. Backup/restore |
| 4608 | of the file itself is unaffected either way (the file is opaque bytes to |
| 4609 | backup). |
| 4610 | |
| 4611 | ## Choosing |
| 4612 | |
| 4613 | Classic for ordinary app data (the default is correct). Append for |
| 4614 | write-hot or log-shaped collections: event logs, impressions, telemetry, |
| 4615 | game/world state, anything updated far more often than it is read cold. |
| 4616 | When in doubt, stay classic — switching later is one schema edit. |
| 4617 | " |
| 4618 | append-only-storage Append-Only Storage: Design Decisions Data & Storage 310 Design decisions for making collection writes O(1) via append-only TSV storage, while preserving the single-file-of-truth invariant. "Decisions for the next storage phase: making collection writes O(1) while |
| 4619 | keeping the system's defining constraint intact. Written before |
| 4620 | implementation, like docs/event-hooks-decisions.md, so the direction is on |
| 4621 | record with its reasoning. |
| 4622 | |
| 4623 | ## The Invariant (decided first, everything else follows) |
| 4624 | |
| 4625 | **A collection either IS one `records.tsv` file, or can deterministically |
| 4626 | emit one.** The single TSV is the source of truth: complete on its own, |
| 4627 | greppable, diffable, backed up with `cp`. Anything clever — indexes, caches, |
| 4628 | offsets — is a *sidecar*: derived, disposable, and rebuildable from the TSV |
| 4629 | alone. No storage feature may ever be added that cannot be flattened back to |
| 4630 | the single file. (This also binds any future alternate backend: its contract |
| 4631 | includes materializing the canonical TSV on demand.) |
| 4632 | |
| 4633 | ## Why Change Anything |
| 4634 | |
| 4635 | Measured (2026-07-12, M1, local SSD, after the read-cache work): `create` and |
| 4636 | `update` rewrite the whole file per record — 10.5s at 1M rows, 2.5min at 5M. |
| 4637 | Reads scale fine (O(1) indexed `get` holds at millions of rows); writes are |
| 4638 | the wall. Motivating workloads: game-server state (write-hot large |
| 4639 | collections), ad-exchange impression logs, price history — all append-shaped. |
| 4640 | |
| 4641 | ## The Design |
| 4642 | |
| 4643 | Append-only *within the single file*: |
| 4644 | |
| 4645 | - **Create** appends one row. O(1). |
| 4646 | - **Update** appends a superseding row with the same id. Reads resolve |
| 4647 | **last-wins** per id. (Note: today's duplicate-id behavior is |
| 4648 | first-occurrence-wins; this flips deliberately and must be called out in |
| 4649 | the change.) |
| 4650 | - **Delete** appends a tombstone row (representation decided at |
| 4651 | implementation — a reserved marker that cannot collide with user data and |
| 4652 | survives the csv layer; it must be visible and obvious in a raw `cat`). |
| 4653 | - **Compaction** is the only remaining whole-file rewrite: collapse to live |
| 4654 | rows via the existing atomic temp+rename, run on a schedule or when the |
| 4655 | superseded-row ratio passes a threshold — never inline in a request. Until |
| 4656 | compaction, the file contains its own row history: grep shows every version |
| 4657 | a record went through. That is a feature (an inspectable audit trail), not |
| 4658 | merely tolerated. |
| 4659 | - **New-column handling**: today a new field triggers a full-file header |
| 4660 | rewrite. Append-only tolerates rows shorter than the current header (they |
| 4661 | read as empty — the semantics that already exist), so a header change can |
| 4662 | ride the next compaction rather than forcing an immediate rewrite. |
| 4663 | |
| 4664 | ## Sidecars |
| 4665 | |
| 4666 | - **id → byte-offset index** file per collection: maps each id to the offset |
| 4667 | of its *latest* row. Enables point reads by seek without parsing the file. |
| 4668 | Derived and disposable — rebuild is one sequential scan. Never required for |
| 4669 | correctness; readers without the sidecar fall back to scan. |
| 4670 | - **The in-process read cache** (already shipped) composes into incremental |
| 4671 | reads: cache entries remember the byte offset they consumed; when a stat |
| 4672 | signature changes by growth alone, parse only the tail delta — O(new rows), |
| 4673 | not O(file). This dissolves the ""big hot collection vs. cache eviction"" |
| 4674 | tension for write-hot workloads. |
| 4675 | - Cache-comment revision required at implementation: the current |
| 4676 | `_RECORDS_CACHE` reasoning leans on every write producing a fresh inode via |
| 4677 | atomic rename. Appends mutate in place (same inode; mtime/size change). |
| 4678 | Signature checks still detect change, but the comment's argument must be |
| 4679 | rewritten for the append case, including the torn-tail rule below. |
| 4680 | |
| 4681 | ## Crash Safety |
| 4682 | |
| 4683 | Rename-atomicity is replaced (for appends) by the classic log rule: a torn |
| 4684 | final line — no trailing newline, or a row that fails to parse at EOF — is |
| 4685 | ignored by readers and truncated/overwritten by the next writer. Appends are |
| 4686 | flushed per write; fsync policy is a deliberate knob (default: flush, no |
| 4687 | fsync per row — same durability class as today's writes; an env for |
| 4688 | fsync-per-append where a workload wants it). Compaction keeps full |
| 4689 | temp+rename atomicity. |
| 4690 | |
| 4691 | ## Concurrency |
| 4692 | |
| 4693 | Writers still serialize under the existing per-collection file lock — but the |
| 4694 | critical section shrinks from ""rewrite everything"" to ""append one line,"" so |
| 4695 | effective write throughput rises by orders of magnitude without new |
| 4696 | machinery. Readers remain lock-free; the stat-signature cache covers |
| 4697 | cross-process coherence, as today. |
| 4698 | |
| 4699 | ## What This Buys, Honestly |
| 4700 | |
| 4701 | - The measured interactive ceiling moves from tens of thousands of rows to |
| 4702 | **tens of millions** for ordinary use, and far beyond for append-heavy, |
| 4703 | read-by-id workloads (a 15GB file appends in microseconds and point-reads |
| 4704 | by seek). |
| 4705 | - What stays hard: rich secondary queries (by customer, by date range, by |
| 4706 | status) still scan unless a sidecar index for that field exists. Secondary |
| 4707 | sidecar indexes are future work, same rules: derived, disposable. |
| 4708 | - What is out of scope on purpose: cross-collection transactions, |
| 4709 | replication, multi-writer scaling. Single VM, one honest file, is still the |
| 4710 | product. |
| 4711 | |
| 4712 | ## Migration and Compatibility |
| 4713 | |
| 4714 | Opt-in per collection (schema flag or storage marker), default unchanged — |
| 4715 | existing collections keep exact current behavior until switched. A compacted |
| 4716 | append-only file is byte-compatible with a classic one (header + unique |
| 4717 | rows), so switching a collection back is: compact, remove the marker. |
| 4718 | Package installs, backups, and restore already treat `records.tsv` as opaque |
| 4719 | content and keep working; the backup CLI gains nothing to learn (the sidecar |
| 4720 | index is rebuildable, so backups may ignore it entirely). |
| 4721 | |
| 4722 | ## The Escape Hatch (documented now, built never — until real need) |
| 4723 | |
| 4724 | If a collection someday truly outgrows one file (billions of rows, heavy |
| 4725 | secondary queries), the answer is a **pluggable per-collection backend** |
| 4726 | under the identical schema/permission/API surface — SQLite being the obvious |
| 4727 | candidate (single file, stdlib, public domain). The invariant above still |
| 4728 | binds it: such a backend must emit the canonical `records.tsv` on demand. |
| 4729 | This paragraph exists so nobody ever ""improves"" the TSV engine into a |
| 4730 | half-database; past the envelope, graft a real one underneath instead. |
| 4731 | |
| 4732 | ## Prior Art |
| 4733 | |
| 4734 | The delta-plus-merge shape has flat-file ancestry: Strozzi NoSQL (1998), the |
| 4735 | system that coined ""NoSQL,"" documented exactly this pattern for big tables — |
| 4736 | extract a small working table, edit it, background-merge it into the sorted |
| 4737 | master, keeping the old table and the delta ""for backup and/or journaling |
| 4738 | purposes."" This design automates that workflow inside one file. Its lock |
| 4739 | strategy (a .lock sidecar next to the table, cleaned on interrupt) is also |
| 4740 | the mechanism this codebase independently uses. The offset-sidecar planned |
| 4741 | below is the trick genomics' tabix proved on TSV at petabyte scale. |
| 4742 | |
| 4743 | ## Build Order |
| 4744 | |
| 4745 | 1. Tail-delta read cache (offset-tracking) — useful even before append-only |
| 4746 | lands, zero format change. |
| 4747 | 2. Append-only create/update/delete + torn-tail recovery + last-wins reads, |
| 4748 | behind the per-collection opt-in. |
| 4749 | 3. Compaction (manual/admin trigger first, then scheduled via the daemon). |
| 4750 | 4. id→offset sidecar for seek-based point reads on large collections. |
| 4751 | 5. Secondary-field sidecars — only when a named workload demands one. |
| 4752 | " |
| 4753 | write-pipeline The Write Pipeline: What Happens, In What Order, And What Can Stop It Data & Storage 320 A stage-by-stage reference for every synchronous, fan-out, and asynchronous step a record write goes through, with each stage's failure semantics. "[`zero-to-code.md`](/docs/zero-to-code) says where each kind of logic lives. |
| 4754 | This page is its runtime twin: when a record is written, **every stage that |
| 4755 | runs, in order, with its failure semantics** — because ""code working with |
| 4756 | code, signals going around"" is exactly where frameworks went dark. Django |
| 4757 | signals and Rails callbacks earned their reputation not because reactions |
| 4758 | are wrong but because nobody could answer *why did my record change?* |
| 4759 | without a debugger. Here the pipeline is fixed, short, and this page is its |
| 4760 | single description. Verified against `object_server.py` and |
| 4761 | `object_records.py`; if this page and the code disagree, fix one of them — |
| 4762 | that disagreement is a bug. |
| 4763 | |
| 4764 | ## The synchronous path (inside the request) |
| 4765 | |
| 4766 | Everything here happens before the client gets its response, in this order: |
| 4767 | |
| 4768 | | # | stage | on failure | lives in | |
| 4769 | |---|---|---|---| |
| 4770 | | 1 | **permission check** (collection + row rules) | 403, nothing ran | policy | |
| 4771 | | 2 | **field-write denial** (schema field permissions) | 403, names the fields | schema | |
| 4772 | | 3 | **owner stamp** — sessions get `owner_id` written server-side; clients cannot spoof it (admin *tokens* skip this: seeding and migration set ownership deliberately) | — | server | |
| 4773 | | 4 | **pre-write hook** (`hooks.before_write`) — may reject (its own 4xx, or 503 for an unreadable read) or transform (stamp fields; id/owner/read-only/computed protected) | **fails CLOSED**: a broken hook is a 500 and no write | `hook/` object | |
| 4774 | | 5 | **auto `created_at`**, then **computed fields materialize** — rollups first, then formulas, so a formula may read a rollup | a broken formula stores `""""` — **fails SOFT**, the write proceeds | `object_computed` | |
| 4775 | | 6 | **schema validation** — types, required, enums, relations-exist, integer-cents; runs on the *final* record, so a hook's transform is validated too | 400, no write | schema | |
| 4776 | | 7 | **transition check** — is this status move declared, and may *this* subject make it (`when` guards) | 403/409, no write | schema | |
| 4777 | | 8 | **take the check locks the write needs** (schema **`locked_checks`** declared on, or reading, this collection or its rollup parents; sorted, before any file lock), then **the collection's file lock**, and inside both check what must hold against the rows *as they are now*: the id is new (create), `If-Match`/`expected_rev` still matches (update), the stored record is not frozen by a schema **`locked_when`** rule (update, delete), no other record holds a key a schema **`unique`** constraint covers (create, update), and every selected **locked check** allows it (create, update, delete) | 409 (a check's 4xx; 503 when it cannot decide), no write | `object_records` | |
| 4778 | | 9 | still inside the lock: **persist**, then the **change-log entry** (actor, before/after, changed fields) | write errors surface as 4xx/5xx | `object_records` | |
| 4779 | |
| 4780 | **Only stage 8 is atomic with the write.** Stages 1–4 read whatever they |
| 4781 | read *before* the lock: two overlapping requests can both pass the same hook |
| 4782 | and both arrive at stage 8. A rule of the form ""this value appears once"" |
| 4783 | therefore belongs in `unique`, not in a hook that looks for an existing row |
| 4784 | — that hook passes twice. A rule of the form ""this record is settled"" |
| 4785 | belongs in `locked_when`, not in a hook that reads `existing.status` — that |
| 4786 | hook is handed the record as it was before the lock, and an edit overlapping |
| 4787 | the approval is written onto the approved row. A rule of the form ""this sum |
| 4788 | stays under what another collection says"" belongs in `locked_checks`, whose |
| 4789 | lock holds the other collection still. (An update re-reads its record under the lock and |
| 4790 | runs stages 5–7 there; that makes them consistent with the stored record, not |
| 4791 | with other records.) Stage 8 also runs for writers that never see stages 1–4: |
| 4792 | handlers, the daemon, imports and seeds call `object_records` directly. |
| 4793 | |
| 4794 | Two asymmetries in there are doctrine, not accident: **gates fail closed, |
| 4795 | derivations fail soft** (a validation gate that silently passes on error is |
| 4796 | not a gate; a caption that blanks on error is just a blank caption), and |
| 4797 | **hooks run before validation** so that what a hook stamps is still checked |
| 4798 | like any client input. |
| 4799 | |
| 4800 | **A delete is the short version of the same path**: stage 1 (permission, |
| 4801 | checked against the stored row), stage 4, stage 8 (`locked_when` and the |
| 4802 | locked checks whose `on.delete` is true), |
| 4803 | stage 9. The hook is called with |
| 4804 | `action: ""delete""` and the row about to go; it may allow or reject, and a |
| 4805 | transform is a broken answer (500, nothing deleted). There is nothing to |
| 4806 | stamp, compute or validate. Until deletes reached stage 4, any rule a hook |
| 4807 | enforced about a settled record could be walked round by deleting it. |
| 4808 | |
| 4809 | ## The fan-out (after the write, same request, best-effort) |
| 4810 | |
| 4811 | Once the record is durably written, the server fans out — in this order, |
| 4812 | each stage isolated so one failing never blocks the next, and none of them |
| 4813 | can un-write the record: |
| 4814 | |
| 4815 | 1. **rollup re-triggers** — a payment write recomputes its invoice's rollup |
| 4816 | fields (single-hop by design: a thread-local guard stops A→B→A cascades; |
| 4817 | a chain that needs more hops is a design smell, not a setting) |
| 4818 | 2. **realtime push** — permission-filtered signal (collection, id, action); |
| 4819 | subscribers re-fetch through the enforced API, so the socket never |
| 4820 | leaks record bodies |
| 4821 | 3. **event handlers** (`HANDLES` objects) — the reaction layer: composers, |
| 4822 | status flips. Payload carries the raw verb (`create`) while the event |
| 4823 | name uses the participle (`…created`) — accept both |
| 4824 | 4. **durable event log** (when enabled) — for pollers and webhooks |
| 4825 | |
| 4826 | ## The asynchronous tail (the daemon, seconds later) |
| 4827 | |
| 4828 | Independent passes over the change log and collections, each with its own |
| 4829 | cursor, each at-least-once: **notify** (rules → in-app/email intents), |
| 4830 | **email outbox** drain, **change dispatch** (off by default — replays |
| 4831 | handlers for storage-level writes so reactions stop depending on which |
| 4832 | path wrote), **auto-transitions** (the 48h approve), **scheduled runners** |
| 4833 | (aging, dunning, recurring journals, matcher, escalation — every run's |
| 4834 | outcome a `scheduler_runs` record), **queue messages** (delay, retry, |
| 4835 | backoff). |
| 4836 | |
| 4837 | ## How chains work without becoming Django signals |
| 4838 | |
| 4839 | The reaction graph is real: a payment triggers the books composer, which |
| 4840 | writes a journal, whose lines re-trigger the journal's rollups. What keeps |
| 4841 | it legible instead of haunted: |
| 4842 | |
| 4843 | - **One hop is synchronous, everything else is a record.** A handler's |
| 4844 | write does not re-enter the dispatcher (storage-level writes don't |
| 4845 | dispatch), so there is no unbounded cascade — a deeper chain must go |
| 4846 | through the change-dispatch pass, which has a cursor, markers, and a log. |
| 4847 | - **Everything generated says who generated it**: `generated_from` |
| 4848 | provenance on composed records, `actor` on every change-log entry. |
| 4849 | ""Why did my record change?"" is a query, not a debugging session: |
| 4850 | `record_changes` names the actor; a composed journal names its source. |
| 4851 | - **Idempotency by provenance** means redelivery is safe by construction — |
| 4852 | a replayed event composes nothing, so at-least-once is a guarantee, not |
| 4853 | a hazard. |
| 4854 | - **Reactions may not gate and gates may not react** |
| 4855 | ([`logic-decisions.md`](/docs/logic-decisions) #6). The moment a reaction |
| 4856 | can block a write, or a gate can send an email, the pipeline above stops |
| 4857 | being a truthful description — that boundary is what makes this page |
| 4858 | possible. |
| 4859 | |
| 4860 | ## Multi-collection workflows |
| 4861 | |
| 4862 | An order becomes an invoice becomes a payment becomes a journal; a task is |
| 4863 | claimed, submitted, approved, settled. There is deliberately **no workflow |
| 4864 | engine** — a business process here is a chain of *(transition on one |
| 4865 | record) → (reaction that writes the next record)*, and each link is |
| 4866 | individually visible in the table above. The process's state is not hidden |
| 4867 | in an engine: it IS the records, their statuses, and their provenance |
| 4868 | stamps, which is why an AI operator can answer ""where is this order stuck?"" |
| 4869 | by reading collections. If a real orchestration need repeats (sagas, |
| 4870 | compensation across many collections), that is a doctrine-#4 moment — |
| 4871 | extract it *then*, from the concrete chains that exist. |
| 4872 | |
| 4873 | ## Reading a live system |
| 4874 | |
| 4875 | - `record_changes` — who did what, before/after, per record |
| 4876 | - `generated_from` — what machine wrote this, from what source |
| 4877 | - `/scheduler` — what the clock did and what each run returned |
| 4878 | - execution logs — every hook and handler run, observable like any object |
| 4879 | - boot lines — the daemon prints every pass's posture (`Books: NOT READY…`, |
| 4880 | `Queue: enabled`, `Change dispatch: disabled`) so a disabled layer is |
| 4881 | announced, not discovered |
| 4882 | " |
| 4883 | durability-and-recovery Durability & Recovery Data & Storage 330 How the object server keeps your data safe and readable in plain text, with crash-safe writes, replayable change logs, and a dedicated conformance suite. "How the object server keeps your data safe, and why you can still read it in |
| 4884 | fifty years. |
| 4885 | |
| 4886 | ## The design principle: plain text is the source of truth |
| 4887 | |
| 4888 | Every record lives in a tab-separated-values file on disk — |
| 4889 | `data/collections/<name>/records.tsv` — that you can open with `cat`, `grep`, |
| 4890 | a spreadsheet, or any programming language's CSV reader, on any operating |
| 4891 | system, with no special software. There is no proprietary binary format your |
| 4892 | data can be trapped inside. |
| 4893 | |
| 4894 | Everything that makes the store *fast* — the id→offset index, the in-memory |
| 4895 | read cache — is **derived from the TSV and rebuildable from it**. Delete every |
| 4896 | index and cache and the database is byte-for-byte identical; you lose speed, |
| 4897 | never a byte. The canonical data is exactly the set of `.tsv` files, and |
| 4898 | nothing else is load-bearing. |
| 4899 | |
| 4900 | > **Why it matters:** a binary database entombs your bytes in a format that |
| 4901 | > needs *its own software* to read. Plain text means your data outlives the |
| 4902 | > software that wrote it. |
| 4903 | |
| 4904 | ## Graceful degradation |
| 4905 | |
| 4906 | Because the store is plain text, corruption **degrades gracefully**. A damaged |
| 4907 | `.tsv` — or a truncated backup of one — can be opened in any editor and |
| 4908 | salvaged by hand: at worst a single line is garbled; the file never becomes |
| 4909 | ""won't open."" A corrupted binary database page, by contrast, can render the |
| 4910 | whole database unreadable without vendor-specific recovery tools, and a torn |
| 4911 | write can damage internal tree structure catastrophically. Plain text has no |
| 4912 | structure to catastrophically damage. |
| 4913 | |
| 4914 | ## Crash safety |
| 4915 | |
| 4916 | - **Classic collections** are rewritten with a temp-file-plus-atomic-rename. |
| 4917 | A reader always sees either the entire previous version or the entire new |
| 4918 | one — never a half-written file. |
| 4919 | - **Append-only collections** (used for high-write logs) treat an interrupted |
| 4920 | write as a torn tail: only the last, incomplete entry is ignored on read; |
| 4921 | every fully-written entry before it survives — including rows whose quoted |
| 4922 | fields span multiple physical lines (the write-side repair is quote-aware; |
| 4923 | see [History: the torn-tail gap](#history-the-torn-tail-write-gap-fixed)). |
| 4924 | - **Concurrency** is serialized with a kernel file lock (`flock`) that applies |
| 4925 | across both threads *and* separate processes, so concurrent writers on a |
| 4926 | multi-worker deployment cannot corrupt or lose each other's writes. |
| 4927 | |
| 4928 | ## Recovery by replay: backup + log |
| 4929 | |
| 4930 | Alongside each collection, every mutation is also appended to an independent |
| 4931 | **change log** — `record_changes/<collection>/changes.jsonl` — recording, for |
| 4932 | each create/update/delete: a timestamp, the actor, and full *before* and |
| 4933 | *after* snapshots of the record. |
| 4934 | |
| 4935 | This gives you the classic ""restore a backup and replay the log"" recovery |
| 4936 | model, in plain text: |
| 4937 | |
| 4938 | - **Reconstruct a collection from its change log alone.** Replaying the log in |
| 4939 | chronological order — apply each `after` snapshot on create/update, drop the |
| 4940 | record on delete — reproduces the collection's exact current state. If a |
| 4941 | collection file is ever lost or damaged, the change log rebuilds it. |
| 4942 | - **Point-in-time recovery.** Restore a plain-text backup, then replay the |
| 4943 | change log *forward* to a chosen timestamp. |
| 4944 | - **The change log is itself crash-safe by construction.** It is line-based |
| 4945 | (JSON-per-line); a read skips any incomplete final line, so a crash |
| 4946 | mid-append costs only that one in-flight entry. |
| 4947 | |
| 4948 | The result is **two independent plain-text records of every change** — the |
| 4949 | collection file and the change log — either of which can reconstruct the |
| 4950 | other. Your recovery, like your data, needs no special software: a short |
| 4951 | script replays the log. |
| 4952 | |
| 4953 | ## How we test durability |
| 4954 | |
| 4955 | Durability is verified by a dedicated conformance suite, run deliberately |
| 4956 | (like a benchmark) rather than on every commit, covering: |
| 4957 | |
| 4958 | - **Character-set fidelity** — ASCII and control bytes, multibyte UTF-8, |
| 4959 | emoji and grapheme clusters, adversarial Unicode, and arbitrary JSON, each |
| 4960 | round-tripped byte-exact through every storage and read path, with no silent |
| 4961 | normalization. |
| 4962 | - **Crash recovery** — a write interrupted at *every byte offset* is simulated |
| 4963 | and the store is checked to recover to a valid state with no loss of |
| 4964 | committed data — including multi-line quoted rows, whose every-offset sweep |
| 4965 | was held as strict xfails until the write-side repair was fixed and is now |
| 4966 | an ordinary regression battery. |
| 4967 | - **Concurrency** — real concurrent processes writing the same collection, |
| 4968 | checked for lost updates and corruption. |
| 4969 | - **Atomicity** — single-record writes are all-or-nothing, and a reader never |
| 4970 | observes a torn intermediate. |
| 4971 | - **Backup, restore, and compaction** — verified byte-exact, including exotic |
| 4972 | content, and crash-safe (an interrupted compaction never damages the |
| 4973 | original). |
| 4974 | - **Plain-text rebuild and replay** — deleting every index leaves the data |
| 4975 | fully intact and queryable from the TSV alone; a collection is reconstructed |
| 4976 | exactly from its change log. |
| 4977 | |
| 4978 | The philosophy follows the databases that made testing their reputation: a |
| 4979 | visible, exhaustive test suite is itself the assurance that the data is safe. |
| 4980 | |
| 4981 | ## History: the torn-tail write gap (fixed) |
| 4982 | |
| 4983 | **Status: fixed (2026-07-30).** This section replaces a ""Known gap"" that |
| 4984 | stood here for one day — kept as history because the shape of the bug and of |
| 4985 | its first, reverted fix are both instructive. |
| 4986 | |
| 4987 | **The bug.** Before an append lands, `_repair_torn_tail` trims any partial |
| 4988 | row left by an interrupted write. It found ""the last row boundary"" by |
| 4989 | scanning backwards for a newline — quote-blind, so a newline *inside* a |
| 4990 | quoted multi-line field looked like a boundary. Worse, its fast path |
| 4991 | returned untouched any file whose final byte was `\n`, including a newline |
| 4992 | inside an unclosed quote — skipping repair in exactly the case that needed |
| 4993 | it. A crash mid-multi-line-row could then swallow the next appended row into |
| 4994 | the open quote. Exposure: ~97% of such a row's write window. |
| 4995 | |
| 4996 | **The first fix, and why it was reverted.** It gated the repair on the |
| 4997 | records cache's `covered_bytes`. Two flaws, found the second time around: |
| 4998 | that value lives only in process memory (gone precisely when a crash makes |
| 4999 | repair matter), and — the actual killer — a full parse of a *torn* file |
| 5000 | stores `covered_bytes` equal to the whole file size, because the read fold |
| 5001 | ""accounts for"" the torn bytes by knowing they are torn. So a warm cache |
| 5002 | reported clean on exactly the files needing repair. Under pytest the cache |
| 5003 | was warm from other tests; standalone it was cold. ""Fails in pytest, passes |
| 5004 | standalone"" was that, nothing more. |
| 5005 | |
| 5006 | **The fix that stands.** The repair scans forward with the same quote-aware |
| 5007 | `committed_prefix_len` the read path and the backup index use — one |
| 5008 | implementation, three users, no copies to drift. A cache may only ever |
| 5009 | *skip* the scan, never choose a truncation point, and the only cache |
| 5010 | consulted is the id-sidecar's, whose `covered_bytes` values are genuine row |
| 5011 | boundaries by construction. Cold (post-crash) the repair pays one full scan, |
| 5012 | which is the honest price of the one moment a torn tail can exist. Two |
| 5013 | neighbouring holes were closed in the same pass: an intact-but-unterminated |
| 5014 | *header* no longer truncates to a headerless file that reports success and |
| 5015 | then fails every read (the header is restored from the schema), and a |
| 5016 | sidecar corrupted with non-UTF-8 bytes now rebuilds instead of raising on |
| 5017 | every read. |
| 5018 | |
| 5019 | **Verification.** The strict-xfail acceptance tests that mapped the trigger |
| 5020 | surface — every byte offset from a row's first embedded newline to its last |
| 5021 | — were rewritten into the regression guards they were designed to become, |
| 5022 | and the every-offset sweeps now pass as ordinary tests. |
| 5023 | " |
| 5024 | backup-restore Backup and Restore Data & Storage 340 How to create, verify, and restore runtime backups of a DBBASIC Object Server instance, including scheduled backups and the deliberately CLI-only restore path. "DBBASIC runtime backups protect the object loop by keeping source, state, logs, |
| 5025 | files, versions, schemas, and collection records recoverable together. |
| 5026 | |
| 5027 | The public backup helper is: |
| 5028 | |
| 5029 | ```bash |
| 5030 | python -m object_backup |
| 5031 | ``` |
| 5032 | |
| 5033 | It creates a tar/gzip archive with a JSON manifest and a narrow runtime backup |
| 5034 | set. |
| 5035 | |
| 5036 | ## Included |
| 5037 | |
| 5038 | Runtime backups include: |
| 5039 | |
| 5040 | ```text |
| 5041 | objects/ |
| 5042 | data/state/ |
| 5043 | data/logs/ |
| 5044 | data/versions/ |
| 5045 | data/source_changes/ |
| 5046 | data/schema_versions/ |
| 5047 | data/record_changes/ |
| 5048 | data/package_changes/ |
| 5049 | data/file_changes/ |
| 5050 | data/files/ |
| 5051 | data/schemas/ |
| 5052 | data/collections/ |
| 5053 | ``` |
| 5054 | |
| 5055 | That covers object source, object state, current logs, rotated compressed logs, |
| 5056 | source versions, source change history, schema change history, record change |
| 5057 | history, package change history, object file change history, object-owned |
| 5058 | files, schema metadata, and TSV-backed collection records. |
| 5059 | |
| 5060 | ## Excluded |
| 5061 | |
| 5062 | Runtime backups deliberately exclude: |
| 5063 | |
| 5064 | - deployment secrets |
| 5065 | - environment files |
| 5066 | - systemd service files |
| 5067 | - git history |
| 5068 | - virtualenvs |
| 5069 | - caches |
| 5070 | - lock files |
| 5071 | - temp files |
| 5072 | - ephemeral rate-limit files |
| 5073 | |
| 5074 | The environment file and service unit still need operator-managed backups, but |
| 5075 | they should be stored through a secret-aware server backup process, not inside |
| 5076 | the portable runtime archive. |
| 5077 | |
| 5078 | ## Create |
| 5079 | |
| 5080 | ```bash |
| 5081 | mkdir -p /var/backups/dbbasic-object-server |
| 5082 | |
| 5083 | python -m object_backup create \ |
| 5084 | /var/backups/dbbasic-object-server/runtime-YYYYMMDD-HHMMSS.tar.gz \ |
| 5085 | --objects-dir /var/lib/dbbasic-object-server/objects \ |
| 5086 | --data-dir /var/lib/dbbasic-object-server/data |
| 5087 | ``` |
| 5088 | |
| 5089 | The command writes `dbbasic-backup-manifest.json` inside the archive. The |
| 5090 | manifest records the format version, timestamp, included roots, file count, byte |
| 5091 | count, and warnings. |
| 5092 | |
| 5093 | ## Restore Points |
| 5094 | |
| 5095 | Server-side mutations that can rewrite multiple runtime files should create a |
| 5096 | restore point before writing. Package installs use: |
| 5097 | |
| 5098 | ```python |
| 5099 | object_backup.create_runtime_restore_point(""package-hello-world"") |
| 5100 | ``` |
| 5101 | |
| 5102 | By default, restore points are written under: |
| 5103 | |
| 5104 | ```text |
| 5105 | data/backups/ |
| 5106 | ``` |
| 5107 | |
| 5108 | Set `DBBASIC_BACKUPS_DIR` to move those archives to a mounted backup volume or |
| 5109 | another operator-managed path. Runtime backup archives do not include |
| 5110 | `data/backups/`, so restore points do not recursively back up other archives. |
| 5111 | |
| 5112 | Every install writes a full archive by default, which on a large data |
| 5113 | directory adds up quickly when reinstalling many packages. To share one |
| 5114 | archive, create it once with `POST /admin/backups` and name it in each |
| 5115 | install body: `{""allow_replace"": true, ""restore_point"": ""<backup id>""}`. No |
| 5116 | new archive is written, and the install's change-log entry records the named |
| 5117 | one, so `POST /packages/{id}/restore` still works. An unknown or malformed id |
| 5118 | is refused (409 / 400) before anything changes. See ""Upgrade"" in |
| 5119 | [`single-vm-deployment.md`](/docs/single-vm-deployment) for the batch recipe. |
| 5120 | |
| 5121 | Package restore uses the recorded restore point from a package install change, |
| 5122 | not an arbitrary package path. That package-scoped HTTP route |
| 5123 | (`POST /packages/{id}/restore`, gated by `DBBASIC_ENABLE_PACKAGE_RESTORE`) |
| 5124 | is separate from full-runtime restore, which stays CLI-only. It calls |
| 5125 | `restore_runtime_backup(..., overwrite=True, prune_extra=True)` so files created |
| 5126 | by the package are removed if they were not present in the snapshot. Pruning is |
| 5127 | limited to the runtime roots; `data/backups/` is left alone. |
| 5128 | |
| 5129 | A package restore rolls back the runtime, not the record of what happened. |
| 5130 | What it does to each runtime root: |
| 5131 | |
| 5132 | | Root | Package restore | |
| 5133 | | --- | --- | |
| 5134 | | `objects/` | rolled back to the snapshot (files added since are removed) | |
| 5135 | | `data/state/`, `data/files/`, `data/user_files/` | rolled back | |
| 5136 | | `data/collections/`, `data/schemas/` | rolled back | |
| 5137 | | `data/package_baselines/`, `data/reconciles/` | rolled back (they describe the installed packages) | |
| 5138 | | `data/permissions/policy.json` | rolled back, only after the policy difference is shown and confirmed (below) | |
| 5139 | | `data/permissions/audit.jsonl` and its rotated segments | **kept** as on disk | |
| 5140 | | `data/identity/users.tsv`, `accounts.tsv` | **kept** as on disk: a user disabled, or a role removed, since the snapshot stays that way | |
| 5141 | | `data/versions/` (object source versions) | **kept**; the restore adds a version | |
| 5142 | | `data/source_changes/` | **kept**; the restore adds a `source_rollback`, `source_create` or `source_destroy` entry | |
| 5143 | | `data/schema_versions/` | **kept**; the restore adds a version | |
| 5144 | | `data/record_changes/` (and `archive/`) | **kept**; the restore adds a `create`/`update`/`delete` entry per row it changed | |
| 5145 | | `data/file_changes/` | **kept**; the restore adds a `file_create`/`file_update`/`file_delete` entry | |
| 5146 | | `data/package_changes/` | **kept**; the restore adds `restore_requested` and `rolled_back` | |
| 5147 | | `data/logs/` (object logs, rotated logs) | **kept** | |
| 5148 | |
| 5149 | Every entry the restore adds names who ran it (the actor), when, and the |
| 5150 | snapshot (`package_restore: {package_id, from_change_id, restore_point}` in a |
| 5151 | source or file change's `details`, and the message |
| 5152 | `Package restore: <id> rolled back to before change <change_id>` on versions |
| 5153 | and record changes). An object source the restore replaces or removes is |
| 5154 | saved as a version first when no version already holds it, so nothing the |
| 5155 | rollback overwrote is lost: it can be brought back with the usual source |
| 5156 | rollback. The response's `history` gives the counts of entries added and any |
| 5157 | that could not be written (`failed`, `errors`); the runtime is restored |
| 5158 | either way. |
| 5159 | |
| 5160 | ### The policy difference comes first |
| 5161 | |
| 5162 | Rolling back can put back an older, looser permission policy: a deny rule |
| 5163 | added since the snapshot to close a hole would silently disappear. So a |
| 5164 | package restore is two steps whenever it changes who may do what: |
| 5165 | |
| 5166 | 1. `POST /packages/{id}/restore` with `{""change_id"": ""..."", ""preview"": true}` |
| 5167 | writes nothing and returns `policy_diff` (every rule added, removed or |
| 5168 | changed, reordered rules, access mode, admin roles, user roles, role |
| 5169 | metadata, and the field permissions in `data/schemas/`), a readable |
| 5170 | `policy_diff_text`, and `policy_diff_hash`. |
| 5171 | 2. The apply, `{""change_id"": ""..."", ""confirm"": ""restore-runtime"", |
| 5172 | ""policy_diff_hash"": ""<from the preview>""}`, recomputes the difference and |
| 5173 | is refused with `409` if the hash is missing (and the policy changes) or |
| 5174 | is not the hash of the difference now -- the policy or the snapshot |
| 5175 | changed since the preview. The 409 carries the current difference and |
| 5176 | hash; look at it again before sending it back. |
| 5177 | |
| 5178 | Each change is marked `loosens` (someone may do something they may not do |
| 5179 | now), `tightens`, or `neutral` (labels, reasons), and `policy_diff.loosens` |
| 5180 | says whether any change loosens; the error and the text call a loosening |
| 5181 | restore out in capitals. A change that cannot be proven to tighten counts as |
| 5182 | loosening: a changed row filter or validity window, rules reordered (the |
| 5183 | first matching allow wins), any access-mode change other than to |
| 5184 | `role_based`. A snapshot without `policy.json` is compared as the server's |
| 5185 | default policy, since the restore prunes the live one. |
| 5186 | |
| 5187 | Fail closed: if either policy, or any schema in `data/schemas/`, cannot be |
| 5188 | read or parsed, the difference cannot be computed and the restore (and the |
| 5189 | preview) is refused with `409`. Fix or move the unreadable file first. |
| 5190 | |
| 5191 | A restore that does not change the policy needs no hash. The difference and |
| 5192 | its hash are recorded in the `rolled_back` package change. |
| 5193 | |
| 5194 | ## Verify |
| 5195 | |
| 5196 | ```bash |
| 5197 | python -m object_backup verify \ |
| 5198 | /var/backups/dbbasic-object-server/runtime-YYYYMMDD-HHMMSS.tar.gz \ |
| 5199 | --json |
| 5200 | ``` |
| 5201 | |
| 5202 | Verification checks that: |
| 5203 | |
| 5204 | - the archive can be read |
| 5205 | - the manifest is present |
| 5206 | - the manifest count matches the archive contents |
| 5207 | - archive paths stay under `objects/` or supported `data/` roots |
| 5208 | - symlinks, hard links, device files, and other unsafe member types are rejected |
| 5209 | |
| 5210 | ## Restore |
| 5211 | |
| 5212 | Restore is a **deliberate CLI operation**, not an HTTP verb. It is |
| 5213 | destructive and whole-instance, so it is intentionally not exposed on the |
| 5214 | admin surface (`/admin/status` reports `capabilities.backups.can_restore: |
| 5215 | false`); a ""restore"" button one misclick from wiping live data is a |
| 5216 | footgun. The pairing is: **download a backup from Scroll or |
| 5217 | `GET /admin/backups/{id}/download` to get it, and this CLI to apply it.** |
| 5218 | |
| 5219 | Runtime backups live under `data/backups/` (or `DBBASIC_BACKUPS_DIR`) and |
| 5220 | are named `YYYYMMDDTHHMMSSffffffZ-<label>.tar.gz` (label `manual` for |
| 5221 | on-demand, `package-<id>` for install restore points). Always verify |
| 5222 | first (see above). |
| 5223 | |
| 5224 | ### Dry-run into clean directories first |
| 5225 | |
| 5226 | ```bash |
| 5227 | mkdir -p /tmp/dbbasic-restore/objects /tmp/dbbasic-restore/data |
| 5228 | |
| 5229 | python -m object_backup restore \ |
| 5230 | /var/lib/dbbasic-object-server/data/backups/20260708T145041382734Z-manual.tar.gz \ |
| 5231 | --objects-dir /tmp/dbbasic-restore/objects \ |
| 5232 | --data-dir /tmp/dbbasic-restore/data \ |
| 5233 | --json |
| 5234 | ``` |
| 5235 | |
| 5236 | By default restore refuses to overwrite existing files, so this dry run |
| 5237 | never touches a live runtime. Start the server against the restored |
| 5238 | directories and check it before trusting the archive: |
| 5239 | |
| 5240 | ```bash |
| 5241 | DBBASIC_OBJECTS_DIR=/tmp/dbbasic-restore/objects \ |
| 5242 | DBBASIC_DATA_DIR=/tmp/dbbasic-restore/data \ |
| 5243 | uvicorn object_server:app --host 127.0.0.1 --port 8001 |
| 5244 | ``` |
| 5245 | |
| 5246 | Then verify `/health` and representative object routes. A real recovery |
| 5247 | drill should do this on a second clean VM. |
| 5248 | |
| 5249 | ### Recovering the live runtime |
| 5250 | |
| 5251 | Stop the service first so nothing writes during the restore. Use |
| 5252 | `--overwrite` to replace existing files, and `--prune-extra` (which |
| 5253 | requires `--overwrite`) only when you want an exact match to the archive, |
| 5254 | removing files added since — a powerful, opt-in flag: |
| 5255 | |
| 5256 | ```bash |
| 5257 | sudo systemctl stop dbbasic-object-server |
| 5258 | |
| 5259 | sudo -u dbbasic /opt/dbbasic-object-server/.venv/bin/python \ |
| 5260 | -m object_backup restore \ |
| 5261 | /var/lib/dbbasic-object-server/data/backups/<id>.tar.gz \ |
| 5262 | --objects-dir /var/lib/dbbasic-object-server/objects \ |
| 5263 | --data-dir /var/lib/dbbasic-object-server/data \ |
| 5264 | --overwrite --prune-extra --json |
| 5265 | |
| 5266 | sudo systemctl start dbbasic-object-server |
| 5267 | curl http://127.0.0.1:8001/health |
| 5268 | ``` |
| 5269 | |
| 5270 | When `--overwrite` would change the permission policy (`policy.json`, or the |
| 5271 | field permissions in `data/schemas/`), the CLI prints the difference first |
| 5272 | -- loosening changes marked, the same classification as the package restore |
| 5273 | -- and asks for `yes` on a terminal. Anything else, or no terminal, refuses |
| 5274 | and restores nothing; pass `--yes` to apply non-interactively (the |
| 5275 | difference is still printed, or returned as `policy_diff` with `--json`). |
| 5276 | To see the difference without restoring: |
| 5277 | |
| 5278 | ```bash |
| 5279 | python -m object_backup restore <backup>.tar.gz \ |
| 5280 | --objects-dir /var/lib/dbbasic-object-server/objects \ |
| 5281 | --data-dir /var/lib/dbbasic-object-server/data \ |
| 5282 | --preview # add --json for the structured difference |
| 5283 | ``` |
| 5284 | |
| 5285 | If either side's policy or a schema cannot be read, the overwrite is |
| 5286 | refused. Restores without `--overwrite` cannot replace a live policy and ask |
| 5287 | nothing. The full CLI restore is disaster recovery: unlike the package |
| 5288 | restore it does write back the histories, the audit log and the identity |
| 5289 | registry from the archive. |
| 5290 | |
| 5291 | Pruning is limited to known runtime roots (`objects/`, `data/state/`, |
| 5292 | `data/logs/`, `data/collections/`, `data/schemas/`, `data/source_changes/`, |
| 5293 | `data/package_changes/`, `data/file_changes/`); `data/backups/` is left |
| 5294 | alone, so restoring never destroys your other archives. |
| 5295 | |
| 5296 | ## HTTP Surface |
| 5297 | |
| 5298 | On-demand backup and download are exposed on the admin API (and used by |
| 5299 | Scroll's Backup screen) — see |
| 5300 | [the HTTP contract](/docs/http-api-contract#backups): |
| 5301 | |
| 5302 | - `GET /admin/backups` — inventory (`id`, `created_at`, `size`, `kind`, `scope`). |
| 5303 | - `POST /admin/backups` — create a full-runtime backup now. |
| 5304 | - `GET /admin/backups/{id}/download` — stream the archive. |
| 5305 | |
| 5306 | All admin-gated (a backup holds every record, file and user on the box, |
| 5307 | so never public; password hashes, sessions, API keys and service keys are |
| 5308 | left out, see [the HTTP contract](/docs/http-api-contract#backups)). Restore |
| 5309 | is deliberately absent from this surface — use the CLI above. |
| 5310 | |
| 5311 | ## Scheduling |
| 5312 | |
| 5313 | **For backups that leave the box, use scheduled backups:** |
| 5314 | set `DBBASIC_BACKUP_DESTINATION` and the daemon writes a hard-linked |
| 5315 | snapshot there on an interval, keeps a bounded number, and restore-tests |
| 5316 | every one, with failures reported in `/admin/status`, the dashboard's |
| 5317 | attention band and the daemon log. |
| 5318 | |
| 5319 | The older recipe below still works. The run itself |
| 5320 | is an external timer (systemd or cron) invoking `object_backup.py create` |
| 5321 | on a cadence with retention; `DBBASIC_BACKUP_SCHEDULE` records the |
| 5322 | operator's intent so `/admin/status` and Scroll can display it. A sample |
| 5323 | daily systemd timer: |
| 5324 | |
| 5325 | ```ini |
| 5326 | # /etc/systemd/system/dbbasic-backup.service |
| 5327 | [Service] |
| 5328 | Type=oneshot |
| 5329 | User=dbbasic |
| 5330 | EnvironmentFile=/etc/dbbasic-object-server.env |
| 5331 | WorkingDirectory=/opt/dbbasic-object-server |
| 5332 | ExecStart=/opt/dbbasic-object-server/.venv/bin/python -m object_backup create \ |
| 5333 | /var/lib/dbbasic-object-server/data/backups/scheduled-%%i.tar.gz |
| 5334 | ``` |
| 5335 | |
| 5336 | ```ini |
| 5337 | # /etc/systemd/system/dbbasic-backup.timer |
| 5338 | [Timer] |
| 5339 | OnCalendar=daily |
| 5340 | Persistent=true |
| 5341 | [Install] |
| 5342 | WantedBy=timers.target |
| 5343 | ``` |
| 5344 | |
| 5345 | Note that on-box backups do not survive losing the VM — pair them with |
| 5346 | provider-level disk backups (or copy archives to a bucket) for disaster |
| 5347 | recovery. On-demand create and download always work regardless of any |
| 5348 | schedule. |
| 5349 | " |
| 5350 | per-tenant-storage Per-Tenant Storage: The SaaS Decomposition Data & Storage 350 A direction note on decomposing one shared collection into per-tenant storage roots — what it buys, what it costs, and why the industry is already headed there. "A direction note, not a build plan. Recorded alongside |
| 5351 | docs/append-only-storage-design.md because the two together answer ""how far |
| 5352 | can one TSV go, and what happens at SaaS scale"" — and the answer to the |
| 5353 | second is not ""a bigger table."" |
| 5354 | |
| 5355 | ## The Observation |
| 5356 | |
| 5357 | The measured storage envelope (docs/append-only-storage-design.md: tens of |
| 5358 | thousands of rows interactive today, tens of millions after append-only) |
| 5359 | looks like a limit under the one-big-table model. Per-tenant storage inverts |
| 5360 | it: a SaaS with 100,000 customers and ""a billion orders"" does not have a |
| 5361 | billion-row problem — it has 100,000 ten-thousand-row problems, each of |
| 5362 | which sits in the comfortable center of the measured envelope. The giant |
| 5363 | commingled table is an artifact of shared-database design, not a law of |
| 5364 | SaaS. |
| 5365 | |
| 5366 | ## What Decomposition Buys |
| 5367 | |
| 5368 | - **Physical isolation.** Row-level security (`WHERE tenant_id = ?`, one |
| 5369 | missing predicate from a breach) becomes filesystem separation. The |
| 5370 | permission engine's row filters harden into file boundaries. |
| 5371 | - **GDPR and export for free.** Right-to-be-forgotten is removing the |
| 5372 | tenant's directory. ""Export my data"" is handing over the tenant's own |
| 5373 | TSV files — human-readable, Excel-openable, no export pipeline. |
| 5374 | - **Per-customer backup/restore already exists.** The scoped restore + |
| 5375 | read-only preview shipped this cycle applies per tenant with zero new |
| 5376 | code: ""restore customer X's notes to yesterday"" is the same operation. |
| 5377 | - **Per-tenant migrations.** Package upgrades ride the provenance/reconcile |
| 5378 | system tenant-by-tenant: incremental rollout, conflicts parked per |
| 5379 | tenant, no all-customers-at-once schema locks. |
| 5380 | - **Noisy neighbors decompose.** One tenant's huge collection cannot slow |
| 5381 | another's small one; the records-cache LRU bound doubles as per-tenant |
| 5382 | cache fairness. |
| 5383 | - **Tenant mobility is file movement.** Rebalancing tenants across VMs, |
| 5384 | or graduating one outlier to its own instance or to the per-collection |
| 5385 | backend escape hatch, is `mv` of a directory. Shared-nothing per tenant; |
| 5386 | horizontal scale without a distributed database. |
| 5387 | - **Metering is `du`.** Storage billing per tenant is a directory size. |
| 5388 | |
| 5389 | ## Honest Costs |
| 5390 | |
| 5391 | - **Cross-tenant queries become scatter-gather.** Admin analytics (""orders |
| 5392 | today, all customers"") need rollup collections maintained by the daemon |
| 5393 | (aggregates are just another collection), or a scan across tenant dirs. |
| 5394 | This is the standard sharding trade and should be designed as rollups, |
| 5395 | not ad-hoc scans. |
| 5396 | - **File-count hygiene.** 100k tenants x N collections is ~1M files — |
| 5397 | fine for modern filesystems, but the directory layout should shard |
| 5398 | (e.g. tenants/ab/abcd.../collections/...) from day one. |
| 5399 | - **The single-TSV invariant holds per collection per tenant** — and the |
| 5400 | whole-instance view (""all tenants' notes as one TSV"") is itself just a |
| 5401 | deterministic concatenation with a tenant column, satisfying the |
| 5402 | emit-one-file rule at the aggregate level when ever needed. |
| 5403 | |
| 5404 | ## Prior Art (the industry is arriving here) |
| 5405 | |
| 5406 | Cloudflare Durable Objects (SQLite per entity, storage co-located with |
| 5407 | logic), Turso (database-per-tenant as a product), the SQLite-per-user |
| 5408 | pattern generally. Per-tenant single-file storage next to per-tenant code |
| 5409 | is the current direction of travel; this system's version is the flavor |
| 5410 | you can `cat`. |
| 5411 | |
| 5412 | Also the oldest advice in the flat-file lineage: Strozzi NoSQL's ""Big |
| 5413 | tables"" doc opens with *""big tables should be avoided in the first place""* — |
| 5414 | use the Unix filesystem to pre-organize relations and keep each one small. |
| 5415 | Per-tenant decomposition is that doctrine, systematized. |
| 5416 | |
| 5417 | ## Current State and Gap |
| 5418 | |
| 5419 | Today the platform is multi-tenant by *rows* (owner_id row filters, one |
| 5420 | shared collection per name) and multi-site by *hosts* (site_hosts). The gap |
| 5421 | this note names: collections themselves are instance-global. The eventual |
| 5422 | shape is tenant-scoped collection roots under one instance — same schemas, |
| 5423 | same permission engine, same generators, same API surface, with the tenant |
| 5424 | resolved from identity the way hosts are resolved from requests today. Not |
| 5425 | scheduled; recorded so the append-only and cache work keep it reachable |
| 5426 | (nothing in either conflicts with tenant-scoped roots — both operate per |
| 5427 | file). |
| 5428 | " |
| 5429 | site-routing Site Routing Sites, UI & Realtime 400 How to turn the object server into a webserver with clean public URLs, a route table, multi-domain hosting, and static asset handling. "Site routing turns the object server into a webserver: clean public URLs |
| 5430 | (`/about`, `/articles/{uuid}`) resolve to objects, so a whole website can be |
| 5431 | built, edited, and rolled back through the normal object loop with no deploy |
| 5432 | step and no per-page reverse-proxy rewrites. |
| 5433 | |
| 5434 | It is off by default and enabled per deployment: |
| 5435 | |
| 5436 | ```text |
| 5437 | DBBASIC_ENABLE_SITE_ROUTES=true |
| 5438 | ``` |
| 5439 | |
| 5440 | ## Resolution Order |
| 5441 | |
| 5442 | Site routing runs only after every built-in route family has declined the |
| 5443 | path, so reserved surfaces (`/objects`, `/admin`, `/api`, `/identity`, |
| 5444 | `/login`, `/health`, `/collections`, `/schemas`, `/events`, `/packages`, |
| 5445 | `/daemon`, `/permissions`, `/logout`, `/signup`, `/verify`, `/reset`, |
| 5446 | `/reset/confirm`) can never be shadowed by a site page. |
| 5447 | |
| 5448 | For everything else: |
| 5449 | |
| 5450 | 1. **Convention.** `/` maps to `site_home`, `/about` to `site_about`, |
| 5451 | `/docs/install` to `site_docs_install`. Hyphens become underscores |
| 5452 | (`/getting-started` → `site_getting_started`). Creating a page object |
| 5453 | creates its URL — the filesystem-routing feel of the original prototype, |
| 5454 | kept because it makes the common case zero-config. |
| 5455 | 2. **The `site_routes` collection.** Records with `pattern`, `object_id`, and |
| 5456 | optional `priority` handle what conventions cannot express: |
| 5457 | |
| 5458 | ```text |
| 5459 | id pattern object_id priority |
| 5460 | r1 /articles/{article_id:uuid} articles_view 10 |
| 5461 | r2 /blog/{slug} blog_post 20 |
| 5462 | ``` |
| 5463 | |
| 5464 | Pattern segments are literal text, `{name}` (any single segment), or |
| 5465 | `{name:uuid}` (segment must be UUID-shaped — the common case for record |
| 5466 | ids, which are UUIDv4 by default). Captured params are merged into the |
| 5467 | object's request payload, so `articles_view` reads |
| 5468 | `request[""article_id""]`. Lower `priority` wins; ties go to the pattern |
| 5469 | with more literal segments. |
| 5470 | 3. **`site_404`.** If nothing resolves and a `site_404` object exists, it |
| 5471 | runs with the missed `path` in its payload and should return |
| 5472 | `status_code: 404`. Without it, the plain JSON 404 stays. |
| 5473 | |
| 5474 | ## Design Decisions |
| 5475 | |
| 5476 | These choices came out of comparing the original prototype's pure filesystem |
| 5477 | router, the route-table-in-object-state design from the early dbbasic.com |
| 5478 | plan, and what the public server has grown since: |
| 5479 | |
| 5480 | - **Routing only maps URLs; authorization stays in the permission policy.** |
| 5481 | The resolved object executes through the normal execution path, so |
| 5482 | enforcement, audit entries, execution logs, timeouts, concurrency limits, |
| 5483 | and correlation ids all apply. Publishing a page is two audited steps: |
| 5484 | create the object, grant `execute` to `public` (or whichever principal). |
| 5485 | A file appearing on disk never silently becomes public under enforcement. |
| 5486 | - **The route table lives in records, not object state.** Records give the |
| 5487 | table schema validation, change history, rollback, Scroll editing, and MCP |
| 5488 | tools for free. Editing the sitemap is a data change with an audit trail. |
| 5489 | - **Convention for the 90%, data for the 10%.** Plain pages need no table |
| 5490 | entry. The table exists for parameterized routes, renames, and pointing |
| 5491 | multiple URLs at one object. |
| 5492 | - **TLS and static assets stay in the reverse proxy.** Caddy terminates TLS |
| 5493 | and should serve `/static/*` from disk with cache headers; site routing |
| 5494 | replaces per-page rewrites with one catch-all proxy block. |
| 5495 | |
| 5496 | ## Deployment |
| 5497 | |
| 5498 | With site routing enabled, the Caddy shape becomes: explicit handles for the |
| 5499 | reserved admin/API surfaces you want public, a `/static/*` file server, and a |
| 5500 | catch-all `reverse_proxy` instead of a catch-all 404. Under permission |
| 5501 | enforcement, unrouted or unauthorized paths still return controlled 403/404 |
| 5502 | responses from the server. |
| 5503 | |
| 5504 | ## Multiple Domains |
| 5505 | |
| 5506 | One object server can serve many websites. The `site_hosts` collection maps |
| 5507 | request hosts to object prefixes: |
| 5508 | |
| 5509 | ```text |
| 5510 | id host prefix home_object not_found_object |
| 5511 | h1 dbbasic.com db |
| 5512 | h2 example.org eg |
| 5513 | ``` |
| 5514 | |
| 5515 | With those records, `/` on dbbasic.com serves `db_home` and `/pricing` |
| 5516 | serves `db_pricing`, while `/` on example.org serves `eg_home` — same server, same |
| 5517 | data directory, fully separate page namespaces. `home_object` and |
| 5518 | `not_found_object` default to `{prefix}_home` and `{prefix}_404` (falling |
| 5519 | back to the generic `site_404`). Hosts without a record keep the default |
| 5520 | `site_*` behavior, so single-site deployments need no configuration. |
| 5521 | `site_routes` pattern records take an optional `host` column; host-specific |
| 5522 | rows only match their domain and beat host-agnostic rows. |
| 5523 | |
| 5524 | Pointing a new domain at the server is then: |
| 5525 | |
| 5526 | 1. DNS: point the domain's A record at the VM. |
| 5527 | 2. Caddy: add a site block for it and reload — Caddy only answers (and only |
| 5528 | fetches certificates) for hostnames it has a block for, and DNS must |
| 5529 | already point at the VM for the certificate challenge to succeed. With |
| 5530 | the `public_site` snippet defined once at the top of the Caddyfile, each |
| 5531 | new domain is three lines: |
| 5532 | |
| 5533 | ```caddyfile |
| 5534 | (public_site) { |
| 5535 | handle /login { reverse_proxy 127.0.0.1:8001 } |
| 5536 | handle /logout { reverse_proxy 127.0.0.1:8001 } |
| 5537 | handle_path /static/* { |
| 5538 | root * /var/lib/dbbasic-static/{args[0]} |
| 5539 | file_server |
| 5540 | header Cache-Control ""public, max-age=3600"" |
| 5541 | } |
| 5542 | handle { reverse_proxy 127.0.0.1:8001 } |
| 5543 | } |
| 5544 | |
| 5545 | newsite.example { |
| 5546 | import public_site newsite |
| 5547 | } |
| 5548 | ``` |
| 5549 | |
| 5550 | Public domains expose only the site surface; keep the admin/API/MCP |
| 5551 | handles only on the operations domain, so public sites never route to |
| 5552 | the operator surface at all. |
| 5553 | 3. Add the `site_hosts` record and create `{prefix}_home` — the site is live. |
| 5554 | |
| 5555 | Identity, sessions, records, policy, and audit are shared across domains: |
| 5556 | one operator account works everywhere, and browsers scope session cookies |
| 5557 | per domain automatically. Domains that must not share those belong on their |
| 5558 | own server instance instead (one process per trust boundary). |
| 5559 | |
| 5560 | ## Static Assets |
| 5561 | |
| 5562 | Site CSS, JavaScript, images, and fonts are served by the reverse proxy from |
| 5563 | a plain directory — never through object execution — so they get file-server |
| 5564 | performance, gzip, and cache headers: |
| 5565 | |
| 5566 | ```caddyfile |
| 5567 | handle_path /static/* { |
| 5568 | root * /var/lib/dbbasic-static |
| 5569 | file_server |
| 5570 | header Cache-Control ""public, max-age=3600"" |
| 5571 | } |
| 5572 | ``` |
| 5573 | |
| 5574 | Pages reference them normally (`<link href=""/static/site.css"">`). The |
| 5575 | directory is deploy-time content owned by the service user; treat it like |
| 5576 | object source (versioned in the site package), not like runtime data. |
| 5577 | User-uploaded files are different: keep those in the object file APIs so they |
| 5578 | inherit permissions, audit, and backups. |
| 5579 | |
| 5580 | ## Writing Site Pages |
| 5581 | |
| 5582 | Site pages are normal objects (see [`object-authoring.md`](/docs/object-authoring)): return a dict for |
| 5583 | JSON, a `content_type`/`body` dict for HTML, use `request[""_identity""]` for |
| 5584 | per-user rendering, and handle `POST` for forms — browser form posts arrive |
| 5585 | as parsed fields with the session cookie applied. Ship a site as a package |
| 5586 | ([`package-authoring.md`](/docs/package-authoring)) so it installs with its schema, seed records, and |
| 5587 | route table rows in one reviewed unit. |
| 5588 | " |
| 5589 | generative-ui Generative UI — One Renderer, Every App Sites, UI & Realtime 410 How a collection's schema alone drives list, form, and detail rendering across every app, and why customizing a generated page never means forking generated code. "There is no per-app UI code. A collection's schema drives a single set of |
| 5590 | generative renderers, served as static scripts (`/list`, `/form`, `/detail`), |
| 5591 | that turn records into live, permission-checked, realtime surfaces. This page |
| 5592 | is the overview; the field-level contract is in |
| 5593 | [`schema-forms.md`](/docs/schema-forms), the behavior decisions in |
| 5594 | [`ui-decisions.md`](/docs/ui-decisions), and the visual system in |
| 5595 | [`design-system.md`](/docs/design-system). |
| 5596 | |
| 5597 | ```mermaid |
| 5598 | flowchart LR |
| 5599 | SCH[""schema<br/>fields · views · capabilities""] --> LIST[""window.dbbasicList""] |
| 5600 | SCH --> FORM[""window.dbbasicForm""] |
| 5601 | SCH --> DET[""window.dbbasicDetail""] |
| 5602 | LIST --> MODES[""list · table · board · tree · calendar""] |
| 5603 | LIST --> FSR[""filters · search · sort · row cap""] |
| 5604 | FORM --> CTRL[""type-aware controls · validation""] |
| 5605 | DET --> COMP[""detail + related + capabilities""] |
| 5606 | CL[""change log (websocket)""] -. re-render .-> LIST |
| 5607 | CL -. re-render .-> DET |
| 5608 | ``` |
| 5609 | |
| 5610 | ## The list, in five modes |
| 5611 | |
| 5612 | `window.dbbasicList(collection, cfg)` resolves `views.list_mode` from the |
| 5613 | schema and renders one of: |
| 5614 | |
| 5615 | - **list** (default) — rich rows: avatar, title, subtitle, meta, tag pills, |
| 5616 | owner edit/delete. |
| 5617 | - **table** — a dense, sortable HTML table over `list_fields`; cells format by |
| 5618 | type (money `_cents` → `$`, boolean → Yes/No, datetime → relative, enum → |
| 5619 | colored badge), and **relation columns show the target's label, not the raw |
| 5620 | id**. Owned rows get the same edit/delete the list has. |
| 5621 | - **board** — a kanban grouped by an enum field; dragging a card issues the |
| 5622 | ordinary status write, so `flow` transitions still gate the move. A board |
| 5623 | collection that also has `list_fields` shows a **Board ⇄ Table** toggle whose |
| 5624 | choice persists per collection. |
| 5625 | - **tree** — nests a self-relation (`parent_id`) into a hierarchy. |
| 5626 | - **calendar** — buckets records by a date field. |
| 5627 | |
| 5628 | Every mode shares **one** fetch/sort/cap/search/subscribe pipeline, so all of |
| 5629 | them inherit: |
| 5630 | |
| 5631 | - **filters** — `views.filter_fields` renders a filter bar (enum → select, |
| 5632 | boolean → Yes/No); a pick narrows the fetch server-side (`field=value`, after |
| 5633 | the permission row filter) and composes with the search box. |
| 5634 | - **search** — the toolbar box, server-side over the collection's `search` |
| 5635 | fields. |
| 5636 | - **the 50-row cap** with a Show-all toggle (no surface ever renders a |
| 5637 | 50,000px page). |
| 5638 | - **realtime** — each surface subscribes to the change log and re-renders when |
| 5639 | a record changes, from any tab, user, or agent. |
| 5640 | |
| 5641 | A mode whose required field can't be derived (no enum for board, no |
| 5642 | self-relation for tree, no date for calendar) falls back to the row list with a |
| 5643 | visible notice — never a blank page. |
| 5644 | |
| 5645 | ## The form |
| 5646 | |
| 5647 | `window.dbbasicForm(collection)` builds a record form from the schema: field |
| 5648 | order from `forms.default.fields`, controls from field semantics (enum → |
| 5649 | select, relation → picker, boolean → checkbox, date → date input, textarea, |
| 5650 | number, text), and labels/help/required/max-length from the field. It handles |
| 5651 | create (POST) and edit (PUT), sets `id`/`owner_id`/`created_at` automatically, |
| 5652 | never writes computed/read-only fields, and supports conditional field |
| 5653 | visibility (`visible_when`). See [`schema-forms.md`](/docs/schema-forms). |
| 5654 | |
| 5655 | ## The detail page |
| 5656 | |
| 5657 | `window.dbbasicDetail` renders one record read-only by reusing the form's own |
| 5658 | field renderer in read-only mode — no second field renderer to keep in sync. It |
| 5659 | adds owner-only Edit/Delete (reusing the form's edit pipeline), always shows |
| 5660 | record metadata (`created_at`/`updated_at`) even when `detail_fields` curates |
| 5661 | the main fields, and auto-mounts any declared **capabilities** (comments, |
| 5662 | attachments, sharing — see [`capabilities.md`](/docs/capabilities)) below the |
| 5663 | detail. Composed detail pages are `views` records with a `detail` block plus |
| 5664 | `related` child blocks; the view renderer |
| 5665 | (`app-views/objects/site/view_render.py`) assembles them. |
| 5666 | |
| 5667 | A `textarea`-type field shown read-only gets a safe, minimal markdown |
| 5668 | subset (bold, italic, links, paragraph breaks) — the same transform the |
| 5669 | standalone `markdown` block below applies — instead of plain escaped text |
| 5670 | in a `<span>`, which used to collapse multi-line content into one |
| 5671 | run-together line. |
| 5672 | |
| 5673 | ## Other view block kinds |
| 5674 | |
| 5675 | Beyond `list`/`form`/`detail`/`related`, a view's `blocks` array can also |
| 5676 | declare: |
| 5677 | |
| 5678 | - **`markdown`** — a block of static prose baked directly into the view |
| 5679 | definition (`{kind: ""markdown"", text: ""...""}`), the same escape-first, |
| 5680 | safe-subset renderer as the textarea treatment above. |
| 5681 | - **`reader`** — `{kind: ""reader"", url: ""...""}` fetches a URL through the |
| 5682 | flag-gated, signed-in-only `POST /api/read` and renders title + body text |
| 5683 | + a numbered link list. See [`shell-and-ai.md`](/docs/shell-and-ai)'s |
| 5684 | ""Reading the Web"" section for the SSRF posture and the voice-navigation |
| 5685 | loop this backs. |
| 5686 | - **`count`** / **`aggregate`** — live stat cards over a collection (row |
| 5687 | count, or a sum of numeric/`_cents` fields, with an optional |
| 5688 | balanced/not-balanced badge for double-entry-style checks). |
| 5689 | - **`thread`** — sugar for a comment/reply thread capability. |
| 5690 | - **`object`** — mounts an arbitrary object's own rendered output inline. |
| 5691 | |
| 5692 | Every kind subscribes to its source collection and re-renders live, the |
| 5693 | same as `list`/`related`. An unrecognized kind (or one missing a required |
| 5694 | field) renders a small ""unsupported"" placeholder card rather than breaking |
| 5695 | the page. |
| 5696 | |
| 5697 | ## Why this is the point |
| 5698 | |
| 5699 | Adding an app is a schema file. The list, the table, the board, the toggle, |
| 5700 | the filters, the form, the detail page, badges, the row cap, relation labels, |
| 5701 | realtime, and owner actions all fall out of it — the same code for every app. |
| 5702 | The measure isn't the feature list (anyone can claim those); it's the amount of |
| 5703 | per-app code, which is a schema and at most one page object. |
| 5704 | |
| 5705 | ## This is not scaffolding |
| 5706 | |
| 5707 | Rails scaffolds and Django's startapp share one failure that defined a |
| 5708 | generation of frameworks: the generator emits **code**, you edit it, and from |
| 5709 | that moment you own all of it. The generator can never help that screen again |
| 5710 | — template improvements don't flow, upgrades don't apply, and nothing records |
| 5711 | which parts you changed. The fork happens at generation time and diverges |
| 5712 | silently forever. ""Eject"" is the same failure with a button on it. |
| 5713 | |
| 5714 | The rule that keeps this system on the other side of that line: |
| 5715 | |
| 5716 | > **Generated output is never materialized, so it can never be edited.** |
| 5717 | > A page is a view record *interpreted at request time* by a renderer that is |
| 5718 | > itself an ordinary object. Customizing never means editing emitted code, |
| 5719 | > because there is no emitted code. You either change **data** (and keep |
| 5720 | > receiving renderer improvements) or you write **your own object** (which was |
| 5721 | > never generated, so nothing was forked). |
| 5722 | |
| 5723 | ### The customization ladder |
| 5724 | |
| 5725 | Each rung says exactly what you take ownership of and what keeps flowing: |
| 5726 | |
| 5727 | 1. **Edit the block config** (filters, `title_field`, sort, `row_limit`) — you |
| 5728 | own the config; every renderer improvement still flows. |
| 5729 | 2. **Add blocks** — a view is a list of blocks; put an `aggregate` summary or |
| 5730 | `markdown` intro above the generated list. Same ownership as (1). |
| 5731 | 3. **Customize a shipped view record** — the upgrade system detects it against |
| 5732 | the package baseline and parks a reconcile instead of clobbering: the system |
| 5733 | *records* what you own and shows you when upstream moved. Scaffolding's |
| 5734 | fork is silent; this one has a ledger. |
| 5735 | 4. **Drop an `object` block into a generated page** — one hand-written panel |
| 5736 | among generated ones (`{""kind"": ""object"", ""object_id"": ""site_my_panel""}`). |
| 5737 | You own that panel; the rest of the page keeps flowing. It runs through the |
| 5738 | ordinary execution path, so permissions and audit apply — the block widens |
| 5739 | what a page can *show*, never what a viewer may *see*. |
| 5740 | 5. **Write the whole page object.** Convention routing means creating |
| 5741 | `site/notes.py` instantly overrides the generated `/notes` — and deleting |
| 5742 | the file reverts to it. The override is total, explicit, and reversible, |
| 5743 | and it is visible in the objects listing rather than buried in a diff |
| 5744 | against generator output. |
| 5745 | |
| 5746 | ### Why replacing a page is safe here and wasn't in Rails |
| 5747 | |
| 5748 | The deep failure of scaffolds wasn't the HTML — it was that the scaffold |
| 5749 | contained **rules** (validations in the controller, logic in the view), so |
| 5750 | editing it forked the rules. Here the doctrine is that *a page may never be |
| 5751 | the only place a rule exists*: enforcement lives in the schema, hooks, |
| 5752 | transitions, and permissions, on the shared write path that the JSON API, MCP |
| 5753 | agents, and the websocket all go through. |
| 5754 | |
| 5755 | That doctrine is not just policy — the architecture makes the wrong place |
| 5756 | **fail loudly**. A rule written into a page object simply does not gate API or |
| 5757 | MCP writes, so the mistake shows up the first time anything that isn't the |
| 5758 | page touches the collection. In Rails, logic in the controller *worked* for |
| 5759 | web users, which is exactly why the fork stayed invisible for years. The |
| 5760 | residual risk here is someone treating rung 4–5 as a place to put gates; the |
| 5761 | system's answer is that gates there provably don't hold, and the hook is one |
| 5762 | file away. |
| 5763 | |
| 5764 | ## Related |
| 5765 | |
| 5766 | - [`schema-forms.md`](/docs/schema-forms) — the field-level contract these |
| 5767 | renderers read. |
| 5768 | - [`ui-decisions.md`](/docs/ui-decisions) — the living log of interaction |
| 5769 | decisions (detail-vs-edit, the row cap, board flex, filters, relation labels, |
| 5770 | capabilities) and the reasons behind them. |
| 5771 | - [`design-system.md`](/docs/design-system) — semantic tokens, themes as data, and |
| 5772 | the stylesheet served as an object. |
| 5773 | - [`capabilities.md`](/docs/capabilities) — the behavior layer mounted on detail. |
| 5774 | " |
| 5775 | design-system The Design System Sites, UI & Realtime 420 How DBBASIC's design system works as a semantic contract with a thin, themeable renderer, delivered as a live object rather than a static component library. "DBBASIC's design system is not a component library you depend on — it is |
| 5776 | a **semantic contract with a thin, themeable renderer, delivered as an |
| 5777 | object.** It has three layers, and only the top one is pixels. |
| 5778 | |
| 5779 | ```mermaid |
| 5780 | flowchart TD |
| 5781 | SEM[""Layer 1 — Semantics<br/>schema: types, enum, relation,<br/>list_mode, transitions, permissions""] --> REND |
| 5782 | TOK[""Layer 2 — Tokens<br/>semantic roles: surface, text,<br/>accent, positive/warning/danger""] --> REND |
| 5783 | REND[""Layer 3 — Renderers<br/>web pages · Scroll · shell · AI""] |
| 5784 | TOK -.theme = a set of role values.-> THEMES[""Themes as data:<br/>base · paper · terminal · yours""] |
| 5785 | ``` |
| 5786 | |
| 5787 | ## The governing idea: define once, project everywhere, own no copies |
| 5788 | |
| 5789 | Everything below is one principle seen from different angles. State the |
| 5790 | design once — as tokens, as a shared stylesheet object, as a nav object, |
| 5791 | as a schema — and let every surface *project* it. No page owns a copy of |
| 5792 | the theme; it references `/style`. No page owns a copy of the nav; it |
| 5793 | includes `/nav`. No app hardcodes a widget; it declares a field's |
| 5794 | meaning. Because nothing downstream owns a copy, changing the source |
| 5795 | changes the whole product at once, with nothing to chase. |
| 5796 | |
| 5797 | This is why rebranding the entire twelve-app suite and giving it a shared |
| 5798 | navigation bar was **two objects edited live** — no deploy, no migration, |
| 5799 | no per-page rework. If a future change to the look or the chrome ever |
| 5800 | requires editing many pages, that is the signal that a copy leaked in and |
| 5801 | should be pulled back into a shared object. Guard this property; it is the |
| 5802 | whole value. |
| 5803 | |
| 5804 | ## Layer 1 — Semantics (the source of truth) |
| 5805 | |
| 5806 | Design decisions live in the schema, not in markup. A field that declares |
| 5807 | `enum` *means* ""one of these values""; each surface picks its own control |
| 5808 | (dropdown on the web, segmented control in Scroll, a spoken list to the |
| 5809 | AI). `views.list_mode` picks table / cards / feed. `transitions` says |
| 5810 | which state moves are legal. Permissions decide which controls exist at |
| 5811 | all. See [schema forms](/docs/schema-forms) and [permissions](/docs/permissions-model). |
| 5812 | |
| 5813 | **We deliberately do not use a widget-prescriptive `ui_schema`.** The |
| 5814 | predecessor paired each schema with a React-JSON-Schema-Form |
| 5815 | `ui_schema` that said things like `""ui:widget"": ""radio""`. That only ever |
| 5816 | renders on one surface — a `radio` hint is meaningless to an AI, the |
| 5817 | shell, a voice interface, or a native app. Semantics render everywhere; |
| 5818 | widget instructions render once. This is the single most important choice |
| 5819 | in the system, and the reason a design here can span surfaces that do not |
| 5820 | exist yet. |
| 5821 | |
| 5822 | **Permissions are affordances.** A control exists because the caller can |
| 5823 | perform the action, not because markup drew it and then hid it. A delete |
| 5824 | button appears when the policy allows delete; a project filter appears |
| 5825 | because there is a `project_id` relation; a column appears because |
| 5826 | `list_fields` lists it. The design system renders *capability* — which is |
| 5827 | why an AI acting for a user, or a shared component, can never show a |
| 5828 | control the user could not actually use. |
| 5829 | |
| 5830 | ## Layer 2 — Tokens (roles, not colors) |
| 5831 | |
| 5832 | The visual vocabulary is a small set of **semantic roles** — surface |
| 5833 | (`bg`, `panel`, `line`), text (`text`, `muted`), `accent`, and status |
| 5834 | (`positive`, `warning`, `danger`) — plus spacing, radii, shadow, and two |
| 5835 | type families. Components are written against the roles, never against |
| 5836 | raw colors, so a retheme changes values in one place and nothing in any |
| 5837 | page moves. |
| 5838 | |
| 5839 | ## Layer 3 — Renderers, and the design system *as an object* |
| 5840 | |
| 5841 | The stylesheet is itself a DBBASIC object: **`site_style`, served at |
| 5842 | `/style`.** Every page links to it (`<link rel=""stylesheet"" href=""/style"">`) |
| 5843 | instead of carrying its own CSS. Because it is an object, the whole visual |
| 5844 | system is versioned, rollback-able, and live-editable like everything |
| 5845 | else — retheming is one reversible object change, not a deploy. |
| 5846 | |
| 5847 | Other renderers consume the same two layers: Scroll's generated Flutter |
| 5848 | forms and lists, the shell's terminal, and the AI (whose ""UI"" is the |
| 5849 | schema's `label`/`help` text — good microcopy is design work that serves |
| 5850 | the form, the accessibility label, and the AI tool description at once). |
| 5851 | |
| 5852 | ## The app shell — chrome contributed, not copied |
| 5853 | |
| 5854 | Navigation is part of the design system, and it follows the same rule. |
| 5855 | The **`site_nav` object, served at `/nav`,** injects one shared top bar |
| 5856 | into every page that includes `<script src=""/nav""></script>`: brand, an |
| 5857 | app switcher across installed apps, global search (`⌘K` / `Ctrl-K`) over |
| 5858 | `/api/search`, an Ask-AI link to the shell, a notification bell reading |
| 5859 | the `notifications` collection, and a user menu (appearance, sign out). |
| 5860 | Its styling lives in `/style`, so it themes with everything else. |
| 5861 | |
| 5862 | The point is that a *package* (`app-theme`) contributes this bar to every |
| 5863 | other app without those apps knowing — a thing a Django app could never do |
| 5864 | to its siblings. Adding a nav item is one edit to one object; every app |
| 5865 | gets it. If you find yourself pasting nav markup into a page, stop: add it |
| 5866 | to `site_nav`. |
| 5867 | |
| 5868 | The bell is **live**: it subscribes to the `notifications` collection over |
| 5869 | the `/ws` websocket and updates the instant something happens, with a 20s |
| 5870 | poll as backup. Every app page is live the same way — each subscribes to |
| 5871 | its collection and auto-refreshes (150ms debounced) when a record it can |
| 5872 | see changes, over the one shared socket, via |
| 5873 | `window.dbbasicSubscribe(collection, handler)`. Add a live list to a new |
| 5874 | page in one line. Auto-update on events is the thing the old |
| 5875 | dashboard/Channels stacks never did cleanly — see the |
| 5876 | [realtime contract](/docs/http-api-contract#realtime-push-websocket). |
| 5877 | |
| 5878 | ## Themes are data — and packages |
| 5879 | |
| 5880 | A **theme is just a set of values for the token roles.** `site_style` |
| 5881 | ships three built in: |
| 5882 | |
| 5883 | - **base** — the DBBASIC identity: a warm dark (per the earth-theme rule |
| 5884 | ""warm, not cold blue-black"") with a terracotta/ember accent, carried |
| 5885 | forward from the palette an earlier project already established. |
| 5886 | - **paper** — a warm light theme. |
| 5887 | - **terminal** — high-contrast green-on-black. |
| 5888 | |
| 5889 | The active theme lives in the object's state. There is a visual chooser |
| 5890 | at **`/appearance`** (the `site_appearance` object): it reads the |
| 5891 | available themes and their preview swatches from `/style?info=true` and |
| 5892 | lets an admin click one to reskin the whole instance; non-admins see the |
| 5893 | active theme read-only. Or switch over HTTP: |
| 5894 | |
| 5895 | ```http |
| 5896 | POST /style {""theme"": ""terminal""} # admin session only |
| 5897 | POST /style {""tokens"": {""accent"": ""#5aa7ff""}} # custom role overrides |
| 5898 | GET /style?info=true # {active, available, previews, tokens} |
| 5899 | ``` |
| 5900 | |
| 5901 | `site_style` self-gates writes to admin sessions (using the unspoofable |
| 5902 | injected identity), so a public `execute` grant can serve the CSS to |
| 5903 | everyone while only operators change the look. |
| 5904 | |
| 5905 | **A theme is a package.** Installing a package that ships its own |
| 5906 | `site_style` (or that sets custom tokens) reskins the whole instance — |
| 5907 | design distributed the same way apps are. A community can publish themes; |
| 5908 | you install the one you like; you can fork it because it is one small, |
| 5909 | readable object. Per-user theming (each account choosing a theme) is a |
| 5910 | planned extension built on the same roles plus the `shell_preferences` |
| 5911 | pattern. |
| 5912 | |
| 5913 | ## Forms, tables, search, and filters |
| 5914 | |
| 5915 | The base stylesheet carries a genuinely complete component vocabulary so |
| 5916 | generated UIs and hand-written pages share one look: form fields with |
| 5917 | labels/help/required markers and validation states; tables with sortable |
| 5918 | headers, hover, numeric alignment, and pagination; a toolbar with a search |
| 5919 | input and filter chips; buttons as **intents** (primary / neutral / |
| 5920 | danger) rather than colors; badges; and first-class empty / loading / |
| 5921 | denied / error states. |
| 5922 | |
| 5923 | That is the visual layer. The **generative renderer** that reads a schema |
| 5924 | and emits these — the successor to an earlier project's `django_tables2` + `django_filters` |
| 5925 | (which worked because they were declarative from a single source) unified |
| 5926 | across table, cards, and feed with search and filters wired to |
| 5927 | `search.fields` — is the next build. The earlier project's honest lesson is that this |
| 5928 | substrate must be *one* renderer, not the four disconnected |
| 5929 | implementations it grew (django_tables2 for tables, two incompatible |
| 5930 | form engines, hand-written cards and feeds). The semantics and the token |
| 5931 | vocabulary are now in place for it. |
| 5932 | |
| 5933 | ## Building a page against the design system |
| 5934 | |
| 5935 | ```html |
| 5936 | <link rel=""stylesheet"" href=""/style""> |
| 5937 | ... |
| 5938 | <div class=""wrap""> |
| 5939 | <header class=""app""><h1>Notes</h1><div class=""who"">…</div></header> |
| 5940 | <div class=""toolbar""> |
| 5941 | <input class=""search grow"" placeholder=""Search…""> |
| 5942 | <div class=""filters""><button class=""chip"" aria-pressed=""true"">All</button></div> |
| 5943 | </div> |
| 5944 | <div class=""cards"">…</div> |
| 5945 | </div> |
| 5946 | ``` |
| 5947 | |
| 5948 | No inline CSS, no framework, no build step — just the shared classes. When |
| 5949 | the instance's theme changes, this page changes with it. Page-unique |
| 5950 | layout (a form's column grid, an edit-mode toggle) may stay in a small |
| 5951 | `<style>` block, but it must use the token variables (`var(--panel)`, |
| 5952 | `var(--line)`, `var(--accent)`) — never hardcoded colors — so it reskins |
| 5953 | too. |
| 5954 | |
| 5955 | ## Why this is a design system, not a style guide |
| 5956 | |
| 5957 | The test that separates the two: **change the source, and does the whole |
| 5958 | product change with no copies to chase?** Here it does — edit `/style`, |
| 5959 | every page reskins; edit `/nav`, every page's chrome updates; edit a |
| 5960 | schema, every surface re-renders that field. A folder of CSS classes and a |
| 5961 | component catalog is a style guide; you still hand-apply it and it drifts. |
| 5962 | A design system propagates from one place. Protect that difference: the |
| 5963 | day a change stops propagating is the day it quietly became a style guide. |
| 5964 | |
| 5965 | ## Why not a dashboard template |
| 5966 | |
| 5967 | The web-template industry (Bootstrap admin themes, and the marketplaces |
| 5968 | that sell them — an earlier project itself shipped on the ""Volt"" dashboard) assumed |
| 5969 | **everything is a dashboard**: a fixed chrome of sidebar, topbar, cards, |
| 5970 | and a data table, into which you pour your app. That is widgets-before- |
| 5971 | meaning — the shape is the product, and the only app you can express is |
| 5972 | the one the widgets already draw. It is the same mistake as a |
| 5973 | widget-prescriptive `ui_schema`, at the scale of a whole product. It is |
| 5974 | also why that earlier project accumulated 110 KB of override CSS *fighting* its template: |
| 5975 | when the chrome is copied into every page, changing it means fighting it |
| 5976 | everywhere. |
| 5977 | |
| 5978 | Reading modes (`table` / `cards` / `feed`) are the direct rejection of the |
| 5979 | one-shape assumption: a note is read individually (cards), a task is |
| 5980 | compared to others (table), a message is sequential (feed). The dashboard |
| 5981 | world only had the table. |
| 5982 | |
| 5983 | The reason no one built it this way earlier is not taste, it is |
| 5984 | arithmetic. Projecting one schema into a web form, a table, a Flutter |
| 5985 | widget, an AI tool description, and an accessibility label meant |
| 5986 | hand-writing five renderers per app — insane in 2015, so buying the frozen |
| 5987 | template was rational. What changed is that the schema is now legible to a |
| 5988 | model, a model can render a surface, and the runtime hot-loads it with no |
| 5989 | deploy — so the marginal cost of a surface collapsed, and the correct |
| 5990 | architecture (declare meaning once, project everywhere) finally pays. Build |
| 5991 | for that, not for the dashboard era. |
| 5992 | |
| 5993 | ## Current edges (honest) |
| 5994 | |
| 5995 | - **Theme-complete, component-incomplete.** The token/theme/app-shell |
| 5996 | layers are done and propagate. The component *vocabulary* exists in |
| 5997 | `/style`, but pages still assemble it by hand — the **generative |
| 5998 | renderer** (schema → dense list with row actions, filters, and relative |
| 5999 | timestamps) is not built yet. It is the next big design build, and it |
| 6000 | needs a `created_at` field added to schemas first (nothing captures |
| 6001 | creation time today, so there are no relative timestamps to show). |
| 6002 | - **Web + tokens today.** Scroll shares the token *roles* but the web and |
| 6003 | Flutter renderers are not unified against one contract yet. |
| 6004 | - **Instance-level theming.** Per-user theme choice is a planned extension |
| 6005 | on the same roles plus `shell_preferences`. |
| 6006 | - **The shell page** (`/shell`) deliberately keeps its own terminal palette |
| 6007 | and does not link `/style` or `/nav` — a focused full-screen mode. The |
| 6008 | admin dashboard is not yet on the shared shell either. |
| 6009 | |
| 6010 | ## Extending it correctly — rules for future builds |
| 6011 | |
| 6012 | When adding to the design system, keep the propagation property intact: |
| 6013 | |
| 6014 | 1. **Contribute, don't copy.** New chrome goes in a shared object |
| 6015 | (`site_style`, `site_nav`), never pasted into pages. If it must live in |
| 6016 | a page, it is page-unique and must use tokens. |
| 6017 | 2. **Tokens are roles, never hex.** Add a role (e.g. `--info`) if you need |
| 6018 | a new meaning; never a raw color in a component or a page. |
| 6019 | 3. **Semantics, not widgets.** Express new capability as schema meaning |
| 6020 | (a new field key, a new `views` mode) that every surface can interpret |
| 6021 | — resist any per-surface ""render as X"" instruction; that is `ui_schema` |
| 6022 | returning, and it collapses you back to one surface. |
| 6023 | 4. **Let permissions draw the controls.** Show an action because the |
| 6024 | policy allows it, not because you wrote the button. |
| 6025 | 5. **One renderer per concern.** When the generative renderer lands, route |
| 6026 | all lists/forms through it — do not grow a second form engine. The earlier project grew |
| 6027 | four; that fragmentation is the failure mode to avoid. |
| 6028 | 6. **No framework to fight.** Do not adopt a CSS framework you will then |
| 6029 | override. The system is small and authoritative on purpose. |
| 6030 | 7. **If a change stops propagating, fix the leak** — pull the copy back |
| 6031 | into the shared object — rather than editing many pages. |
| 6032 | |
| 6033 | Follow these and the next person (or the next model, or a stranger who |
| 6034 | forks this) can retheme, re-chrome, or extend the whole product from a |
| 6035 | handful of objects — which is the point. |
| 6036 | " |
| 6037 | rest-and-object-messages REST and Object Messages Sites, UI & Realtime 430 How the DBBASIC Object Server splits its HTTP API into RESTful resources, object messages, and realtime streams — and why that split matters. "DBBASIC should be RESTful where it exposes resources and direct where it |
| 6038 | executes behavior. |
| 6039 | |
| 6040 | The goal is not to pretend every operation is pure REST. The goal is to keep a |
| 6041 | clean split: |
| 6042 | |
| 6043 | ```mermaid |
| 6044 | flowchart LR |
| 6045 | A[""HTTP API""] --> B[""Resources""] |
| 6046 | A --> C[""Object messages""] |
| 6047 | A --> D[""Streams""] |
| 6048 | |
| 6049 | B --> B1[""source""] |
| 6050 | B --> B2[""state""] |
| 6051 | B --> B3[""logs""] |
| 6052 | B --> B4[""files""] |
| 6053 | B --> B5[""versions""] |
| 6054 | B --> B6[""metadata""] |
| 6055 | |
| 6056 | C --> C1[""execute method""] |
| 6057 | C --> C2[""run job""] |
| 6058 | C --> C3[""handle webhook""] |
| 6059 | C --> C4[""perform admin action""] |
| 6060 | |
| 6061 | D --> D1[""WebSocket events""] |
| 6062 | D --> D2[""Server-Sent Events""] |
| 6063 | ``` |
| 6064 | |
| 6065 | ## Why This Matters |
| 6066 | |
| 6067 | Many APIs called REST are really RPC over HTTP: |
| 6068 | |
| 6069 | ```text |
| 6070 | POST /doThing |
| 6071 | POST /executeAction |
| 6072 | POST /api/run |
| 6073 | ``` |
| 6074 | |
| 6075 | That shape is easy to add, but it hides what the system actually owns. DBBASIC |
| 6076 | objects own real resources: source, state, logs, files, versions, and metadata. |
| 6077 | Those should be exposed as resources with stable paths, predictable HTTP |
| 6078 | methods, status codes, and JSON representations. |
| 6079 | |
| 6080 | Object behavior is different. Executing an object is message passing. Jobs, |
| 6081 | events, webhooks, and realtime commands are also messages. They should be |
| 6082 | documented as messages instead of disguised as fake CRUD resources. |
| 6083 | |
| 6084 | ## RESTful Resource Surface |
| 6085 | |
| 6086 | DBBASIC should keep these resource-style endpoints boring and predictable: |
| 6087 | |
| 6088 | ```text |
| 6089 | GET /objects |
| 6090 | POST /objects |
| 6091 | GET /objects/{object_id}?source=true |
| 6092 | PUT /objects/{object_id}?source=true |
| 6093 | GET /objects/{object_id}?state=true |
| 6094 | GET /objects/{object_id}?logs=true |
| 6095 | GET /objects/{object_id}?versions=true |
| 6096 | GET /objects/{object_id}?version=N |
| 6097 | DELETE /objects/{object_id}?destroy=true |
| 6098 | ``` |
| 6099 | |
| 6100 | These endpoints expose things the object server owns. |
| 6101 | |
| 6102 | They should preserve: |
| 6103 | |
| 6104 | - stable object identity |
| 6105 | - standard HTTP status codes |
| 6106 | - JSON response shapes existing clients can keep using |
| 6107 | - explicit authorization checks |
| 6108 | - useful cache behavior where safe |
| 6109 | - compatibility with `docs/http-api-contract.md` |
| 6110 | |
| 6111 | ## Object Message Surface |
| 6112 | |
| 6113 | Object execution is not only CRUD. It is behavior: |
| 6114 | |
| 6115 | ```text |
| 6116 | GET /objects/{object_id} |
| 6117 | POST /objects/{object_id} |
| 6118 | PUT /objects/{object_id} |
| 6119 | DELETE /objects/{object_id} |
| 6120 | ``` |
| 6121 | |
| 6122 | Those calls deliver a method and payload to the object. |
| 6123 | |
| 6124 | That model is closer to: |
| 6125 | |
| 6126 | ```text |
| 6127 | object_id + method + payload -> result |
| 6128 | ``` |
| 6129 | |
| 6130 | than: |
| 6131 | |
| 6132 | ```text |
| 6133 | table + row + CRUD operation |
| 6134 | ``` |
| 6135 | |
| 6136 | This is intentional. A DBBASIC object can represent a report, worker, webhook, |
| 6137 | view, business process, queue handler, generated UI, or admin tool. |
| 6138 | |
| 6139 | ## Rollback |
| 6140 | |
| 6141 | Rollback is the awkward case: |
| 6142 | |
| 6143 | ```text |
| 6144 | POST /objects/{object_id} |
| 6145 | {""action"": ""rollback"", ""version_id"": 1} |
| 6146 | ``` |
| 6147 | |
| 6148 | That is a message, not a pure REST resource update. It is kept for compatibility |
| 6149 | with existing clients. |
| 6150 | |
| 6151 | Future server code may add a cleaner resource-style alias, but it should not |
| 6152 | break the existing message shape without a migration: |
| 6153 | |
| 6154 | ```text |
| 6155 | POST /objects/{object_id}/versions/{version_id}/rollback |
| 6156 | ``` |
| 6157 | |
| 6158 | ## Design Rule |
| 6159 | |
| 6160 | Do not turn every operation into `/api/doThing`. |
| 6161 | |
| 6162 | Use resources for object-owned data: |
| 6163 | |
| 6164 | ```text |
| 6165 | source, state, logs, files, versions, metadata |
| 6166 | ``` |
| 6167 | |
| 6168 | Use messages for object-owned behavior: |
| 6169 | |
| 6170 | ```text |
| 6171 | execute, run, handle, repair, migrate, broadcast |
| 6172 | ``` |
| 6173 | |
| 6174 | Use streams for object-owned realtime feedback: |
| 6175 | |
| 6176 | ```text |
| 6177 | source changed, state changed, log appended, version saved, execution failed |
| 6178 | ``` |
| 6179 | |
| 6180 | That is the honest shape of DBBASIC: REST where resources are real, object |
| 6181 | messages where behavior is real, and streams where live feedback is real. |
| 6182 | " |
| 6183 | realtime Realtime: The Change Log and Live Surfaces Sites, UI & Realtime 440 How DBBASIC Object Server pushes change notifications over a websocket without ever putting record data on the wire, and why that design choice matters. "Every generative surface — every list, table, board, detail page, comment |
| 6184 | thread, and attachment list — subscribes to the change log and re-renders when a |
| 6185 | record it can see changes, from any tab, user, or agent. This falls out of one |
| 6186 | small websocket contract with a deliberate rule: **the wire carries a signal, |
| 6187 | never the record body.** |
| 6188 | |
| 6189 | ```mermaid |
| 6190 | sequenceDiagram |
| 6191 | participant Writer as any write (web/API/agent) |
| 6192 | participant Server |
| 6193 | participant Hub as realtime hub |
| 6194 | participant Client as a live surface |
| 6195 | |
| 6196 | Client->>Server: connect /ws (session), subscribe [collections] |
| 6197 | Server->>Server: may this subject READ each collection? |
| 6198 | Server-->>Client: {type: subscribed, collections} |
| 6199 | Writer->>Server: create/update/delete a record |
| 6200 | Server->>Hub: publish {collection, record_id, action} |
| 6201 | Hub->>Hub: per subscriber, re-run the READ decision |
| 6202 | Hub-->>Client: {type: record, collection, record_id, action} |
| 6203 | Client->>Server: refetch through the normal permission-enforced API |
| 6204 | Client->>Client: re-render |
| 6205 | ``` |
| 6206 | |
| 6207 | ## Transport |
| 6208 | |
| 6209 | `GET /ws` (upgraded to a websocket). The connection is **authenticated** — a |
| 6210 | session cookie or bearer token — and anonymous connections are refused (`1008`). |
| 6211 | Realtime is behind a flag; when off, surfaces fall back to polling. |
| 6212 | |
| 6213 | ## Client protocol |
| 6214 | |
| 6215 | Messages are JSON. On accept, the server sends `{""type"": ""welcome"", ""user"": ...}`. |
| 6216 | Then: |
| 6217 | |
| 6218 | | Client sends | Server replies | |
| 6219 | |--------------|----------------| |
| 6220 | | `{""action"": ""subscribe"", ""collections"": [""tasks"", ""notes""]}` | `{""type"": ""subscribed"", ""collections"": [...]}` — only the collections the subject may read are kept | |
| 6221 | | `{""action"": ""unsubscribe"", ""collections"": [...]}` | `{""type"": ""subscribed"", ""collections"": [...]}` | |
| 6222 | | `{""action"": ""ping""}` | `{""type"": ""pong""}` | |
| 6223 | |
| 6224 | Subscriptions are capped per connection, and each collection name is validated. |
| 6225 | |
| 6226 | In the browser this is wrapped as one helper, `window.dbbasicSubscribe(collection, |
| 6227 | handler)` (served by the `nav` object): it opens the socket once, subscribes on |
| 6228 | demand, reconnects with backoff, and runs a ~20-second poll as a fallback for |
| 6229 | missed events and multi-worker deployments. A page never talks to `/ws` |
| 6230 | directly — it calls `dbbasicSubscribe` and re-renders in the handler. |
| 6231 | |
| 6232 | ## The event |
| 6233 | |
| 6234 | A change pushes exactly: |
| 6235 | |
| 6236 | ```json |
| 6237 | { ""type"": ""record"", ""collection"": ""tasks"", ""record_id"": ""…"", ""action"": ""update"" } |
| 6238 | ``` |
| 6239 | |
| 6240 | `action` is `create` / `update` / `delete`. **No field values travel** — only |
| 6241 | which record changed. The client reacts by *refetching* through the ordinary |
| 6242 | API, which re-applies the full permission policy and field redaction. So a live |
| 6243 | surface can never show a field the API wouldn't have served. |
| 6244 | |
| 6245 | ## Permission filtering — twice |
| 6246 | |
| 6247 | Realtime is inside the permission engine, not beside it: |
| 6248 | |
| 6249 | 1. **On subscribe** — a subject may follow a collection only if it may `READ` |
| 6250 | it (`_ws_can_subscribe` runs the same check a `GET` would). |
| 6251 | 2. **On publish** — for each subscriber, the server re-runs the READ decision |
| 6252 | *against the changed record*, so a row-filtered subscriber only hears about |
| 6253 | rows its filter would let it see. If the policy can't be loaded to filter |
| 6254 | safely, nothing is pushed. |
| 6255 | |
| 6256 | Combined with the signal-only payload, this means the change log leaks neither |
| 6257 | the existence of records you can't see (filtered per-subscriber) nor their |
| 6258 | contents (never sent). |
| 6259 | |
| 6260 | ## Why signal, not body |
| 6261 | |
| 6262 | - **Security** — the wire can't leak a field, because it carries none. All |
| 6263 | reads go back through the one enforced path. |
| 6264 | - **Simplicity** — there is no second serialization/redaction path to keep in |
| 6265 | sync with the API; the client just refetches. |
| 6266 | - **Correctness under races** — the refetch always returns the current row, so a |
| 6267 | burst of edits collapses to one correct re-render rather than replaying stale |
| 6268 | bodies. |
| 6269 | |
| 6270 | The durable, poll-based event log remains the fallback for missed pushes and |
| 6271 | for deployments with more than one worker process. |
| 6272 | |
| 6273 | ## Related |
| 6274 | |
| 6275 | - [`asgi-realtime-direction.md`](/docs/asgi-realtime-direction) — why the server |
| 6276 | uses plain ASGI and how websocket/SSE object events fit the direction. |
| 6277 | - [`generative-ui.md`](/docs/generative-ui) — the surfaces that subscribe. |
| 6278 | - [`permissions-model.md`](/docs/permissions-model) — the READ decision reused on |
| 6279 | subscribe and on every push. |
| 6280 | - `runtime-contract.md` — the daemon and event contracts |
| 6281 | behind the durable log. |
| 6282 | " |
| 6283 | asgi-realtime-direction ASGI and Realtime Direction Sites, UI & Realtime 450 Why DBBASIC's ASGI layer stays close to persistent CGI, what it borrows from Phoenix/Erlang, and how the websocket realtime overlay sits on top of the durable event log. "The working prototype used plain ASGI with Uvicorn, not Django ASGI, Channels, |
| 6284 | FastAPI, or Starlette. |
| 6285 | |
| 6286 | The shape was simple: |
| 6287 | |
| 6288 | ```mermaid |
| 6289 | flowchart LR |
| 6290 | A[""Uvicorn""] --> B[""ASGI app""] |
| 6291 | B --> C[""Filesystem router""] |
| 6292 | C --> D[""api/*.py handlers""] |
| 6293 | ``` |
| 6294 | |
| 6295 | That kept the useful part of classic CGI: |
| 6296 | |
| 6297 | ```mermaid |
| 6298 | flowchart LR |
| 6299 | A[""URL""] --> B[""File""] |
| 6300 | B --> C[""Function""] |
| 6301 | ``` |
| 6302 | |
| 6303 | but without classic CGI's process-per-request cost. |
| 6304 | |
| 6305 | That is a better comparison than saying DBBASIC is a Rails-like app structure. |
| 6306 | The goal is closer to persistent CGI with a reusable object runtime: |
| 6307 | |
| 6308 | - filesystem paths can map to runnable code |
| 6309 | - the server stays warm between requests |
| 6310 | - routing is derived from object source placement |
| 6311 | - common helpers provide state, logs, files, versions, and scheduling |
| 6312 | - object boundaries stay small enough for humans and AI tools to inspect |
| 6313 | |
| 6314 | Classic CGI made deployment easy but left too much work to each script. DBBASIC |
| 6315 | keeps the direct path-to-code idea and adds the shared runtime pieces that make |
| 6316 | objects reusable as application building blocks. |
| 6317 | |
| 6318 | ## Why ASGI Matters |
| 6319 | |
| 6320 | ASGI gives DBBASIC one server surface for: |
| 6321 | |
| 6322 | - normal HTTP requests |
| 6323 | - long-lived WebSocket connections |
| 6324 | - Server-Sent Events |
| 6325 | - startup and shutdown lifecycle hooks |
| 6326 | |
| 6327 | That matters because DBBASIC objects are not only pages or REST handlers. They |
| 6328 | can also be jobs, event handlers, admin actions, realtime screens, data feeds, |
| 6329 | and AI-edited live application pieces. |
| 6330 | |
| 6331 | The important loop is: |
| 6332 | |
| 6333 | ```mermaid |
| 6334 | flowchart LR |
| 6335 | A[""Object changes""] --> B[""Version saved""] |
| 6336 | B --> C[""Object event""] |
| 6337 | C --> D[""UI/client updates""] |
| 6338 | ``` |
| 6339 | |
| 6340 | HTTP can handle the command. WebSockets or SSE can carry the feedback. |
| 6341 | |
| 6342 | ## Phoenix And Erlang |
| 6343 | |
| 6344 | Phoenix and Erlang/BEAM show why realtime application systems can feel so much |
| 6345 | better than request/response-only web frameworks: |
| 6346 | |
| 6347 | - long-lived connections are normal |
| 6348 | - PubSub is a core idea |
| 6349 | - server-side events can update clients quickly |
| 6350 | - stateful processes can model active parts of the application |
| 6351 | - failures are isolated and supervised |
| 6352 | |
| 6353 | DBBASIC should learn from that direction. |
| 6354 | |
| 6355 | The DBBASIC version is not Erlang and does not get BEAM supervision for free. |
| 6356 | Python ASGI does not automatically give per-object process isolation, hot code |
| 6357 | replacement, distributed process registries, or Phoenix PubSub semantics. |
| 6358 | |
| 6359 | What DBBASIC can still use well is the product shape: |
| 6360 | |
| 6361 | ```mermaid |
| 6362 | flowchart TD |
| 6363 | A[""Object source""] |
| 6364 | B[""Object state""] |
| 6365 | C[""Object logs""] |
| 6366 | D[""Object versions""] |
| 6367 | E[""Realtime object events""] |
| 6368 | A --> E |
| 6369 | B --> E |
| 6370 | C --> E |
| 6371 | D --> E |
| 6372 | ``` |
| 6373 | |
| 6374 | That can support live admin screens, Scroll object inspectors, AI repair loops, |
| 6375 | dashboards, collaborative editing, queues, and business app interfaces without |
| 6376 | forcing everything through a Rails/Django-style request/deploy cycle. |
| 6377 | |
| 6378 | ## Public V1 Direction |
| 6379 | |
| 6380 | The public v1 server should stay single-node first and keep clustering separate |
| 6381 | until replication and conflict behavior are proven. |
| 6382 | |
| 6383 | The first public ASGI layer is now small and runnable. It includes: |
| 6384 | |
| 6385 | - `GET /health` |
| 6386 | - `GET /objects?format=json` |
| 6387 | - `GET /objects/{object_id}?source=true&format=json` |
| 6388 | - object execution |
| 6389 | - source update and rollback |
| 6390 | - state/log/version endpoints |
| 6391 | - metadata endpoints |
| 6392 | - temporary admin-token gate for object listing and introspection reads |
| 6393 | |
| 6394 | Role, object, and row-level permissions, resource limits, and |
| 6395 | backup/restore checks all shipped. The websocket event stream is now |
| 6396 | implemented too (see below). |
| 6397 | |
| 6398 | ## Realtime: implemented |
| 6399 | |
| 6400 | Realtime arrived as an event system, not a decorative feature, and it |
| 6401 | reuses the durable event log rather than inventing a parallel path: |
| 6402 | |
| 6403 | - **Durable log (source of truth).** Every record write already publishes |
| 6404 | `collection.record.created/updated/deleted` to `object_events`, which is |
| 6405 | persisted, capped, and pollable with a cursor. This is the reliable, |
| 6406 | cross-restart, cross-worker path. |
| 6407 | - **Live overlay (`/ws`).** An in-process pub/sub hub (`object_realtime`) |
| 6408 | pushes those same events to connected websockets the instant they |
| 6409 | happen. See the [HTTP API contract](/docs/http-api-contract#realtime-push-websocket) |
| 6410 | for the connect + subscribe protocol. |
| 6411 | |
| 6412 | Events are boring JSON signals — collection, record id, action — never the |
| 6413 | record body, so a push can never leak a field. Delivery obeys the |
| 6414 | permission engine: you can only subscribe to a collection you may read, and |
| 6415 | with enforcement on you only receive events for records your row filters |
| 6416 | would show you. The client refetches through the normal enforced API. |
| 6417 | |
| 6418 | **Single-process assumption.** The live hub lives in one process; with one |
| 6419 | uvicorn worker every write and every socket share the event loop, so |
| 6420 | push is immediate and consistent. Across multiple workers each has its own |
| 6421 | hub, and clients fall back to polling the durable log — which is why the |
| 6422 | durable log, not the socket, is the source of truth. Keep the public v1 |
| 6423 | single-worker (or add a shared broker before scaling workers) so live push |
| 6424 | stays whole; either way correctness never depends on the socket. |
| 6425 | |
| 6426 | An object-scoped room model (`/ws/objects/{object_id}` for source/state/log |
| 6427 | changes) is a natural next addition on the same hub, using the existing |
| 6428 | source/state/version change events. |
| 6429 | |
| 6430 | ## Design Rule |
| 6431 | |
| 6432 | Keep the ASGI layer thin. |
| 6433 | |
| 6434 | The server should route requests and streams to object operations. It should not |
| 6435 | become a second framework with its own competing object model. |
| 6436 | " |
| 6437 | shell-and-ai The Shell and AI — Talk to the Whole System AI 500 How the DBBASIC shell routes instant record commands, search, and AI chat through the same MCP tools and permission engine, plus voice and web-reading features. "The shell (`/shell`) is one input that reaches everything: instant |
| 6438 | record commands, global search, and an AI that operates the server |
| 6439 | through the same MCP tools any agent uses — with **your key, your |
| 6440 | model choice, and your permissions**. |
| 6441 | |
| 6442 | ```mermaid |
| 6443 | flowchart TD |
| 6444 | U[""You type""] --> D{""prefix?""} |
| 6445 | D -->|""$ . ^""| REC[""Create note / task / link<br/>(records API, your session)""] |
| 6446 | D -->|""~""| SRCH[""GET /api/search""] |
| 6447 | D -->|""/""| CMD[""Built-ins: /help /key /model /tools /voice""] |
| 6448 | D -->|""anything else""| CHAT[""POST /api/ai/chat""] |
| 6449 | CHAT --> PROV[""AI provider<br/>(your stored key)""] |
| 6450 | PROV -->|""tool calls""| MCP[""MCP tool subset<br/>dispatched with YOUR credentials""] |
| 6451 | MCP --> PERM[""Permission engine + audit""] |
| 6452 | PERM --> PROV |
| 6453 | PROV --> REPLY[""Reply + tool log + token usage + cost""] |
| 6454 | ``` |
| 6455 | |
| 6456 | ## Setup: Your Key, Your Model |
| 6457 | |
| 6458 | AI features use each user's own provider key — the server stores it |
| 6459 | write-only and calls providers on your behalf. Key material never |
| 6460 | appears in any response, record, or backup. Two providers are supported |
| 6461 | today (`object_ai.SUPPORTED_SERVICES`): `anthropic` and `openai` — no |
| 6462 | Gemini, no local/on-device inference. An `openai` key, once stored, also |
| 6463 | covers the cloud voice paths below (`POST /api/tts` with `engine: ""openai""`, |
| 6464 | `POST /api/stt`) — one key, no separate signup for voice. |
| 6465 | |
| 6466 | In the shell: |
| 6467 | |
| 6468 | ``` |
| 6469 | /key anthropic sk-ant-... store a key (masked, never logged) |
| 6470 | /keys which services have keys |
| 6471 | /model anthropic:claude-haiku-5-5 pick a model (service:model) |
| 6472 | /model openai:gpt-5-mini or the other provider |
| 6473 | ``` |
| 6474 | |
| 6475 | Or over HTTP: `PUT /identity/users/{you}/service-keys` with your |
| 6476 | session (see the [HTTP API contract](/docs/http-api-contract)). |
| 6477 | |
| 6478 | ## Tool Subsets: Small Context, Configurable Power |
| 6479 | |
| 6480 | The AI is offered a **named subset** of the MCP tool catalog, not the |
| 6481 | whole thing. Small subsets keep the context small enough for fast, |
| 6482 | inexpensive models — and the subset is your safety dial: |
| 6483 | |
| 6484 | ``` |
| 6485 | /tools global_search,list_records,get_record,create_record conversation mode |
| 6486 | /tools global_search,list_objects,get_object_source,create_object,update_object_source,execute_object builder mode |
| 6487 | ``` |
| 6488 | |
| 6489 | Every tool call the model makes is dispatched through the server's own |
| 6490 | routing **with your credentials**: the AI can do exactly what you could |
| 6491 | do yourself — row filters, field redaction, and the audit trail apply. |
| 6492 | An AI acting for a user is never more powerful than the user. |
| 6493 | |
| 6494 | ### Output Budget and Effort Per Mode |
| 6495 | |
| 6496 | A subset that includes `create_object` or `update_object_source` is |
| 6497 | **builder mode**; anything else is **conversation mode**. The mode picks |
| 6498 | two defaults: |
| 6499 | |
| 6500 | | | Conversation | Builder | |
| 6501 | |---|---|---| |
| 6502 | | `max_tokens` | 4096 | 8192 (16384 when streaming) | |
| 6503 | | effort | `low` (`DBBASIC_AI_EFFORT`) | `high` (`DBBASIC_AI_BUILDER_EFFORT`) | |
| 6504 | |
| 6505 | A request may ask for its own `max_tokens` (capped at 8192, or 16384 when |
| 6506 | streaming, since a streamed answer starts arriving at once instead of |
| 6507 | holding one response open) and its own `effort` (`low`, `medium`, `high`, |
| 6508 | `xhigh`, `max`). `DBBASIC_AI_MAX_TOKENS_CAP` sets an operator cap that |
| 6509 | bounds both paths. Output tokens include the model's thinking, so the old |
| 6510 | default of 1024 left little room for an answer, and none for a builder |
| 6511 | answer that writes a whole object. |
| 6512 | |
| 6513 | Effort is sent as `output_config: {""effort"": ...}` only to models that |
| 6514 | accept it: current Claude ids from 4.6 on (`claude-haiku-5-5`, |
| 6515 | `claude-sonnet-5`, `claude-opus-4-8`, ...). `claude-haiku-4-5`, any id the |
| 6516 | server cannot read as a current Claude id (including dated snapshot ids), |
| 6517 | and OpenAI models get no effort field; they use their own default. The |
| 6518 | server never sends `temperature`, `top_p`, `top_k` or a thinking budget: |
| 6519 | Claude Haiku 5.5 thinks adaptively by default and refuses those. |
| 6520 | |
| 6521 | ### Strict Tool Schemas |
| 6522 | |
| 6523 | On the same models (Claude 4.6+), every offered tool whose input schema |
| 6524 | can be *closed* is sent with `""strict"": true`, so the provider guarantees |
| 6525 | the call's input matches the schema. Closing means every object lists its |
| 6526 | properties, sets `additionalProperties: false` and has a `required` list; |
| 6527 | the server makes that copy (the MCP catalog is not changed), moving any |
| 6528 | `default` into the description because the server's tool routing applies |
| 6529 | defaults itself. |
| 6530 | |
| 6531 | Five tools take a free-form object and so stay non-strict: `create_record` |
| 6532 | (`record`), `update_record` (`changes`), `list_records` (`where`), |
| 6533 | `execute_object` (`payload`) and `update_schema` (`schema`). Closing those |
| 6534 | would refuse the very fields the tools exist to carry. Every other tool in |
| 6535 | the catalog -- including `create_object`, `update_object_source`, |
| 6536 | `global_search`, `get_record` and `read_page` -- can be strict. OpenAI tool |
| 6537 | definitions are unchanged. |
| 6538 | |
| 6539 | The provider accepts at most 20 strict tools in one request (a live call |
| 6540 | with 25 was refused with HTTP 400). A tool subset with more closable tools |
| 6541 | than that keeps `strict` on the ones that change something (`create_*`, |
| 6542 | `update_*`, `delete_*`, `rollback_*`, `setup_*`, `start_*`, `stop_*`) first, |
| 6543 | then the others in the order offered; the rest are sent unmarked. The |
| 6544 | shell's usual subsets are far below the limit. |
| 6545 | |
| 6546 | ## Conversation Memory |
| 6547 | |
| 6548 | The shell logs every exchange to the `shell_commands` collection (your |
| 6549 | history is just records — searchable and owner-scoped). A new browser |
| 6550 | session replays recent history and sends prior AI turns back with each |
| 6551 | message, so conversations resume. The server stays stateless about |
| 6552 | chats: `POST /api/ai/chat` accepts a `history` list, and what to |
| 6553 | remember is the client's choice. |
| 6554 | |
| 6555 | ## Streaming |
| 6556 | |
| 6557 | `POST /api/ai/chat` with `""stream"": true` answers in server-sent events, |
| 6558 | so the shell and Talk show the reply as it is written instead of after |
| 6559 | the whole turn. It is the same turn, not a second implementation: |
| 6560 | |
| 6561 | 1. Every refusal that can happen before the provider is called (flag, |
| 6562 | session, origin, body, model, tool names, attachments, missing key) |
| 6563 | runs first and stays a plain JSON error with its real status. |
| 6564 | 2. The turn runs in a worker thread through the same `object_ai.run_chat` |
| 6565 | loop. Anthropic is asked for `stream: true`; its events are parsed as |
| 6566 | they arrive and each text delta is forwarded to the browser as a |
| 6567 | `text` event. |
| 6568 | 3. When a round asks for tools, each tool's input is assembled from its |
| 6569 | streamed fragments and parsed only once its block has stopped. Input |
| 6570 | that does not parse into a JSON object is never dispatched: the model |
| 6571 | gets an error result (`is_error`) and may retry. Valid calls dispatch |
| 6572 | through the server's own routing with the caller's credentials, exactly |
| 6573 | as on the JSON path, and each is reported as a `tool_call` event. Then |
| 6574 | the next round streams. |
| 6575 | 4. When the turn ends, it is priced and recorded by the same code as a JSON |
| 6576 | turn, and the final `done` event carries the same object the JSON |
| 6577 | endpoint returns. A failure mid-turn ends with an `error` event instead |
| 6578 | (and, as on the JSON path, records nothing). |
| 6579 | |
| 6580 | Text events are a preview; `done.reply` is the answer (a refusal can |
| 6581 | arrive after some words streamed). A browser that disconnects mid-turn |
| 6582 | does not stop the turn: the provider is being paid either way, so it |
| 6583 | finishes, runs its tools and is recorded; only the writes to the closed |
| 6584 | connection are dropped. OpenAI turns are not streamed from OpenAI: each |
| 6585 | round's text arrives as one `text` event when the round finishes. |
| 6586 | |
| 6587 | The shell and Talk pages ask for a stream: the shell fills the pending |
| 6588 | line and Talk fills the caption as the words arrive, then both render the |
| 6589 | final `done` reply exactly as before (Talk speaks only that final reply, |
| 6590 | never a partial one). A response that is not `text/event-stream` -- a |
| 6591 | refusal made before the provider call, or a proxy that answers JSON -- is |
| 6592 | read as the JSON reply it always was. |
| 6593 | |
| 6594 | ## When a Turn Stops Early |
| 6595 | |
| 6596 | The server reads each response's `stop_reason` before its content, and |
| 6597 | the chat response carries it (`stop_reason`) so a surface can tell the |
| 6598 | cases apart: |
| 6599 | |
| 6600 | - **`refusal`**: the model declined. Whatever content came with it is |
| 6601 | not an answer and is not shown; `reply` says the model declined and |
| 6602 | names the provider's category and explanation, which also come back as |
| 6603 | `refusal: {category, explanation}`. No tool from that response runs. |
| 6604 | - **`max_tokens`**: the answer hit the output limit. `reply` is the |
| 6605 | partial text followed by a note that it was cut off, and `cut_off` is |
| 6606 | `true`. A tool call in the same response is **not** run: its input may |
| 6607 | stop mid-argument. (OpenAI's `length` is treated the same way.) |
| 6608 | - **`pause_turn`**: the provider paused a long turn. The paused content |
| 6609 | is sent back unchanged and the turn resumes, counting as a round. If |
| 6610 | the round limit comes first, `reply` says so and `truncated` is `true`. |
| 6611 | |
| 6612 | A refused or cut-off turn still spent tokens, so its usage and cost are |
| 6613 | recorded like any other. |
| 6614 | |
| 6615 | ## Prompt Caching |
| 6616 | |
| 6617 | Anthropic requests mark their stable prefix for prompt caching. A request |
| 6618 | renders as tools, then system, then messages, and a cached entry is a |
| 6619 | prefix of that, so the breakpoints (`cache_control: {""type"": |
| 6620 | ""ephemeral""}`) go on the parts that are identical turn after turn: the |
| 6621 | last tool definition and the `system` text. Text that changes every turn |
| 6622 | -- the local time, the last web page read -- goes in the request's |
| 6623 | `context` field instead, which is sent as a second system block *after* |
| 6624 | the cached one. A timestamp inside `system` would make every request's |
| 6625 | prefix unique: each turn would pay to write a cache entry nobody reads. |
| 6626 | |
| 6627 | The simpler top-level `cache_control` (cache up to the last block) is not |
| 6628 | used on purpose: a turn's last block is the new user message, and the next |
| 6629 | turn's history carries that message without its context, so what one turn |
| 6630 | wrote is not what the next turn sends. |
| 6631 | |
| 6632 | A prefix shorter than the model's minimum cacheable length is not cached |
| 6633 | (no error; the cache token counts are 0). OpenAI requests are unchanged: |
| 6634 | `system` and `context` are joined into its one system message, and OpenAI |
| 6635 | caches on its own. |
| 6636 | |
| 6637 | ## Cost Recording |
| 6638 | |
| 6639 | Every chat turn is priced server-side, not by the caller. `POST |
| 6640 | /api/ai/chat` reads token counts straight from the provider's own response, |
| 6641 | looks up the model's price in the `ai_prices` collection (editable records, |
| 6642 | never a hardcoded table -- so a price change is a data edit, not a |
| 6643 | deploy), and computes the cost in integer cents: `tokens * |
| 6644 | per_million_cents // 1_000_000`, input and output added separately, no |
| 6645 | float division on money. The result -- `tokens_in`, `tokens_out`, |
| 6646 | `tokens_cache_read`, `tokens_cache_write`, `cost_cents`, `model`, |
| 6647 | `provider` -- lands in the `ai_usage` collection, written by the chat |
| 6648 | handler itself with the caller's user id as actor, so the record can't be |
| 6649 | skipped or forged the way a client-written log could be. The same numbers |
| 6650 | come back in the chat response's `usage` object (`input_tokens`, |
| 6651 | `output_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`, |
| 6652 | `largest_prompt_tokens`, `cost_cents`) so a surface can show them |
| 6653 | immediately. |
| 6654 | |
| 6655 | Cached prompt tokens (see Prompt Caching above) are reported by Anthropic |
| 6656 | *beside* `input_tokens`, not inside it, and are billed at their own rates: |
| 6657 | `ai_prices` has `cache_read_per_million_cents` and |
| 6658 | `cache_write_per_million_cents` for them. A blank cache rate means |
| 6659 | *unknown*, not free. |
| 6660 | |
| 6661 | The cost is null -- tokens still recorded -- when the turn cannot be priced |
| 6662 | honestly: |
| 6663 | |
| 6664 | - no `ai_prices` row matches the model; |
| 6665 | - the turn read or wrote prompt cache and the matching cache rate is blank; |
| 6666 | - the row sets `price_max_prompt_tokens` and one request's whole prompt |
| 6667 | (uncached + cache read + cache write) went over it. |
| 6668 | |
| 6669 | The last rule exists for models whose rate rises above a prompt size. |
| 6670 | Claude Haiku 5.5 costs $0.10 in / $0.50 out per million tokens for |
| 6671 | prompts up to 100K tokens and $0.50 / $2.50 beyond. A price row holds one |
| 6672 | rate, so the seeded Haiku 5.5 row covers prompts up to 100,000 tokens and a |
| 6673 | turn with a bigger request is left unpriced rather than recorded at a fifth |
| 6674 | of its real cost. Pricing the higher tier would need a second rate on the |
| 6675 | row and per-request (not per-turn) cost math; it is not implemented. |
| 6676 | |
| 6677 | Seeded rates (cents per million tokens): |
| 6678 | |
| 6679 | | Model | In | Out | Cache read | Cache write | Priced up to | |
| 6680 | |---|---|---|---|---|---| |
| 6681 | | `claude-haiku-5-5` | 10 | 50 | 1* | 13* | 100,000 | |
| 6682 | | `claude-sonnet-5-5` | 200 | 1000 | 10 | 250* | | |
| 6683 | | `claude-opus-5-5` | 400 | 2000 | 20 | 500* | | |
| 6684 | |
| 6685 | The cache-read rates for Sonnet 5.5 and Opus 5.5 are published prices. |
| 6686 | The starred rates are derived, not published: Anthropic prices cache |
| 6687 | reads at 0.05x the input rate and 5-minute cache writes at 1.25x, so |
| 6688 | Haiku 5.5 reads come to 0.5 cents per million and writes to 12.5, and the |
| 6689 | seed rounds every derived rate UP to a whole cent (1 and 13). The recorded |
| 6690 | cost is informational -- these turns run on the user's own key -- and must |
| 6691 | never under-report, so a slightly high number beats a missing one. An |
| 6692 | operator who has the exact published rate edits the row; the most recent |
| 6693 | `effective_date` wins. |
| 6694 | |
| 6695 | The older rows (`claude-haiku-4-5`, `claude-sonnet-5`, `claude-opus-4-8`, |
| 6696 | `gpt-5-mini`, `gpt-5`) stay, with blank cache rates: for them a turn that |
| 6697 | touches the cache is recorded with a null cost. Upgrading |
| 6698 | `app-settings` on an existing server merges the new rows by id and leaves |
| 6699 | rows already there untouched. |
| 6700 | |
| 6701 | ## Coding Without Coding |
| 6702 | |
| 6703 | With builder-mode tools, the AI can create and edit live objects: |
| 6704 | |
| 6705 | > make an object called site_dice that renders a page rolling two dice |
| 6706 | |
| 6707 | The model writes the source, calls `create_object`, and the page is |
| 6708 | live at `/dice` immediately — objects load per execution, so there is |
| 6709 | no deploy step between the AI writing code and the code serving |
| 6710 | traffic. Edits use `update_object_source`; every version lands in |
| 6711 | source history with rollback; and create/update responses report the |
| 6712 | methods the code actually exposes, so the model can self-correct. |
| 6713 | |
| 6714 | Object writes ride the admin gate (an admin-role session today), and |
| 6715 | source writes require `DBBASIC_ENABLE_SOURCE_WRITES=true` — the same |
| 6716 | boundaries that govern humans. |
| 6717 | |
| 6718 | ## Voice |
| 6719 | |
| 6720 | The shell doubles as a push-to-talk terminal. Speech in and speech out each |
| 6721 | have two paths: browser-native (free, on-device, always available if the |
| 6722 | browser supports it) and cloud (a real per-user OpenAI key, real cost, but |
| 6723 | ""not on device"" — works on browsers/hardware the native APIs don't cover, |
| 6724 | and sounds noticeably better than the local synthesis engines). |
| 6725 | |
| 6726 | - **Speech in, browser path**: the mic button uses `window.SpeechRecognition` |
| 6727 | (or the `webkit` prefix); interim words show live in the input, and the |
| 6728 | final transcript submits through the same form-submit path a typed line |
| 6729 | does — no separate send code. Neither Chrome nor Safari expose the API |
| 6730 | outside a secure context (`https://` or `localhost`), and without it the |
| 6731 | button simply stays hidden. This is the default (`talk_stt_engine: ""browser""`). |
| 6732 | - **Speech in, cloud path**: when `talk_stt_engine` is `""openai""`, the mic |
| 6733 | becomes push-to-talk instead of continuous listening — tap to start a |
| 6734 | real `MediaRecorder` capture, tap again to stop and upload the clip to |
| 6735 | `POST /api/stt`, which transcribes it via the caller's own stored OpenAI |
| 6736 | key and returns text. No wake word, no VAD silence endpoint: raw audio has |
| 6737 | no equivalent to `SpeechRecognition`'s live partial-result signal, so |
| 6738 | there is no live signal to drive one. See `POST /api/stt` below. |
| 6739 | - **Speech out, browser path**: `speechSynthesis.speak` — free, on-device, |
| 6740 | no server round-trip. |
| 6741 | - **Speech out, cloud path**: when `talk_tts_engine` is `""openai""`, assistant |
| 6742 | replies (markdown and code fences stripped first — only prose is spoken, |
| 6743 | never tool-call noise) POST to `POST /api/tts` with `""engine"": ""openai""` |
| 6744 | and play the returned `audio/mpeg`, via the caller's own stored OpenAI key. |
| 6745 | If the request fails for any reason, the browser's own `speechSynthesis` |
| 6746 | says the line instead, so voice mode never goes silent because of a |
| 6747 | server-side gap. |
| 6748 | |
| 6749 | `/voice`, `/voice on`, `/voice off` toggle voice mode inline (mirrors |
| 6750 | `/model`); the setting persists on `shell_preferences.voice_enabled` and is |
| 6751 | honored on page load like `ai_model` and `tools`. `talk_tts_engine` and |
| 6752 | `talk_stt_engine` (both default to the free/local path) live on the same |
| 6753 | `shell_preferences` record — the Talk page (`/talk`) additionally has a |
| 6754 | single in-page toggle that flips both together, since ""cloud voice"" is one |
| 6755 | combined mode to remember, not two settings. |
| 6756 | |
| 6757 | ### `POST /api/tts` |
| 6758 | |
| 6759 | ```http |
| 6760 | POST /api/tts |
| 6761 | Authorization: Bearer <session-token> (or the session cookie) |
| 6762 | |
| 6763 | {""text"": ""one note matches"", ""voice"": ""en-us"", ""engine"": ""local""} |
| 6764 | ``` |
| 6765 | |
| 6766 | Response: audio bytes (`audio/wav` for `engine: ""local""`, `audio/mpeg` for |
| 6767 | `engine: ""openai""`), or the usual `{""status"": ""error"", ""error""}` JSON shape |
| 6768 | on failure. Requires `DBBASIC_ENABLE_TTS=true` (off by default) and a |
| 6769 | signed-in session — same posture as `/api/ai/chat`. `text` is capped at 800 |
| 6770 | characters (413 beyond that). `engine` is optional, `""local""` or `""openai""`, |
| 6771 | defaulting to `""local""` — the two paths never silently fall back to each |
| 6772 | other; a caller who asked for cloud quality and hits a provider error sees |
| 6773 | that error. |
| 6774 | |
| 6775 | **`engine: ""local""`** (default): discovered at call time, first match wins: |
| 6776 | `espeak-ng`, `espeak`, then macOS `say` (development convenience — `say` |
| 6777 | writes AIFF and the also-stock `afconvert` turns it into WAV; if `afconvert` |
| 6778 | isn't present the endpoint returns 501 rather than growing a bespoke audio |
| 6779 | pipeline). No engine on `PATH` at all is a 503 with a clear message. |
| 6780 | |
| 6781 | **`engine: ""openai""`**: calls OpenAI's TTS API (`gpt-4o-mini-tts` by |
| 6782 | default) using the caller's own key, stored via `PUT |
| 6783 | /identity/users/{user_id}/service-keys` (`service: ""openai""`) — no key |
| 6784 | stored is a 400 with the exact PUT to fix it. A provider-side failure (bad |
| 6785 | key, rate limit) is a 502. `DBBASIC_TTS_CLOUD_TIMEOUT_SECONDS` bounds the |
| 6786 | outbound call (default 30s). |
| 6787 | |
| 6788 | Successful audio is cached at |
| 6789 | `data/tts-cache/{sha256(engine|voice|text[|model])}.wav` regardless of |
| 6790 | engine — a repeat of the same line is a cache read, not a re-synthesis. |
| 6791 | There's no eviction in v1; operators who want a bound should prune that |
| 6792 | directory on their own schedule. |
| 6793 | |
| 6794 | ### `POST /api/stt` |
| 6795 | |
| 6796 | ```http |
| 6797 | POST /api/stt |
| 6798 | Authorization: Bearer <session-token> (or the session cookie) |
| 6799 | Content-Type: audio/webm |
| 6800 | |
| 6801 | <raw audio bytes> |
| 6802 | ``` |
| 6803 | |
| 6804 | Response: `{""status"": ""ok"", ""text"": ""...""}`, or the usual |
| 6805 | `{""status"": ""error"", ""error""}` shape. The request body is the raw audio |
| 6806 | bytes themselves (whatever `MediaRecorder` produced client-side — typically |
| 6807 | `audio/webm` on Chrome/Firefox, `audio/mp4`-ish on Safari), not JSON; the |
| 6808 | `Content-Type` header says what format it is. Requires |
| 6809 | `DBBASIC_ENABLE_STT=true` (off by default, unlike TTS which many operators |
| 6810 | turn on immediately — STT costs money on every utterance, not just the |
| 6811 | occasional reply) and a signed-in session. Capped at 10MB per clip (413 |
| 6812 | beyond that). |
| 6813 | |
| 6814 | Unlike TTS, there is **no local-engine path here at all** — every call goes |
| 6815 | to OpenAI's transcription API (`gpt-4o-mini-transcribe` by default), using |
| 6816 | the caller's own stored key exactly like the TTS cloud path. No key stored |
| 6817 | is a 400; a provider-side failure is a 502. |
| 6818 | `DBBASIC_STT_TIMEOUT_SECONDS` bounds the outbound call (default 30s). |
| 6819 | Nothing is persisted server-side beyond the ordinary `ai_usage`/cost |
| 6820 | accounting every provider call gets — the audio itself is uploaded, |
| 6821 | transcribed, and discarded within the request. |
| 6822 | |
| 6823 | ## Reading the Web |
| 6824 | |
| 6825 | The AI can fetch and read a real web page — the lynx/w3m move for an AI + |
| 6826 | voice consumer: strip a URL down to `{title, text, links}`, links numbered |
| 6827 | in document order so they double as speakable navigation targets (""open |
| 6828 | link three""). It is a real, tested loop: read a page, get a short spoken |
| 6829 | summary with numbered links, say ""open link one,"" and it resolves against |
| 6830 | the previous turn's link list, fetches that page, and summarizes it too — |
| 6831 | follow a chain of pages by voice alone. |
| 6832 | |
| 6833 | The `read_page` tool is offered like any other MCP tool (add it to a |
| 6834 | `/tools` subset to use it) and calls `object_reader.py` server-side, gated |
| 6835 | behind `DBBASIC_ENABLE_READER` (off by default). Fetching is SSRF-hardened: |
| 6836 | every hostname — the original and every redirect hop — is resolved and |
| 6837 | checked before the socket opens, refusing loopback/link-local/private |
| 6838 | ranges and failing closed on any resolution ambiguity; `http`/`https` only, |
| 6839 | a small redirect cap, and hard timeout/size limits. HTML is stripped with |
| 6840 | `html.parser` (no regex scraping), never a headless browser — JS-rendered |
| 6841 | pages, images, and login-walled pages are out of scope by design. |
| 6842 | |
| 6843 | A fetched page can also be shown on screen as a `{""kind"": ""reader"", ""url"": |
| 6844 | ...}` view block (title + body text + the numbered link list), fetched |
| 6845 | client-side through `POST /api/read` — the same flag and SSRF posture |
| 6846 | apply. |
| 6847 | |
| 6848 | ## The Instant Commands |
| 6849 | |
| 6850 | | Input | Effect | |
| 6851 | |---|---| |
| 6852 | | `$ pay the hosting bill` | quick note | |
| 6853 | | `. fix the header` | quick task | |
| 6854 | | `^https://example.com docs` | save a link | |
| 6855 | | `~flywheel` | global search across collections | |
| 6856 | | `/help` | list commands | |
| 6857 | |
| 6858 | These never touch the AI — they are one permission-checked record |
| 6859 | write each, which is why they feel instant. |
| 6860 | |
| 6861 | ## For Agents |
| 6862 | |
| 6863 | Everything above is equally available to AI agents connecting over MCP |
| 6864 | (`POST /api/mcp`) with their own identities and labeled sessions, and |
| 6865 | to headless callers hitting `POST /api/ai/chat` directly. One surface, |
| 6866 | many kinds of operator. |
| 6867 | " |
| 6868 | permissions-model Permissions Model Security & Limits 600 A reference guide to DBBASIC's server-side permissions primitive: access modes, rules, row/field filters, sharing, subscriptions, and route enforcement. "DBBASIC permissions are a server-side primitive. Scroll can edit, preview, and |
| 6869 | explain rules, but the object server must make the final allow/deny decision. |
| 6870 | |
| 6871 | Many web frameworks treat permissions as something each app has to rediscover: |
| 6872 | blog visibility, admin-only pages, intranet roles, or social-app follows. Those |
| 6873 | cases matter, but they are not enough for a general business platform. |
| 6874 | |
| 6875 | DBBASIC needs object-level permissions that can model SaaS, customer portals, |
| 6876 | employee roles, contractors, paid content, shared workspaces, internal admin |
| 6877 | tools, and AI-generated app surfaces with the same small set of primitives. |
| 6878 | Getting this right means most apps need less custom permission code. |
| 6879 | |
| 6880 | The model needs to cover the common app cases without forcing every object into |
| 6881 | one framework shape: |
| 6882 | |
| 6883 | - public visitors |
| 6884 | - signed-in users |
| 6885 | - paid subscribers |
| 6886 | - temporary paid access |
| 6887 | - admins and employees |
| 6888 | - customer accounts with their own employees |
| 6889 | - object owners |
| 6890 | - users or accounts an owner shared with |
| 6891 | - per-row and per-field restrictions |
| 6892 | |
| 6893 | Permissions decide who may *call* an object. What the object's code may then |
| 6894 | *do* is a separate boundary: user-namespace objects (`u_<uid>_*`) run in a |
| 6895 | Landlock-sandboxed worker, as a separate OS user that owns nothing, that |
| 6896 | cannot read secrets, files, other users' data or the network, nor change or |
| 6897 | inspect other users' files, and reaches its own state, logs and files only through |
| 6898 | proxies the server checks. See |
| 6899 | runtime-contract.md ""User Object Isolation"". |
| 6900 | A system object that user code calls runs with the identity of the original |
| 6901 | request, never one the user code supplied. |
| 6902 | |
| 6903 | ## Decision Shape |
| 6904 | |
| 6905 | The core API is: |
| 6906 | |
| 6907 | ```python |
| 6908 | check_permission(subject, action, policy, collection=None, object_id=None, record=None) |
| 6909 | ``` |
| 6910 | |
| 6911 | It returns: |
| 6912 | |
| 6913 | ```python |
| 6914 | PermissionDecision( |
| 6915 | allowed=True/False, |
| 6916 | reason=""..."", |
| 6917 | code=""allowed|authentication_required|payment_required|forbidden"", |
| 6918 | http_status=200|401|402|403, |
| 6919 | row_filter={...}, |
| 6920 | ) |
| 6921 | ``` |
| 6922 | |
| 6923 | When a list/query request has a row filter but no specific record, the decision |
| 6924 | can return `allowed=True` with the row filter attached. The caller then applies |
| 6925 | that filter before returning rows. |
| 6926 | |
| 6927 | ```mermaid |
| 6928 | flowchart TD |
| 6929 | A[""request""] --> B[""identify subject""] |
| 6930 | B --> C[""load policy""] |
| 6931 | C --> D{""admin role?""} |
| 6932 | D -- yes --> Z[""allow""] |
| 6933 | D -- no --> E{""explicit deny matches?""} |
| 6934 | E -- yes --> Y[""deny with reason""] |
| 6935 | E -- no --> F{""access mode allows?""} |
| 6936 | F -- yes --> Z |
| 6937 | F -- no --> G{""allow rule matches?""} |
| 6938 | G -- yes --> H[""allow with optional row/field filters""] |
| 6939 | G -- no --> I{""owner fallback?""} |
| 6940 | I -- yes --> J{""switched off by an owner_fallback rule?""} |
| 6941 | J -- no --> Z |
| 6942 | J -- yes --> Y |
| 6943 | I -- no --> Y |
| 6944 | ``` |
| 6945 | |
| 6946 | ## Persistence And API |
| 6947 | |
| 6948 | The current public server stores the active policy as: |
| 6949 | |
| 6950 | ```text |
| 6951 | data/permissions/policy.json |
| 6952 | ``` |
| 6953 | |
| 6954 | If the file does not exist, the server uses a conservative default: |
| 6955 | |
| 6956 | ```json |
| 6957 | { |
| 6958 | ""access_mode"": ""role_based"", |
| 6959 | ""roles"": {}, |
| 6960 | ""user_roles"": {}, |
| 6961 | ""rules"": [], |
| 6962 | ""admin_roles"": [""admin"", ""superuser""] |
| 6963 | } |
| 6964 | ``` |
| 6965 | |
| 6966 | That default has no allow grants. With enforcement on it is enforced as |
| 6967 | deny-all: every non-admin request is refused, the admin token still works, |
| 6968 | and `/permissions/status` warns until a real policy is written (by you, or by |
| 6969 | installing packages). `object_permission_store.starter_policy_payload()` |
| 6970 | returns the documented starter policy for a fresh deployment: anonymous |
| 6971 | visitors can execute the public pages (`site_home`, `system_dashboard`, |
| 6972 | `system_write_probe`) and read the `dbbasic_probe` demo records; signed-in |
| 6973 | users can write probe records; admin-role subjects bypass rules. It grants a |
| 6974 | signed-in user nothing else: what they can read and run is what the |
| 6975 | installed packages' rules (and your own, written per collection or object) |
| 6976 | give them. Install it with the policy endpoint: |
| 6977 | |
| 6978 | ```bash |
| 6979 | python3 -c ""import json, object_permission_store as s; print(json.dumps({'policy': s.starter_policy_payload()}))"" \ |
| 6980 | | curl -s -X PUT https://your-host/permissions/policy \ |
| 6981 | -H ""Authorization: Token <admin-token>"" \ |
| 6982 | -H ""Content-Type: application/json"" --data-binary @- |
| 6983 | ``` |
| 6984 | |
| 6985 | Then edit grants per app instead of widening the starter rules in place. Run |
| 6986 | audit mode before enforcement to see what live traffic would be denied. |
| 6987 | |
| 6988 | ### A wide rule left over from an older starter policy |
| 6989 | |
| 6990 | Until 2026-11-29 the starter policy also carried |
| 6991 | |
| 6992 | ```json |
| 6993 | {""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read"", ""execute""], |
| 6994 | ""reason"": ""signed-in users can read and run objects""} |
| 6995 | ``` |
| 6996 | |
| 6997 | with no collection and no object_id. A rule that names no resource matches |
| 6998 | every resource, and the engine returns the first allow rule that matches |
| 6999 | without comparing it with the others, so on a box that started from that |
| 7000 | policy every signed-in account could run every object (the billing runner, |
| 7001 | recurring journals, sweepers, every hook, generators a package restricts to a |
| 7002 | role) and read every collection, and the row filters packages ship on |
| 7003 | `wallets`, `notes` and the rest decided nothing. With open signup, |
| 7004 | ""signed-in"" means anyone with an email address. |
| 7005 | |
| 7006 | New boxes no longer get it. **An existing box still has it**, and nothing |
| 7007 | removes it for you: it carries no `package` tag, so a package upgrade's |
| 7008 | retraction never touches it, and the server will not delete an operator's rule |
| 7009 | on its own. It is made visible instead: |
| 7010 | |
| 7011 | - `GET /permissions/unshipped` lists it (state `operator`) with a `wide` line |
| 7012 | saying what it grants, and `wide_rules` lists every wide rule in the policy |
| 7013 | (an allow for `registered` or `public` with no `collection` and no |
| 7014 | `object_id`), whoever it is tagged for; |
| 7015 | - the startup log prints one `[dbbasic] WIDE permission rule #N ...` line per |
| 7016 | such rule when permission checks are on. |
| 7017 | |
| 7018 | To remove it: read the policy, drop the rule at the `index` the report gives, |
| 7019 | and write the policy back. Take the policy as it is, do not retype it. |
| 7020 | |
| 7021 | ```bash |
| 7022 | curl -s https://your-host/permissions/policy -H ""Authorization: Token $TOKEN"" \ |
| 7023 | | python3 -c ' |
| 7024 | import json, sys |
| 7025 | policy = json.load(sys.stdin)[""policy""] |
| 7026 | policy[""rules""] = [r for r in policy[""rules""] |
| 7027 | if not (r[""effect""] == ""allow"" and r[""principal""] in (""registered"", ""public"") |
| 7028 | and not r.get(""collection"") and not r.get(""object_id""))] |
| 7029 | print(json.dumps({""policy"": policy}))' \ |
| 7030 | | curl -s -X PUT https://your-host/permissions/policy \ |
| 7031 | -H ""Authorization: Token $TOKEN"" -H ""Content-Type: application/json"" --data-binary @- |
| 7032 | ``` |
| 7033 | |
| 7034 | Before you do, run audit mode (or read `GET /permissions/audit`) to see |
| 7035 | whether anything you rely on was only reachable through it. Packages ship the |
| 7036 | grants their own pages need; a page or action no package grants and your users |
| 7037 | must reach needs a rule of your own naming that object or collection. The |
| 7038 | changed policy takes effect without a restart. |
| 7039 | |
| 7040 | The policy endpoints are still admin-gated while broader login, account |
| 7041 | management, and permission editing mature: |
| 7042 | |
| 7043 | ```http |
| 7044 | GET /permissions/policy |
| 7045 | Authorization: Token <token> |
| 7046 | ``` |
| 7047 | |
| 7048 | ```http |
| 7049 | PUT /permissions/policy |
| 7050 | Authorization: Token <token> |
| 7051 | Content-Type: application/json |
| 7052 | ``` |
| 7053 | |
| 7054 | ```json |
| 7055 | { |
| 7056 | ""policy"": { |
| 7057 | ""access_mode"": ""role_based"", |
| 7058 | ""roles"": {""sales"": {""label"": ""Sales""}}, |
| 7059 | ""user_roles"": {""7"": [""sales""]}, |
| 7060 | ""rules"": [] |
| 7061 | } |
| 7062 | } |
| 7063 | ``` |
| 7064 | |
| 7065 | ### Saving a policy is checked; reading one is not |
| 7066 | |
| 7067 | A save (`PUT /permissions/policy`, or `object_permission_store.replace_policy` |
| 7068 | from a shell, which is how the starter policy is installed) is held to DRON |
| 7069 | (`dron/dron-policy.schema.json`, `docs/dron.md`), the same check a package's |
| 7070 | `rules.json` gets at install. Before anything is written it refuses: |
| 7071 | |
| 7072 | - a key it does not know, on the policy or on a rule, with the closest |
| 7073 | spelling (`unknown key 'rowfilter' (did you mean 'row_filter'?)`): the |
| 7074 | engine would drop it, and a dropped `row_filter` turns ""each user their own |
| 7075 | rows"" into ""every row""; |
| 7076 | - an effect, action, principal, row-filter operator or `$`-variable that is not |
| 7077 | one, a `valid_from`/`expires_at` that does not parse, and any value of the |
| 7078 | wrong type the engine would quietly coerce (a number for a collection or a |
| 7079 | role, a role listed twice, an `access_mode` left null). |
| 7080 | |
| 7081 | The answer is a `400` naming every mistake by rule index, package tag and key |
| 7082 | (`problems` in the body). Rules the stored policy already holds, as the engine |
| 7083 | reads them, are not judged again: a save is not refused over rules you did not |
| 7084 | just write, so `GET /permissions/policy` then `PUT` of the same document |
| 7085 | saves, including on a box that carries rules from an older release, with one |
| 7086 | exception below: a serious mistake in the stored file must be fixed in the |
| 7087 | save that would otherwise write it back. |
| 7088 | |
| 7089 | The stored file is different. A policy written by hand on disk, or left by an |
| 7090 | older release, is read exactly as before: **nothing is refused and no decision |
| 7091 | changes on upgrade** (unless you turn on the setting described under ""Not |
| 7092 | applying an allow that is wider than written"" below). Instead each mistake is |
| 7093 | reported, with what the engine is |
| 7094 | doing with it today and how to fix it: |
| 7095 | |
| 7096 | - an `/admin/status` alert (""Permission policy file has N mistake(s) that let |
| 7097 | it allow MORE than written: rule 3 (package app-notes) key 'rowfilter': the |
| 7098 | engine ignores this key, so this allow applies to every row ...""); |
| 7099 | - `policy.findings` in `GET /permissions/status`, one entry per mistake |
| 7100 | (`index`, `package`, `key`, `message`, `today`, `fix`, `serious`, and |
| 7101 | `applied` on a serious one about an allow rule), and a warning for each |
| 7102 | serious one; |
| 7103 | - `findings` in `GET /permissions/unshipped`; |
| 7104 | - a `[dbbasic] SERIOUS permission policy mistake, rule N key ...` startup |
| 7105 | line per mistake while permission checks are on; |
| 7106 | - `findings` in a restore's policy-difference preview, for the file the |
| 7107 | restore would put back. |
| 7108 | |
| 7109 | `serious` marks the mistakes that make the policy allow more than written: a |
| 7110 | key that would narrow an allow (`row_filter`, `collection`, `object_id`, |
| 7111 | `fields`, `denied_fields`, `valid_from`, `expires_at`) that is ignored or null, |
| 7112 | a deny that can never apply (a principal that matches nobody, an expiry that |
| 7113 | does not parse, a filter that matches no row), and an ignored `rules` or |
| 7114 | `admin_roles`. The text names rules by index and package tag and keys only: |
| 7115 | never a rule's `reason` or a user id. To fix one, edit the rule as the `fix` |
| 7116 | says and save the policy; the save checks your edit. |
| 7117 | |
| 7118 | A save cannot quietly make a serious mistake ""written"". Saving rewrites the |
| 7119 | file as the engine reads it, so a dropped `rowfilter` would come back as an |
| 7120 | explicit allow on every row and the report would vanish without anyone having |
| 7121 | decided it. So while the stored file has a serious finding, a save whose policy |
| 7122 | still holds the affected rule in that widened form (as `GET` returns it) is |
| 7123 | refused with a `400` naming the finding: rule index, package tag, key, what it |
| 7124 | does today and how to fix it (`problems` carries the findings, indexed as in |
| 7125 | the stored file). Fix the rule or remove it in the same save; any other edit |
| 7126 | waits until then. For an ignored `rulez` or `admin_role`, write the `rules` or |
| 7127 | `admin_roles` you meant. Smaller (non-serious) findings never block a save. |
| 7128 | |
| 7129 | A package install does not erase a serious finding either. Installing (or |
| 7130 | retiring a package's rules) rewrites the policy file, and it used to write |
| 7131 | every rule as the engine reads it, so a misspelt `rowfilter` came back as a |
| 7132 | plain allow on every row and the alert went away. A stored rule with a |
| 7133 | serious finding is now written back exactly as the file held it, mistake |
| 7134 | included. The engine reads it the same way, so no decision changes, and the |
| 7135 | finding stays reported until you fix the rule with your own save. |
| 7136 | |
| 7137 | The same holds for a misspelt top-level key with a serious finding (`rulez`, |
| 7138 | `admin_role`): an install writes the key back under the same name with the |
| 7139 | same value. The engine goes on ignoring it, so the rules under `rulez` still |
| 7140 | do not apply and the default admin roles still do; the finding and its alert |
| 7141 | stay until your own save writes the `rules` or `admin_roles` you meant. An |
| 7142 | unknown key whose finding is not serious is dropped by an install, as before. |
| 7143 | |
| 7144 | ### Not applying an allow that is wider than written |
| 7145 | |
| 7146 | `DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS` (default: off; `1`, `true`, `yes` |
| 7147 | or `on` turns it on) changes what the engine does with one kind of serious |
| 7148 | finding. While it is on, **every stored allow rule with a serious finding |
| 7149 | grants nothing**: decisions are made as if the rule were not in the policy. |
| 7150 | That is an allow whose narrowing key (`row_filter`, `collection`, `object_id`, |
| 7151 | `fields`, `denied_fields`, `valid_from`, `expires_at`) is misspelt and so |
| 7152 | ignored, or is null. The own-rows allow with a misspelt `row_filter` then |
| 7153 | shows its users none of the rows, their own included, instead of all of them: |
| 7154 | the engine does not guess what the key was meant to say. Rules written |
| 7155 | correctly in the same policy grant as before. |
| 7156 | |
| 7157 | The rule is not removed. It stays in the file and in `GET /permissions/policy`, |
| 7158 | a save still has to fix or remove it, and a package install that rewrites the |
| 7159 | policy writes the rule back as the file held it. Fix the key as the finding's |
| 7160 | `fix` says and save, and the rule grants what was written. |
| 7161 | |
| 7162 | The finding says which of the two applies, in `today`, in the `/admin/status` |
| 7163 | alert and in the `/permissions/status` warning, and a serious finding on an |
| 7164 | allow rule carries `applied`: |
| 7165 | |
| 7166 | - setting on: ""... ; this rule is not applied"", `""applied"": false`; |
| 7167 | - setting off: ""... ; this rule applies more widely than written; set |
| 7168 | DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS to stop applying it"", |
| 7169 | `""applied"": true`. |
| 7170 | |
| 7171 | With the setting off no decision changes. Rules a package installs carry no |
| 7172 | findings, so they are unaffected either way. If the findings cannot be worked |
| 7173 | out while the setting is on, the policy is treated as one that cannot be read: |
| 7174 | requests are refused the way they are for a policy file that does not parse, |
| 7175 | and `/admin/status` says so. |
| 7176 | |
| 7177 | **Deny rules are never touched by this setting.** A deny with a finding (one |
| 7178 | that can never apply, or one whose dropped key makes it apply more widely) is |
| 7179 | applied, or not, exactly as before, on and off. Whether a deny that never |
| 7180 | applies should also fail closed when read is still the owner's open decision |
| 7181 | (`docs/dron.md`). The serious findings that are not about a rule (an ignored |
| 7182 | `rules` or `admin_roles` key) are not changed either. The default is off in |
| 7183 | this release and may turn on in a later one; set the variable to `false` to |
| 7184 | keep today's behaviour whatever the default becomes. |
| 7185 | |
| 7186 | Identity subjects can come from trusted headers, the admin token, or DBBASIC |
| 7187 | session tokens. The session tokens are backed by a small local registry: |
| 7188 | |
| 7189 | ```text |
| 7190 | data/identity/accounts.tsv |
| 7191 | data/identity/users.tsv |
| 7192 | data/identity/sessions.tsv |
| 7193 | ``` |
| 7194 | |
| 7195 | Accounts carry tenant/subscription defaults. Users carry account membership, |
| 7196 | roles, and user-level subscriptions. A session minted for a registered user |
| 7197 | takes that account, role, and subscription data from the user's current rows on |
| 7198 | every request (see ""When a role change, disable or delete takes effect""), |
| 7199 | giving permission checks the same subject shape whether the request came from |
| 7200 | Scroll, a gateway, or a future DBBASIC login object. |
| 7201 | |
| 7202 | New DBBASIC-created accounts, users, sessions, shared links, record IDs, and |
| 7203 | change/audit IDs should use UUIDv4 values. Imported systems can keep their old |
| 7204 | integer or slug IDs as compatibility columns, but new routes and generated UI |
| 7205 | should not depend on sequential IDs. This keeps SaaS-style tenant data, |
| 7206 | temporary links, subscriptions, shared records, and future package exports from |
| 7207 | being tied to one database sequence. The identity registry still accepts string |
| 7208 | IDs so Django/PostgreSQL data and older Scroll prototypes can migrate without a |
| 7209 | flag day. |
| 7210 | |
| 7211 | Scroll and tests can preview decisions without persisting draft rules: |
| 7212 | |
| 7213 | ```http |
| 7214 | POST /permissions/check |
| 7215 | Authorization: Token <token> |
| 7216 | Content-Type: application/json |
| 7217 | ``` |
| 7218 | |
| 7219 | ```json |
| 7220 | { |
| 7221 | ""policy"": { |
| 7222 | ""access_mode"": ""role_based"", |
| 7223 | ""rules"": [ |
| 7224 | { |
| 7225 | ""effect"": ""allow"", |
| 7226 | ""principal"": ""role:sales"", |
| 7227 | ""actions"": [""read""], |
| 7228 | ""collection"": ""contacts"", |
| 7229 | ""row_filter"": {""owner_id"": ""$user_id""} |
| 7230 | } |
| 7231 | ] |
| 7232 | }, |
| 7233 | ""subject"": {""user_id"": ""7"", ""roles"": [""sales""]}, |
| 7234 | ""action"": ""read"", |
| 7235 | ""collection"": ""contacts"" |
| 7236 | } |
| 7237 | ``` |
| 7238 | |
| 7239 | If `policy` is omitted, `/permissions/check` uses the persisted policy file. |
| 7240 | The optional `now` field accepts an ISO timestamp for testing temporary access |
| 7241 | windows. |
| 7242 | |
| 7243 | A check that names an `object_id` is answered by the same function the |
| 7244 | object routes' gate uses, so the preview and the gate cannot disagree: the |
| 7245 | collection comes from the id, not from the request, and a user object is |
| 7246 | decided as [Access Modes](#access-modes) and [Sharing](#sharing) describe. |
| 7247 | |
| 7248 | ## Route Enforcement |
| 7249 | |
| 7250 | The public server can enforce the persisted policy against object routes and |
| 7251 | collection-record routes, but it is intentionally opt-in while auth and Scroll |
| 7252 | editing mature. |
| 7253 | |
| 7254 | ```text |
| 7255 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true |
| 7256 | ``` |
| 7257 | |
| 7258 | **Requested enforcement is always enforced.** With that flag set, every |
| 7259 | request is decided by the policy, from the first request to the last. There |
| 7260 | are three modes, and `permissions.mode` in `/permissions/status`, `/identity` |
| 7261 | and `/admin/status` names the one in force: |
| 7262 | |
| 7263 | | `mode` | Flags | What requests get | |
| 7264 | |---|---|---| |
| 7265 | | `off` | neither | objects open per route rules, collection data admin-gated, no audit | |
| 7266 | | `audit` | `DBBASIC_ENABLE_PERMISSION_AUDIT=true` alone | the same as `off`; every decision is logged with `enforced: false` | |
| 7267 | | `enforced` | `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true` | every decision applied (and audited) | |
| 7268 | |
| 7269 | Shadow (audit) mode exists only when you ask for it. It used to be a |
| 7270 | fallback as well: the readiness checks below ran on every request, and while |
| 7271 | any of them failed a requested enforcement was quietly switched off, so the |
| 7272 | request was decided, logged and **served anyway**, to anonymous callers too. |
| 7273 | A box that started fenced went open at runtime when its last session |
| 7274 | expired, its last user was disabled, its users file became unreadable or its |
| 7275 | policy file was corrupted. Nothing does that any more. |
| 7276 | |
| 7277 | **Readiness problems are reported, not acted on by opening.** Each one is |
| 7278 | handled by what the enforced request path does about it: |
| 7279 | |
| 7280 | | Problem | What non-admin requests get | Way back in | |
| 7281 | |---|---|---| |
| 7282 | | no admin token (`DBBASIC_ADMIN_TOKEN`) | the policy's decisions; nobody can use the admin APIs over HTTP | the server refuses to start without one (below) | |
| 7283 | | identity store unreadable (`data/identity/*.tsv`) | a request carrying a session or API key: `503` `identity_store_unavailable` with `Retry-After`; a request without one: what the policy grants anonymous callers | fix the file on the box; the admin token still works for diagnosis | |
| 7284 | | a user's account row missing or broken (their `account_id` has no row in `accounts.tsv`, there is no `accounts.tsv`, or the row does not parse), or their rows in `users.tsv` naming different accounts | that user's sessions and API keys: `403` `account_unusable`; their sign-in: `403` `account_unusable` after the right password; other users: unaffected | restore or fix the row (`GET /admin/ops?kind=auth&event=account_unusable` names the user, account and reason); or move the user out of the account; for `reason=conflicting`, remove the duplicate user row | |
| 7285 | | policy invalid or unreadable | `503` `permission_policy_unavailable`; the parse error is shown only to the admin token | `PUT /permissions/policy` with the admin token, or the shell | |
| 7286 | | `password` access mode (no verifier exists) | `401` unless an explicit allow rule matches | `PUT /permissions/policy` with another mode | |
| 7287 | | no non-admin sign-in path (the last session expired, the last user was disabled, none configured) | anonymous: what the policy grants anonymous callers, the rest `401`/`403` | the admin token: create users and mint sessions; `/setup` on a waiting one-click box; turn on a sign-in path and restart | |
| 7288 | |
| 7289 | Every request loads the policy, the admin token's included. When the load |
| 7290 | fails, an admin-token request is decided against the built-in default policy |
| 7291 | instead (whose admin roles let it through), so the owner still reads, runs |
| 7292 | and repairs while the policy file is broken; everyone else gets the `503`. |
| 7293 | What the console sees with the admin token on a broken policy: |
| 7294 | |
| 7295 | - `GET /admin/status` and `GET /permissions/status`: `200`, with a leading |
| 7296 | alert ""Permission policy file is invalid: <error>"" (or ""could not be read""), |
| 7297 | `permissions.policy.valid: false`, mode still `enforced`; counts that need |
| 7298 | the policy are `null` (`inventory.unavailable` lists them). |
| 7299 | - `GET /permissions/policy`: `200` with `{""policy"": null, ""error"": ""..."", |
| 7300 | ""raw"": ""<file text, first 64 KB>"", ""raw_truncated"": false}`; `raw` is |
| 7301 | omitted when the file cannot be read at all. A non-admin gets the `503` |
| 7302 | with no detail. Repair with `PUT /permissions/policy`. |
| 7303 | - Routes whose answer depends on the policy's rules (collection and schema |
| 7304 | listings, collection detail and change history, `GET /permissions/unshipped`, |
| 7305 | search) answer `503` `permission_policy_unavailable` with `error_detail`, so |
| 7306 | a collection never quietly becomes known or unknown. |
| 7307 | An admin-role user signed in with a session is not the admin token: which |
| 7308 | roles are admin is named in the policy, so they wait for the repair like |
| 7309 | everyone else, and with `DBBASIC_ENABLE_SESSION_ADMIN_GATES` their session |
| 7310 | does not pass the admin gates either until the policy can be read. WebDAV |
| 7311 | answers the same `503` rather than an empty folder, which a sync client |
| 7312 | would take as every file deleted. |
| 7313 | |
| 7314 | A single-record read (`GET /collections/{c}/records/{id}`, `GET /api/files/{id}`) |
| 7315 | is decided at the collection level before the record is looked up, and a row |
| 7316 | the caller may not read answers the same `404` as an id that does not exist, |
| 7317 | so the status tells nobody which ids exist. |
| 7318 | |
| 7319 | A person's files have two ways in, `/api/files` and the WebDAV folder |
| 7320 | `/dav/files/`, and under enforcement both ask the same questions in the |
| 7321 | same order: may this subject do the action on the `files` collection at all |
| 7322 | (no record, so no owner fallback), and only then may they do it to this |
| 7323 | file. Every WebDAV verb that reads the folder (`PROPFIND`, `PROPPATCH`, |
| 7324 | `GET`, `HEAD`, `PUT`, `DELETE`, `MOVE`, `COPY`) needs `read` on the |
| 7325 | collection first; then `DELETE` needs `delete`, a rename or a replacing |
| 7326 | `PUT` `update`, a new file `create`. A folder the caller may not read is a |
| 7327 | `403`, never an empty listing. Under a policy with no `files` rules the |
| 7328 | owner is refused on both, as on the record routes ([Ownership](#ownership)). |
| 7329 | |
| 7330 | At startup the server logs a `WARNING` naming each problem and the fix, and |
| 7331 | `GET /admin/status` leads with it in `alerts` (""Permission enforcement is ON, |
| 7332 | and ...""). After startup, at most once a minute per process, the server |
| 7333 | re-checks: a new problem is logged as an `ERROR`, a cleared one as `INFO`, |
| 7334 | and each change is an ops-log row (`GET /admin/ops?kind=permission_readiness`). |
| 7335 | |
| 7336 | **The one refusal: no admin token.** Enforcement without |
| 7337 | `DBBASIC_ADMIN_TOKEN` refuses to start (the ASGI lifespan reports startup |
| 7338 | failed, so uvicorn exits): the token is the way in for every other problem, |
| 7339 | and the only way to repair a broken policy over HTTP. For one release, |
| 7340 | `DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT=true` starts it anyway, |
| 7341 | **enforced**, with a startup line saying so; the repair for any problem is |
| 7342 | then the shell. It used to start the server unenforced, and no longer does; |
| 7343 | it goes away in a later release. To serve without enforcement on purpose, |
| 7344 | set `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false` and |
| 7345 | `DBBASIC_ENABLE_PERMISSION_AUDIT=true`. |
| 7346 | |
| 7347 | **Requiring enforcement.** A hosted, multi-user box should set |
| 7348 | `DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true`. The server then refuses to |
| 7349 | start unless the mode is `enforced` (`off` and `audit` both refuse), with |
| 7350 | one line: `Refusing to start: DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true and |
| 7351 | permission enforcement is off; set DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true.` |
| 7352 | It is opt-in and changes nothing unset. Like the admin-token refusal it is |
| 7353 | checked in the ASGI lifespan, so a server run with the lifespan turned off |
| 7354 | (`uvicorn --lifespan off`) skips it. |
| 7355 | |
| 7356 | `DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT` no longer does anything (it |
| 7357 | used to force enforcement despite the readiness checks, which is now what |
| 7358 | always happens); the server says so at startup. Remove it. |
| 7359 | |
| 7360 | A fresh box is enforced from its first request. The supported order for a |
| 7361 | fresh box with enforcement on: |
| 7362 | |
| 7363 | 1. set `DBBASIC_ADMIN_TOKEN` (the way in while nobody else can sign in); |
| 7364 | 2. turn on a sign-in path: `DBBASIC_ENABLE_PASSWORD_LOGIN=true`, trusted |
| 7365 | headers, guarded session login, or an identity source; |
| 7366 | 3. save a policy before the first start, e.g. |
| 7367 | `object_permission_store.replace_policy(object_permission_store.starter_policy_payload(), base_dir=DATA_DIR)` |
| 7368 | if you want the starter grants (a one-click box does not: its policy is the |
| 7369 | rules its starting apps ship). Skipping it is safe: the box |
| 7370 | starts deny-all and you save one later with `PUT /permissions/policy` or |
| 7371 | by installing packages, using the admin token; |
| 7372 | 4. start, and make the first admin through `/setup` (a one-click box, which |
| 7373 | answers only `/health` and `/setup` until then) or with the admin token. |
| 7374 | |
| 7375 | Without step 1 the server refuses to start. Without step 2 it starts |
| 7376 | enforced with a warning: only the admin token and public grants get in. |
| 7377 | |
| 7378 | Operators can see the state through: |
| 7379 | |
| 7380 | ```json |
| 7381 | { |
| 7382 | ""permissions"": { |
| 7383 | ""mode"": ""enforced"", |
| 7384 | ""enforcement_requested"": true, |
| 7385 | ""enforcement_enabled"": true, |
| 7386 | ""enforcement_blocked"": false |
| 7387 | } |
| 7388 | } |
| 7389 | ``` |
| 7390 | |
| 7391 | `enforcement_blocked` is always `false` now and is kept for one release for |
| 7392 | clients that read it. |
| 7393 | |
| 7394 | When enforcement is on, protected routes call the same decision engine |
| 7395 | before serving or executing data: |
| 7396 | |
| 7397 | ```mermaid |
| 7398 | flowchart LR |
| 7399 | A[""HTTP request""] --> B[""map subject""] |
| 7400 | B --> C[""map route to action""] |
| 7401 | C --> D[""load data/permissions/policy.json""] |
| 7402 | D --> E[""check_permission""] |
| 7403 | E --> F{""allowed?""} |
| 7404 | F -- yes --> G[""serve route""] |
| 7405 | F -- no --> H[""return 401 / 402 / 403""] |
| 7406 | E --> I[""append data/permissions/audit.jsonl""] |
| 7407 | ``` |
| 7408 | |
| 7409 | Route actions currently map like this: |
| 7410 | |
| 7411 | - `GET /objects/{id}` -> `execute` |
| 7412 | - `POST /objects/{id}` -> `execute` |
| 7413 | - `PUT /objects/{id}` -> `update` |
| 7414 | - `DELETE /objects/{id}` -> `delete` |
| 7415 | - `?source=true` -> `source` |
| 7416 | - `?state=true` -> `state` |
| 7417 | - `?logs=true` -> `logs` |
| 7418 | - `?versions=true` or `?version=N` -> `versions` |
| 7419 | - `?metadata=true` -> `read` |
| 7420 | - `GET /collections/{collection}/records` -> `read` |
| 7421 | - `POST /collections/{collection}/records` -> `create` |
| 7422 | - `GET /collections/{collection}/records/{record_id}` -> `read` |
| 7423 | - `PUT /collections/{collection}/records/{record_id}` -> `update` |
| 7424 | - `DELETE /collections/{collection}/records/{record_id}` -> `delete` |
| 7425 | |
| 7426 | Collection record lists apply row filters before pagination. Record detail |
| 7427 | checks include the selected record, so owner, account, subscription, temporary |
| 7428 | access, row-filter, and field-redaction rules can all be enforced by the server. |
| 7429 | Record writes check the affected record. Updates also check the candidate row |
| 7430 | after applying the submitted changes, so a user cannot pass a row filter on the |
| 7431 | old row and then move the row into another owner/account by changing fields. |
| 7432 | Both checks read the row before the write lock, so the write carries that |
| 7433 | row's fingerprint and is refused with `409` `""code"": ""conflict""` (nothing |
| 7434 | written) when the row under the lock is another one: a row given to someone |
| 7435 | else between the check and the write is not written on the old decision. |
| 7436 | The client reads it again and retries, and the retry is decided on the row |
| 7437 | as it now is (docs/dron-write-semantics.md S52). |
| 7438 | |
| 7439 | By default the collection record routes are admin-token gated. Read routes can |
| 7440 | use audit or enforcement mode with the active policy. Write routes require the |
| 7441 | admin token unless permission enforcement is enabled and the active policy |
| 7442 | allows the matching `create`, `update`, or `delete` action. Audit-only mode logs |
| 7443 | write decisions, but it does not authorize mutations by itself. |
| 7444 | |
| 7445 | ### Row-filter index |
| 7446 | |
| 7447 | With enforcement on, a list of a collection (and `/api/search`, an |
| 7448 | anonymous visitor's public rows, and the relation-label fetches a form |
| 7449 | makes) runs the decision engine once per row of the WHOLE collection, for a |
| 7450 | user who may see a handful. Measured in a full install: 10,044 engine calls |
| 7451 | and about 94% of the request to list 40 visible notes out of 10,000. |
| 7452 | |
| 7453 | ```text |
| 7454 | DBBASIC_ROW_FILTER_INDEX=off | shadow | on (default: off) |
| 7455 | ``` |
| 7456 | |
| 7457 | - `off` -- every row is read and checked. Today's behaviour. |
| 7458 | - `on` -- the server first plans, from the policy and the subject alone, |
| 7459 | the equality lookups that are a superset of the rows the subject could be |
| 7460 | allowed (""`owner_id` is u7"", ""`project_id` is one of p1, p2"", |
| 7461 | ""`is_public` is true""), finds those rows through a per-field index kept |
| 7462 | beside the records cache, and runs the engine on them only. The engine |
| 7463 | still decides every row that is returned, so the index can never show a |
| 7464 | row it should not; the differential tests |
| 7465 | (`tests/test_row_filter_pushdown.py`, `..._http.py`) are what stop it |
| 7466 | from hiding one. Responses are identical to `off`: same rows, order, |
| 7467 | `total`, `count`, `has_more`, `revs`, redaction. |
| 7468 | - `shadow` -- both are computed, the full scan is served, and any |
| 7469 | difference is recorded as a `row_filter_shadow` row in the ops log |
| 7470 | (`GET /admin/ops?kind=row_filter_shadow`): ids and counts, never record |
| 7471 | contents. At most one row per collection per minute and 200 in the life |
| 7472 | of a process, so a wrong index cannot crowd login failures out of the |
| 7473 | log the lockout reads. Run this before `on`; it costs more than `off`. |
| 7474 | |
| 7475 | A list is not narrowed, and costs what it does today, when: the subject is |
| 7476 | an admin; the access mode allows reads without rules (`public`, |
| 7477 | `registered`, `subscription`); a rule that applies has no row filter (the |
| 7478 | subject sees everything) or only `ne` / range conditions; any filter in the |
| 7479 | policy uses an unknown operator; the collection is too large for the |
| 7480 | records cache (`DBBASIC_RECORDS_CACHE_MAX_ROWS`); or the only equality a |
| 7481 | rule has is on a `store: extra` field. Deny rules never narrow. |
| 7482 | |
| 7483 | The index is built lazily, one field at a time, by the first narrowed read |
| 7484 | after each write to a collection, and only for the fields that rules and |
| 7485 | the owner keys (`owner_id`, `user_id`, `created_by`) compare by equality. |
| 7486 | It costs 4 bytes per row per field plus about 120 bytes per distinct value |
| 7487 | of that field, and 0.3-0.9 ms per field per 10,000 rows to build. Measured |
| 7488 | on 10,000 notes with the five fields the notes rules use: 3 ms to build, |
| 7489 | 0.4 MiB (40 bytes per row in all); 30,000 notes: 9 ms, 1.2 MiB. The worst |
| 7490 | case is a field whose every value is different, about 120 bytes per row |
| 7491 | (60 MB for one such field at the cache's 500,000-row ceiling); `id`, the |
| 7492 | usual such field, reuses the cache's existing id index and costs nothing. |
| 7493 | The index lives and dies with the records cache entry it describes, so it |
| 7494 | has no invalidation of its own, no file, and no knob beyond the cache's |
| 7495 | (`DBBASIC_RECORDS_CACHE_MAX_ENTRIES`, `DBBASIC_RECORDS_CACHE_MAX_ROWS`). |
| 7496 | |
| 7497 | Time-windowed rules (`valid_from` / `expires_at`) are evaluated at one |
| 7498 | instant per list request, in every mode: the collection check, the row |
| 7499 | filter, a field filter and the field redaction all decide at the same |
| 7500 | reading of the clock. (Before 2026-12, `off` read the clock once per check, |
| 7501 | so a list running across the instant a rule's window closed could let a row |
| 7502 | through under the rule and then redact it under no rule, which removed |
| 7503 | nothing.) |
| 7504 | |
| 7505 | Audit-only mode logs decisions without blocking the request: |
| 7506 | |
| 7507 | ```text |
| 7508 | DBBASIC_ENABLE_PERMISSION_AUDIT=true |
| 7509 | ``` |
| 7510 | |
| 7511 | It serves exactly what `off` serves: collection records, record detail, |
| 7512 | search and user files still need the admin token, as they do with no |
| 7513 | permission flag at all; objects answer per their route rules. (Until this |
| 7514 | release, turning the audit log on skipped those admin gates and served every |
| 7515 | row to anyone, so the observer changed what was served.) That is useful |
| 7516 | before turning enforcement on for a live app. Enforcement also writes audit |
| 7517 | entries. |
| 7518 | |
| 7519 | The audit log is bounded like object logs. When `data/permissions/audit.jsonl` |
| 7520 | reaches `DBBASIC_PERMISSION_AUDIT_MAX_BYTES` (default `10485760`; `0` or less |
| 7521 | never rotates) it is cut into `audit-<sequence>-<timestamp>.jsonl` beside it. |
| 7522 | Each segment is gzip-compressed at the following cut, and only the newest |
| 7523 | `DBBASIC_PERMISSION_AUDIT_KEEP_ROTATED` segments are kept (default `32`; `0` or |
| 7524 | less keeps all). The audit endpoint reads back through the segments when the |
| 7525 | active file holds fewer matching entries than `limit`. |
| 7526 | |
| 7527 | Operators and Scroll can read recent audit entries through the admin-gated audit |
| 7528 | endpoint: |
| 7529 | |
| 7530 | ```http |
| 7531 | GET /permissions/audit?limit=100&object_id=site_home |
| 7532 | Authorization: Token <token> |
| 7533 | ``` |
| 7534 | |
| 7535 | Supported filters are `action`, `object_id`, `collection`, `allowed`, and |
| 7536 | `enforced`. |
| 7537 | |
| 7538 | By default, route checks only trust the admin token and anonymous public traffic. |
| 7539 | If a reverse proxy or auth gateway has already authenticated the request, trusted |
| 7540 | identity headers can be enabled explicitly: |
| 7541 | |
| 7542 | ```text |
| 7543 | DBBASIC_PERMISSION_TRUST_HEADERS=true |
| 7544 | ``` |
| 7545 | |
| 7546 | Supported headers: |
| 7547 | |
| 7548 | - `X-DBBASIC-User-Id` |
| 7549 | - `X-DBBASIC-Account-Id` |
| 7550 | - `X-DBBASIC-Roles` |
| 7551 | - `X-DBBASIC-Subscriptions` |
| 7552 | |
| 7553 | Only enable trusted headers behind infrastructure that strips or overwrites |
| 7554 | client-supplied copies. |
| 7555 | |
| 7556 | ### Identity sources |
| 7557 | |
| 7558 | An *identity source* is another service vouching for who a caller is |
| 7559 | (`object_identity_sources.py`). It takes the request headers and returns a |
| 7560 | principal -- user id, optional account id, roles, display name -- or nothing. |
| 7561 | Sources are configured from the environment, consulted in order (first answer |
| 7562 | wins), and **fail closed**: an exception, a timeout, a non-200, an oversized, |
| 7563 | redirected or non-JSON answer all mean ""not authenticated by this source"". |
| 7564 | |
| 7565 | Order of resolution for a request (`_permission_identity`): |
| 7566 | |
| 7567 | 1. the admin token -- always wins, and is never forwarded anywhere; |
| 7568 | 2. a `dbk_` API key; |
| 7569 | 3. a local session (Authorization header or cookie); |
| 7570 | 4. configured identity sources, for an Authorization token none of the |
| 7571 | above recognised (cookies are never forwarded); |
| 7572 | 5. trusted headers, when `DBBASIC_PERMISSION_TRUST_HEADERS=true`; |
| 7573 | 6. anonymous. |
| 7574 | |
| 7575 | A principal becomes the same `PermissionSubject` a session user gets (user |
| 7576 | id, account id, roles, then project grants and record shares), so the |
| 7577 | permission engine, owner fallback, audit log and the `_identity` an object |
| 7578 | sees treat it exactly like a local user; `GET /identity` reports |
| 7579 | `auth.method` as `identity_source:<name>`. |
| 7580 | |
| 7581 | **A remote identity may not take over a local user.** When the upstream's |
| 7582 | `user_id` names a user in this box's registry (`users.tsv`; users are keyed |
| 7583 | by user id here, and the verify answer carries no email), the identity is |
| 7584 | refused unless that local user is explicitly linked to the source -- the |
| 7585 | user's `identity_source` field equals the source name (`http_verify`). |
| 7586 | Unlinked is the default for every user. Link one with |
| 7587 | `identity_source` in `POST /identity/users`, or from the shell: |
| 7588 | |
| 7589 | ```text |
| 7590 | python -m object_identity_cli set-identity-source --user-id 7 --source http_verify |
| 7591 | python -m object_identity_cli set-identity-source --user-id 7 --unlink |
| 7592 | ``` |
| 7593 | |
| 7594 | Only a row in `users.tsv` makes a user id local. A password, sessions or API |
| 7595 | keys left under an id with no row (a user removed by hand) do not, and a |
| 7596 | remote identity with that id cannot reach them: keys and passwords are |
| 7597 | managed only with that user's own local session or the admin gate, password |
| 7598 | sign-in needs a user row, and a session or key works only for whoever holds |
| 7599 | its token. Creating a local user under such an id refuses or clears them |
| 7600 | first (`POST /identity/users`, `clear-leftovers`). |
| 7601 | |
| 7602 | A refusal is an `auth` ops-log row, `event: identity_source_collision`, with |
| 7603 | the user id and `auth_method: identity_source:<name>` (never the token or its |
| 7604 | hash), at most one a minute per source and user id. A linked user id the |
| 7605 | local registry has disabled is refused too, as for trusted headers. |
| 7606 | |
| 7607 | **A source confers only the roles you allow.** |
| 7608 | `DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES` (comma-separated, e.g. |
| 7609 | `viewer,editor`) lists the role names the verify source may confer. **Unset |
| 7610 | or empty, it confers none**: the upstream says who somebody is, and only an |
| 7611 | operator decides which of its role names mean anything here. Roles the |
| 7612 | upstream names outside the list are dropped, and the drop is an `auth` |
| 7613 | ops-log row (`event: identity_source_roles_dropped`, `label: |
| 7614 | roles=<names>`, the user id; at most one a minute per source and user id). |
| 7615 | A malformed name in the setting refuses the source (an `ERROR` at startup). |
| 7616 | |
| 7617 | **A source can never make anyone admin.** `admin`, `superuser` and every |
| 7618 | role in the policy's `admin_roles` are stripped from what a source says even |
| 7619 | when the allowlist names them (all roles are dropped if the policy cannot be |
| 7620 | read), upstream flags such as `is_staff`/`is_superuser` are not read, and |
| 7621 | the operator gates (admin token, admin session) never consult sources. Note |
| 7622 | that a policy's own `user_roles` entry for that user id still applies -- |
| 7623 | that is the operator granting it, not the upstream. |
| 7624 | |
| 7625 | The user id must be a canonical positive integer -- a JSON int, or a string |
| 7626 | of digits with no sign, whitespace or leading zero -- because it is the |
| 7627 | `u_<id>_` object namespace (see |
| 7628 | [User objects](/docs/http-api-contract#user-objects-non-admin-callers)). `""007""`, |
| 7629 | `"" 7""`, `7.0` and `true` have authenticated nobody. An `account_id`, when the |
| 7630 | answer carries one, must match the account id rules (letters, digits and |
| 7631 | `_ . : @ -`, starting with a letter or digit, at most 128 characters), so |
| 7632 | `""../x""` is refused. The answer must also declare `Content-Type: |
| 7633 | application/json` (a `; charset=` suffix is fine); an HTML error page with a |
| 7634 | JSON-looking body is not an answer. |
| 7635 | |
| 7636 | The first source is `http_verify`: |
| 7637 | |
| 7638 | ```text |
| 7639 | DBBASIC_IDENTITY_VERIFY_URL=https://app-internal:8443/api/auth/verify/ |
| 7640 | DBBASIC_IDENTITY_VERIFY_SECRET=<shared secret, 16-512 visible ASCII characters> |
| 7641 | DBBASIC_IDENTITY_AUDIENCE=box-a.example.com |
| 7642 | ``` |
| 7643 | |
| 7644 | Off when unset. The source is **refused** -- not used at all, an `ERROR` |
| 7645 | line at startup says why (never quoting the secret), `GET /admin/status` |
| 7646 | lists the same reason in `alerts` and in |
| 7647 | `capabilities.identity.identity_source_refused`, `GET /permissions/status` |
| 7648 | in `permissions.identity_source_refused` and `warnings` (none of them quote |
| 7649 | the secret or the URL), and its users arrive as anonymous -- when: |
| 7650 | |
| 7651 | - the URL is not `https://`, unless its host is loopback (`127.0.0.0/8`, |
| 7652 | `::1` or the name `localhost`; a Compose service name or a private |
| 7653 | address is not loopback). A URL with `user:password@` is refused too. |
| 7654 | The same check runs again before every call, and redirects are never |
| 7655 | followed, so a credential never crosses plain http to another host; |
| 7656 | - the host is not loopback and `DBBASIC_IDENTITY_VERIFY_SECRET` is unset |
| 7657 | (or is not 16 to 512 visible ASCII characters with no spaces); |
| 7658 | - `DBBASIC_IDENTITY_AUDIENCE` is unset or not a name (letters, digits and |
| 7659 | `_ . : @ / -`, starting with a letter or digit, at most 256 characters). |
| 7660 | |
| 7661 | A configured source also counts as a user sign-in path in the |
| 7662 | enforcement readiness check (`/permissions/status` shows |
| 7663 | `permissions.identity_source_configured`). For a request carrying `Authorization: Token ...` (or |
| 7664 | `Bearer ...`) it sends that header verbatim in a `GET` with |
| 7665 | `Accept: application/json` to the URL (a 3 s deadline for the whole exchange -- connect, TLS, headers and body -- 64 KiB response |
| 7666 | cap, no redirects followed, no proxy), and maps an HTTP 200 JSON body naming |
| 7667 | this server as its audience to a principal. |
| 7668 | |
| 7669 | **Wire shape, for whoever implements the verify endpoint.** The request: |
| 7670 | |
| 7671 | ```http |
| 7672 | GET /api/auth/verify/ |
| 7673 | Authorization: Token <the caller's token, verbatim> |
| 7674 | Accept: application/json |
| 7675 | X-DBBASIC-Audience: box-a.example.com |
| 7676 | X-DBBASIC-Verify-Secret: <DBBASIC_IDENTITY_VERIFY_SECRET> |
| 7677 | ``` |
| 7678 | |
| 7679 | `X-DBBASIC-Verify-Secret` is omitted when no secret is configured (loopback |
| 7680 | only). The endpoint should compare it in constant time and refuse a request |
| 7681 | without it, and should check that the token may be used at the box named in |
| 7682 | `X-DBBASIC-Audience`. A token it recognises is answered `200` with |
| 7683 | `Content-Type: application/json`: |
| 7684 | |
| 7685 | ```json |
| 7686 | {""audience"": ""box-a.example.com"", ""user_id"": 7, ""username"": ""alice"", |
| 7687 | ""account_id"": ""acct_1"", ""roles"": [""editor""]} |
| 7688 | ``` |
| 7689 | |
| 7690 | `audience` is required and must be a string equal to this server's |
| 7691 | `DBBASIC_IDENTITY_AUDIENCE` -- a missing, different or list-valued audience |
| 7692 | authenticates nobody (cached as a refusal for 10 s). `user_id` is required; |
| 7693 | `username`, `account_id` and `roles` are optional. |
| 7694 | |
| 7695 | The two refusals mean different things, so send the right one: |
| 7696 | |
| 7697 | - `401`: **the token is not valid** (unknown, expired, revoked, not usable |
| 7698 | at this audience). The request itself was acceptable: the shared secret |
| 7699 | matched and the audience is one the endpoint serves. One user's sign-in |
| 7700 | fails; nothing is recorded. |
| 7701 | - `403`: **this server is not accepted**, whatever the token: a missing or |
| 7702 | wrong `X-DBBASIC-Verify-Secret`, or an `X-DBBASIC-Audience` the endpoint |
| 7703 | does not serve. Every sign-in fails, so the server records it for the |
| 7704 | operator (below). |
| 7705 | |
| 7706 | For the caller both are the same: the token is refused and the request goes |
| 7707 | on as anonymous. Anything else (another status, a redirect, a |
| 7708 | timeout, a body over 64 KiB) means ""could not check"" and the caller gets |
| 7709 | `503`. Answers are cached, keyed by a SHA-256 of the header |
| 7710 | value -- raw tokens are never stored or logged -- in a cache bounded to 4,096 |
| 7711 | entries: positive answers for `DBBASIC_IDENTITY_CACHE_TTL_SECONDS` (default |
| 7712 | 30; a larger value than 60 is clamped to 60 with a `WARNING` at startup, and |
| 7713 | nothing in the upstream's answer extends it), a definite refusal (401, 403, or a 200 that is not a valid |
| 7714 | principal) for 10 s. The lookup runs in a thread before routing so a slow |
| 7715 | upstream never blocks the event loop. |
| 7716 | |
| 7717 | An upstream that answers `403` (it refuses this server), or answers `200` |
| 7718 | without this server's audience, or with something that is not a JSON object, |
| 7719 | refuses every user it vouches for, which from outside looks like ""everyone is logged out"". |
| 7720 | The sign of it: an `auth` ops-log row, `event: |
| 7721 | identity_source_audience_refused` (one event for every ""the upstream is not |
| 7722 | accepting this server"" reason), `auth_method: identity_source:<name>` and |
| 7723 | `label: reason=upstream_forbidden refused=<n>` (the upstream answered `403`: |
| 7724 | check that `DBBASIC_IDENTITY_VERIFY_SECRET` here and the upstream's secret |
| 7725 | match, and that `DBBASIC_IDENTITY_AUDIENCE` matches the upstream's audience |
| 7726 | setting) or `reason=audience_missing` (the answer has no `audience` |
| 7727 | key -- an upstream not yet updated to echo it) or `reason=audience_mismatch` |
| 7728 | (the key is there but is not this server's name) or `reason=not_json` (the |
| 7729 | `200` is not a JSON object: an HTML page such as a login page the upstream |
| 7730 | redirected to, a list, text that does not parse), at most one row a minute |
| 7731 | per source and reason, `<n>` counting the answers refused since the previous |
| 7732 | row. `GET /admin/status` lists an alert saying the same in plain words for |
| 7733 | ten minutes after the last such answer, naming every reason seen; it clears |
| 7734 | at once when the upstream answers `200` with the right audience. Neither |
| 7735 | quotes a token, a user, the URL, the secret or the audience value. A `401` |
| 7736 | leaves no row and no alert, even when every answer is one: on a quiet box |
| 7737 | that is just users with stale tokens. |
| 7738 | |
| 7739 | **A credential the server could not check is a 503, not ""anonymous"".** When |
| 7740 | all 8 verify slots are busy (each is held for at most the 3 s deadline, so a |
| 7741 | slow upstream cannot keep them), or the verify service is unreachable, times out |
| 7742 | or answers 5xx (or anything other than 200/401/403), a request that carried an |
| 7743 | `Authorization` token meant for the sources is answered `503` with |
| 7744 | `Retry-After: 2`. Such failures are never cached, so users are recognised |
| 7745 | again the moment the service is back. Requests with no Authorization header, |
| 7746 | the admin token, `dbk_` keys and local sessions never touch the verify path. |
| 7747 | |
| 7748 | **Revocation.** A revoked token keeps working until its cache entry expires |
| 7749 | (at most the TTL). To cut that short, the upstream calls, with the admin token: |
| 7750 | |
| 7751 | ```http |
| 7752 | POST /admin/identity/sources/forget |
| 7753 | Authorization: Token <admin-token> |
| 7754 | Content-Type: application/json |
| 7755 | |
| 7756 | {""token_hash"": ""<sha256 hex of the Authorization header value>""} |
| 7757 | ``` |
| 7758 | |
| 7759 | or `{""all"": true}`. The hash is `sha256(""Token abc123"")` over the full header |
| 7760 | value, lower-case hex -- the server never accepts, logs or echoes a raw token |
| 7761 | here. The answer is `{""status"": ""ok"", ""forgotten"": <n>}`. A lookup that was in |
| 7762 | flight when the entry was forgotten does not store its answer. |
| 7763 | |
| 7764 | **One Authorization header only.** A request with more than one |
| 7765 | `Authorization` header is refused with `400` on every route, so a proxy and |
| 7766 | this server cannot pick different credentials. |
| 7767 | |
| 7768 | **Point it only at a trusted internal service you control.** Every caller's |
| 7769 | credential is sent to it, and whatever it answers for this audience is |
| 7770 | believed. Only `https` URLs (or `http` to loopback) are accepted; anything |
| 7771 | else configures no source. |
| 7772 | |
| 7773 | The verify service's user ids share the id space with the local identity |
| 7774 | registry (and so the `u_<id>_` objects, grants and shares). A box can use |
| 7775 | both only for ids that do not collide, or for local users an operator has |
| 7776 | linked to the source (above). |
| 7777 | |
| 7778 | The server can also mint DBBASIC identity sessions: |
| 7779 | |
| 7780 | ```http |
| 7781 | POST /identity/sessions |
| 7782 | Authorization: Token <admin-token> |
| 7783 | ``` |
| 7784 | |
| 7785 | The admin route can mint arbitrary operator-controlled sessions. For a login |
| 7786 | gateway or local trusted client, `POST /identity/session` can mint a session for |
| 7787 | an existing active user when `DBBASIC_ENABLE_SESSION_LOGIN=true` and the caller |
| 7788 | presents `DBBASIC_SESSION_LOGIN_TOKEN`. That token is separate from the admin |
| 7789 | token. The route accepts only `user_id`, `label`, and `ttl_seconds`; role, |
| 7790 | account, and subscription overrides are rejected so the subject comes from the |
| 7791 | registered user and account. |
| 7792 | |
| 7793 | Sessions store only a token hash under `data/identity/sessions.tsv`. Requests |
| 7794 | can then send `Authorization: Token <session-token>` or |
| 7795 | `Authorization: Bearer <session-token>`, and the server resolves the subject |
| 7796 | directly from its local identity store. This is the first built-in replacement |
| 7797 | for each app hand-rolling the same ""current user, current account, current |
| 7798 | roles, current subscription"" lookup. |
| 7799 | |
| 7800 | ### When a role change, disable or delete takes effect |
| 7801 | |
| 7802 | A credential never carries more than its user has now. Sessions and API keys |
| 7803 | name a user; on every request the server reads that user's row in |
| 7804 | `data/identity/users.tsv` (a stat-cached parse, re-read when the file changes, |
| 7805 | whoever changed it) and takes the user's standing and roles from it. So, |
| 7806 | whether the change came through the admin routes, the CLI, another process or |
| 7807 | a hand edit of the file: |
| 7808 | |
| 7809 | | Change | Sessions | API keys | |
| 7810 | | --- | --- | --- | |
| 7811 | | a role removed | gone on the next request | gone on the next request | |
| 7812 | | a role granted | applies on the next request, no new sign-in | applies on the next request | |
| 7813 | | user disabled (any status but `active`) | refused on the next request and ended (marked revoked) | refused on the next request and deleted | |
| 7814 | | user's row deleted | refused on the next request and ended | refused on the next request and deleted | |
| 7815 | | user re-enabled, or re-created with the same id | old sessions stay ended: sign in again | old keys stay deleted: mint new ones | |
| 7816 | | password reset by emailed link | every session revoked | not touched | |
| 7817 | | password set, changed or removed by an admin (HTTP route or CLI) | every session revoked | not touched | |
| 7818 | | an admin changing or removing their own password with their session | every session revoked except the one making the request | not touched | |
| 7819 | | first password (signup confirmation, first-time setup, `create-superuser`) | nothing to revoke | not touched | |
| 7820 | | the user's account disabled (`PUT /identity/accounts/{id}/status`, `disable-account`) | refused on the next request and ended | refused on the next request, **kept** | |
| 7821 | | the account re-enabled | old sessions stay ended: sign in again | work again, unchanged | |
| 7822 | | the account's subscription removed (a billing lapse) | still signed in; `subscription:` rules stop matching on the next request | unaffected: keys never carry the account's subscriptions | |
| 7823 | |
| 7824 | Password changes revoke at the moment of the change, in the one function |
| 7825 | that writes the password (`object_credentials`), so it does not depend on |
| 7826 | enforcement or on which route or tool did it. If the new password is saved |
| 7827 | but the sessions cannot be ended, the change is reported as a failure (HTTP |
| 7828 | `500 password_sessions_not_ended`, CLI exit 1), not success; setting the |
| 7829 | password again retries. API keys are a separate credential and survive a |
| 7830 | password change. If the account may be compromised, a new password is not |
| 7831 | enough on its own: revoke the user's keys |
| 7832 | (`DELETE /identity/users/{id}/api-keys/{key_id}`) or disable the user |
| 7833 | (`PUT /identity/users/{id}/status` or `/offboard`, which end sessions and delete keys). |
| 7834 | |
| 7835 | ""Ended"" for the other rows happens when the credential is next presented. The status and |
| 7836 | offboard routes revoke everything at once anyway; a status or deletion made |
| 7837 | outside them is refused immediately and ended at first use. A user deleted |
| 7838 | by hand and re-created with the same id before an old session or key is |
| 7839 | presented again would find it alive, with the new row's roles, so creating a |
| 7840 | user looks for credentials left under its id first: a password, sessions |
| 7841 | still signed in, API keys. By default (`POST /identity/users`, the CLI's |
| 7842 | `create-user`) the create is refused and nothing changes, with an error |
| 7843 | naming what was found; `python -m object_identity_cli clear-leftovers |
| 7844 | --user-id <id>` removes them (only for an id with no user), and then the id |
| 7845 | is free. A signup clears them itself, with a warning in the log, since its id |
| 7846 | is new and random. First-time setup and `create-superuser` keep the password |
| 7847 | they have just written but end leftover sessions and delete leftover keys, |
| 7848 | since they wrote neither. |
| 7849 | |
| 7850 | Roles granted through the policy's `user_roles` map are policy, not identity, |
| 7851 | and always applied on the next request. |
| 7852 | |
| 7853 | Subscriptions and account membership follow the same rules as roles. A |
| 7854 | session's account is the user's current `account_id`, and its subscriptions |
| 7855 | are the user's own plus their account's, read from `users.tsv` and |
| 7856 | `data/identity/accounts.tsv` (stat-cached the same way) on every request. So |
| 7857 | a subscription cancelled on the user or on the account stops matching |
| 7858 | `subscription:` rules on the next request; a user moved to another account |
| 7859 | is in the new one (`account:` rules, `$account_id` row filters) on the next |
| 7860 | request, and a user taken out of one has no account. An account whose row is |
| 7861 | gone contributes no subscriptions; a disabled account refuses its users |
| 7862 | altogether (below). API keys read the user's row on every request too and |
| 7863 | have the user's own subscriptions and account; they do not add the account's |
| 7864 | subscriptions. |
| 7865 | |
| 7866 | #### Disabling an account, and a billing lapse |
| 7867 | |
| 7868 | Two different operations, for two different situations: |
| 7869 | |
| 7870 | - **Disable the account** (`PUT /identity/accounts/{id}/status` |
| 7871 | `{""status"": ""disabled""}`, or `object_identity_cli.py disable-account |
| 7872 | --account-id {id}`) when nobody from that account may use the box at all: |
| 7873 | abuse, a compromised tenant, a contract ended. On the next request every |
| 7874 | session and API key of its users is refused (whatever their roles, admin |
| 7875 | included, as for a disabled admin user), its users cannot sign in, and |
| 7876 | their sessions are ended. API keys are kept but refused, so a mistaken or |
| 7877 | temporary disable does not break the customer's integrations for good. |
| 7878 | Re-enabling (`{""status"": ""active""}`, `enable-account`) lets them sign in |
| 7879 | again and makes the same keys work again; no session comes back. The admin |
| 7880 | token, and admins who are not in the account, are never affected, so an |
| 7881 | operator cannot lock themselves out this way. The route writes an |
| 7882 | `account_status_set` ops line. Details in |
| 7883 | [http-api-contract.md](/docs/http-api-contract) (""Account Status""). |
| 7884 | - **Remove the subscription** for non-payment. A billing lapse is not a |
| 7885 | disable: the customer has to be able to sign in to pay. Take the plan out |
| 7886 | of the account's `subscriptions` (and the user's, if it was granted there): |
| 7887 | on the next request `subscription:` rules stop matching, while the user |
| 7888 | stays signed in, can sign in fresh, keeps the account (`account:` rules, |
| 7889 | `$account_id` filters) and their API keys. Putting the subscription back |
| 7890 | applies on the next request, with no new sign-in. Use |
| 7891 | `PUT /identity/accounts/{id}/subscriptions` `{""subscriptions"": [...]}` (the |
| 7892 | whole list; `[]` for none) or `object_identity_cli.py |
| 7893 | set-account-subscriptions --account-id {id} --subscriptions pro,team`: |
| 7894 | input is validated, the write is atomic, and each change leaves an |
| 7895 | `account_subscriptions_set` ops line with who did it and the list before |
| 7896 | and after ([http-api-contract.md](/docs/http-api-contract), ""Account |
| 7897 | Subscriptions""). A hand edit of the `subscriptions` column of |
| 7898 | `data/identity/accounts.tsv` is still picked up on the next request, but |
| 7899 | is neither validated nor recorded. A member's subscriptions are their own |
| 7900 | (user row) plus the account's, so a name the user holds on their own row |
| 7901 | survives its removal from the account; API keys carry only the user's own. |
| 7902 | Plan the rules so that what a lapsed customer still |
| 7903 | needs (their invoices, the billing page) is granted to `registered` or |
| 7904 | `account:` principals, not only to `subscription:` ones. |
| 7905 | |
| 7906 | To check this, `accounts.tsv` is consulted on every request of a user who |
| 7907 | has an account, by session or API key (one `stat`, re-parsed only when the |
| 7908 | file changes; users with no account do not touch it). If it cannot be read the request is |
| 7909 | `503 identity_store_unavailable` under enforcement and carries no credential |
| 7910 | otherwise, as for `users.tsv` (below); nothing is revoked or deleted. An |
| 7911 | account row that does not parse refuses its users without ending anything, |
| 7912 | so fixing the row restores them. A user whose `account_id` names an account |
| 7913 | with no row at all (or when there is no `accounts.tsv`) is refused the same |
| 7914 | way; this used to refuse nobody. Both are fail-closed refusals with their |
| 7915 | own code: under enforcement every request with such a user's session or API |
| 7916 | key is `403 account_unusable` (a fixed message; the admin token sees which |
| 7917 | account and why in `error_detail` on admin routes), otherwise the |
| 7918 | credential carries no authority; signing in is `403 account_unusable` in |
| 7919 | both modes, and only after the right password, so nobody learns of it |
| 7920 | without one (the browser form redirects to `/login?error=account`). Each |
| 7921 | refusal writes an `account_unusable` ops `auth` line naming the user, the |
| 7922 | account and `reason=missing` or `reason=unparsed` (at most one a minute per |
| 7923 | user, account, reason and method). A user with several rows in `users.tsv` |
| 7924 | that name different accounts (or where one names none) is refused the same |
| 7925 | way, `reason=conflicting`, with every account named as the `identifier` |
| 7926 | (`acme,globex`; `(none)` for a row naming none): those rows used to merge |
| 7927 | into a user with no account, which skipped every account check. Duplicate |
| 7928 | rows that agree are read as before. Nothing is ended or deleted, so |
| 7929 | restoring the row restores everyone. Users whose row names no account (a |
| 7930 | single-user install, users created before accounts existed: an empty |
| 7931 | `account_id` or no such column) never read `accounts.tsv` and are not |
| 7932 | affected by its state. An ad hoc session for a user id with no row, and an |
| 7933 | account id asserted by a gateway or identity source, are not refused for |
| 7934 | naming an account this box has no row for. A disable written outside the route ends each session the |
| 7935 | first time it is presented, like a user disabled by hand. |
| 7936 | |
| 7937 | Which roles, subscriptions and account a session has depends on how it was |
| 7938 | minted: |
| 7939 | |
| 7940 | - **From the user's row** (every sign-in route, and `POST /identity/sessions` |
| 7941 | without `roles` or `subscriptions`): the user's current roles, account and |
| 7942 | subscriptions. |
| 7943 | - **With explicit `roles` or `subscriptions`** (`POST /identity/sessions` for |
| 7944 | a registered user): the roles and subscriptions it was minted with less any |
| 7945 | the user no longer has, and its account only while the user is still in it. |
| 7946 | A narrowed session stays narrow; nothing the user does not hold gets |
| 7947 | through; a role, subscription or account the user gains later needs a new |
| 7948 | session. |
| 7949 | - **For a user id with no row** (an ad hoc gateway session; refused under |
| 7950 | `DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS=true`): the roles it was minted with, |
| 7951 | since there is nothing to compare them with. If a row for that id appears |
| 7952 | later, the row caps them. An API key for such an id authenticates as the |
| 7953 | id with no roles, as before. |
| 7954 | - **Written by an older server** (a `sessions.tsv` row with no `roles_from` |
| 7955 | column, or an `api_keys.tsv` row with no `user_bound` column): capped by the |
| 7956 | user's roles, subscriptions and account while the row exists, like an |
| 7957 | explicit session; a deleted user's old session keeps its stored values, and an old key the user id with no roles, until they expire or |
| 7958 | are revoked, because such rows cannot tell ""deleted"" from ""never |
| 7959 | registered"". Revoke them (`PUT /identity/users/{id}/status`) or wait out |
| 7960 | the session TTL (at most 30 days, 24 hours by default). |
| 7961 | |
| 7962 | If `users.tsv` cannot be read, or is missing while a credential names a |
| 7963 | registered user, or `accounts.tsv` cannot be read when a session needs its |
| 7964 | user's account's subscriptions, the request is not guessed at: under enforcement it is |
| 7965 | `503 identity_store_unavailable` with `Retry-After` (see Route Enforcement), |
| 7966 | otherwise it carries no credential. Nothing is revoked, so restoring the file |
| 7967 | restores everyone. A row that does not parse refuses that user's credentials |
| 7968 | without ending them, so fixing the row restores them. |
| 7969 | |
| 7970 | Users from an identity source (above) have no local session and no stored |
| 7971 | roles here: their roles are the upstream's latest answer (less anything |
| 7972 | outside `DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES`), trusted for |
| 7973 | `DBBASIC_IDENTITY_CACHE_TTL_SECONDS` (30 s by default, never more than 60), or |
| 7974 | until `POST /admin/identity/sources/forget` drops it. That TTL is the bound on |
| 7975 | a role the upstream removed. A local row for the same id refuses them unless it |
| 7976 | is linked to the source (`identity_source`, above). A linked row that is disabled, |
| 7977 | or that names a local account that is disabled, refuses them on the next |
| 7978 | request, and so does an account id the upstream names when that account has |
| 7979 | a local row that is disabled; local roles do not cap or add to theirs. The |
| 7980 | trusted-header path (`X-DBBASIC-User-Id`, `X-DBBASIC-Account-Id`) refuses the |
| 7981 | same cases. |
| 7982 | |
| 7983 | Clients can inspect or revoke their own active session without the admin token: |
| 7984 | |
| 7985 | ```http |
| 7986 | GET /identity/session |
| 7987 | DELETE /identity/session |
| 7988 | Authorization: Token <session-token> |
| 7989 | ``` |
| 7990 | |
| 7991 | Those routes require an active session token and do not treat the admin token as |
| 7992 | a user session. |
| 7993 | |
| 7994 | The active subject can be inspected through: |
| 7995 | |
| 7996 | ```http |
| 7997 | GET /identity |
| 7998 | Authorization: Token <token> |
| 7999 | ``` |
| 8000 | |
| 8001 | Admin-token-gated operator routes still require `DBBASIC_ADMIN_TOKEN` by |
| 8002 | default. A deployment can opt in to `DBBASIC_ENABLE_SESSION_ADMIN_GATES=true`; |
| 8003 | when enabled, an active DBBASIC session whose subject has one of the policy |
| 8004 | admin roles can pass the same gate. This is intended for Scroll/operator clients |
| 8005 | that should stop carrying the raw deployment token after login exists. |
| 8006 | |
| 8007 | That endpoint returns the normalized `user_id`, `account_id`, roles, |
| 8008 | subscriptions, auth method, and permission-mode flags the server will use for |
| 8009 | route checks. |
| 8010 | |
| 8011 | Operators and Scroll can inspect permission rollout readiness through: |
| 8012 | |
| 8013 | ```http |
| 8014 | GET /permissions/status |
| 8015 | Authorization: Token <admin-token> |
| 8016 | ``` |
| 8017 | |
| 8018 | That endpoint summarizes the active mode flags, identity counts, persisted |
| 8019 | policy shape, covered route groups, readiness, and warnings. Readiness is |
| 8020 | advisory: it says what would hurt if enforcement were on now (or, when it is |
| 8021 | on, what is hurting), and never switches enforcement on or off. It is meant |
| 8022 | to be read before enabling enforcement on a live app. For identity-gated |
| 8023 | modes, one of these non-admin identity paths should exist, or only the admin |
| 8024 | token and public grants get in: |
| 8025 | trusted proxy headers, guarded session login for existing users, password |
| 8026 | login (`DBBASIC_ENABLE_PASSWORD_LOGIN=true`, counted before any user exists: |
| 8027 | the first one arrives through `/setup`, signup or the admin token), an active |
| 8028 | DBBASIC session, or a configured identity source (a valid |
| 8029 | `DBBASIC_IDENTITY_VERIFY_URL`; see below). The startup check counts an identity |
| 8030 | source as a sign-in path, so a deployment whose users sign in only through one |
| 8031 | reports no problem. A verify source that is set but refused (not `https://` or |
| 8032 | loopback `http://`, no secret for a remote host, no audience, or empty) does not count, and the server makes no network call at startup to |
| 8033 | check that the verifier answers. |
| 8034 | |
| 8035 | ## Access Modes |
| 8036 | |
| 8037 | Access modes answer who gets through the front door. |
| 8038 | |
| 8039 | - `public` - anyone can read or execute public objects. |
| 8040 | - `password` - a shared gate authenticates before policy checks. |
| 8041 | - `registered` - any signed-in user can read or execute. |
| 8042 | - `subscription` - signed-in users with an active subscription can read or |
| 8043 | execute. |
| 8044 | - `role_based` - rules decide by role, user, account, owner, row, field, and |
| 8045 | action. |
| 8046 | - `private` - owner-only fallback unless explicit rules grant access. |
| 8047 | |
| 8048 | An access mode never opens a user object (`u_<id>_<name>`) to anyone but |
| 8049 | its owner. `public`, `registered` and `subscription` allow read and execute |
| 8050 | without a rule on system and package objects only; on a user object the |
| 8051 | mode's grant reaches user `<id>` alone, and everybody else is decided as in |
| 8052 | `role_based`: an admin role or an allow rule naming the `object_id` (see |
| 8053 | [Sharing](#sharing)), otherwise `403` with |
| 8054 | `""user object is not shared with this caller""`. A caller the mode itself |
| 8055 | refuses (anonymous under `registered`, no subscription under |
| 8056 | `subscription`) gets the mode's `401` / `402` as before. |
| 8057 | |
| 8058 | This matters where the gate is asked about a user object on someone else's |
| 8059 | behalf: a site route or an override whose `object_id` is a user object. |
| 8060 | (`/objects/{id}` already answers a non-owner `404` before the gate is |
| 8061 | asked, in every mode.) Earlier releases ran such a route for any caller the |
| 8062 | mode let in. To keep a route to a user object open to others, add a rule |
| 8063 | naming the object: |
| 8064 | |
| 8065 | ```json |
| 8066 | {""effect"": ""allow"", ""principal"": ""public"", ""actions"": [""read"", ""execute""], |
| 8067 | ""object_id"": ""u_42_report""} |
| 8068 | ``` |
| 8069 | |
| 8070 | Use `registered`, `role:<name>` or `user:<id>` as the principal to open it |
| 8071 | to fewer callers. |
| 8072 | |
| 8073 | ## Rules |
| 8074 | |
| 8075 | Rules answer what the subject can do once they are known. |
| 8076 | |
| 8077 | Actions should stay small and explicit: |
| 8078 | |
| 8079 | - `create` |
| 8080 | - `read` |
| 8081 | - `update` |
| 8082 | - `delete` |
| 8083 | - `execute` |
| 8084 | - `source` |
| 8085 | - `state` |
| 8086 | - `logs` |
| 8087 | - `files` |
| 8088 | - `versions` |
| 8089 | - `share` |
| 8090 | - `admin` |
| 8091 | |
| 8092 | Principal strings are portable on purpose: |
| 8093 | |
| 8094 | - `public` |
| 8095 | - `registered` |
| 8096 | - `owner` |
| 8097 | - `role:admin` |
| 8098 | - `role:sales` |
| 8099 | - `user:42` |
| 8100 | - `account:customer-acme` |
| 8101 | - `subscription:pro` |
| 8102 | |
| 8103 | One more principal is not a subject at all: `owner_fallback`, valid only on |
| 8104 | a deny rule, switches the owner fallback off for the rule's actions and |
| 8105 | resource. See [Ownership](#ownership). |
| 8106 | |
| 8107 | Explicit denies are checked before allow rules. |
| 8108 | |
| 8109 | A deny rule with a `row_filter` is about some rows, so it does not match the |
| 8110 | collection-level question (a list, a search, a `/ws` subscribe, asked with |
| 8111 | no record): the list is allowed and the deny hides exactly the rows its |
| 8112 | filter names, per record. Before 2026-11-28 such a deny refused the whole |
| 8113 | list with 403 for every principal except `owner`. |
| 8114 | |
| 8115 | ## Pointing at a record you may not act on |
| 8116 | |
| 8117 | A rule decides who may write a row. It says nothing about the row that row |
| 8118 | points at, and a row that points at something usually acts on it: a refund |
| 8119 | takes money out of its payment, a payment marks its invoice paid, a line |
| 8120 | changes its order's total, a stock move changes a product's level. Until |
| 8121 | 2026-11-30 the shipped rules for all of those were ""registered users create |
| 8122 | rows whose `owner_id` is their own"", so any signed-in user could refund any |
| 8123 | customer's payment: the refund was theirs, the money was somebody else's. |
| 8124 | |
| 8125 | A relation states what its writer must be allowed to do to the target: |
| 8126 | |
| 8127 | ```json |
| 8128 | {""name"": ""payment_id"", |
| 8129 | ""relation"": {""collection"": ""payments"", ""display_field"": ""reference"", ""requires"": ""update""}} |
| 8130 | ``` |
| 8131 | |
| 8132 | On a `POST` or `PUT` through the record API with enforcement on, the server |
| 8133 | reads the target and asks the engine, for the same subject and policy, |
| 8134 | whether it may `read` it and (for `""update""`) `update` it -- exactly the |
| 8135 | question `PUT /collections/payments/records/{id}` would ask, owner fallback, |
| 8136 | project grants and roles included. Admins pass, as they pass every rule. |
| 8137 | |
| 8138 | - Checked on create for every such field with a value, and on update for each |
| 8139 | one whose value changes. |
| 8140 | - A target the writer may not read gets the same 400 a missing one gets |
| 8141 | (`references a missing record`), so the check is no oracle for ids. One |
| 8142 | they may read but not update gets a 403 naming the field. |
| 8143 | - An unreadable target collection is a 503; nothing is written. |
| 8144 | - `update` where the child moves money, stock or state of the parent (or a |
| 8145 | rollup on the parent sums it); `read` where it is a reference (the contact |
| 8146 | an invoice is for, the project a note is filed under, a public category). |
| 8147 | A project member with a read grant can therefore still file a note under |
| 8148 | the project: the engine has no ""write member"" action on a project row to |
| 8149 | ask for. |
| 8150 | - Trusted server-side writers (actions, webhooks, the daemon) write through |
| 8151 | `object_records` and never reach it. An action that writes a child of a |
| 8152 | record it was handed asks `object_access` about that record itself (below). |
| 8153 | |
| 8154 | `tests/test_relation_requires_guard.py` fails when a shipped collection that a |
| 8155 | non-admin principal may create or update has a relation with no `requires` |
| 8156 | and no stated reason (its `EXEMPT`) for going without, and when a writable |
| 8157 | child that a parent rolls up requires less than `update` on it. |
| 8158 | `tests/test_relation_requires_collections.py` probes every declared pointer |
| 8159 | over HTTP as a registered user who owns nothing involved. |
| 8160 | |
| 8161 | ## Objects That Read Storage Directly |
| 8162 | |
| 8163 | A page or action that reads records with `object_records` gets the raw row: |
| 8164 | the collection API's rules, row filters and owner checks do not run. Such an |
| 8165 | object is the only gate in front of what it shows or changes, so it asks the |
| 8166 | same engine with `object_access`: |
| 8167 | |
| 8168 | ```python |
| 8169 | access = object_access.Access(request.get(""_identity""), base_dir=base) |
| 8170 | order = access.get(""orders"", order_id) # None when missing OR refused |
| 8171 | if order is None: |
| 8172 | return not_found() # one answer for both: no oracle |
| 8173 | if not access.can(""update"", ""disputes"", dispute): |
| 8174 | return {""status"": 404, ...} |
| 8175 | rows = access.visible(""wallet_entries"", rows) # the rows the API would list |
| 8176 | ``` |
| 8177 | |
| 8178 | It answers what the API would for the same subject under the active policy, |
| 8179 | with two differences, both towards refusing: a request with no `_identity` |
| 8180 | is anonymous (an in-process caller that wants authority passes one |
| 8181 | explicitly); and an unreadable policy refuses everybody. Project and |
| 8182 | record-share grants are resolved by the server's own code |
| 8183 | (`object_access.with_grants`), so a rule that matches through |
| 8184 | `$accessible_projects` or `$shared_records` matches for a project member |
| 8185 | or a sharee exactly as it does over the API. Field redaction is not |
| 8186 | applied: the object renders the fields it chooses. |
| 8187 | |
| 8188 | One difference goes the other way, and it matters for `update` and |
| 8189 | `delete`: the record API first asks the collection-level question with no |
| 8190 | record, and `can()` with a record does not. So where a collection has no |
| 8191 | rule for the action, the API refuses and `can()` answers with the owner |
| 8192 | fallback: yes, for the row's owner. A collection that must be |
| 8193 | read-only to its owners says so with an `owner_fallback` rule |
| 8194 | ([Ownership](#ownership)); do not infer it from the absence of a grant. |
| 8195 | |
| 8196 | ### The guard test: forgetting is a CI failure |
| 8197 | |
| 8198 | Most access bugs found in November 2026 were an object that read or changed |
| 8199 | someone's record through `object_records` and never asked. The platform |
| 8200 | remembers the other rules for people; this one it checks. |
| 8201 | `tests/test_object_access_guard.py` parses (with `ast`, not grep) every |
| 8202 | `packages/*/objects/site/*.py` and `packages/*/objects/action/*.py` and |
| 8203 | fails on any reference to a public `object_records` reader or writer |
| 8204 | (`read_collection_records`, `get_collection_record`, `create_`/`update_`/ |
| 8205 | `delete_collection_record`, `read_collection_records_where` and the rest of |
| 8206 | the lists in the test) unless one of these holds: |
| 8207 | |
| 8208 | 1. **The file asks `object_access` about that collection.** An `Access` |
| 8209 | object's `.get(collection, id)`, `.can(action, collection, record)`, |
| 8210 | `.visible(collection, rows)` or `.reads_every_row(collection)` appears in |
| 8211 | the same file, with the same collection (a literal, a module constant, or |
| 8212 | the same variable expression). Asking about `orders` does not cover |
| 8213 | `order_lines`: each collection needs its own question or its own |
| 8214 | exemption. The test checks that the file asks, not that the answer is |
| 8215 | used; reading the diff for that is still a person's job. |
| 8216 | 2. **The call carries an exemption comment** on its own line or on a comment |
| 8217 | line directly above it: |
| 8218 | |
| 8219 | ```python |
| 8220 | # access: box configuration |
| 8221 | rows = object_records.read_collection_records(""app_settings"", base_dir=base) |
| 8222 | ``` |
| 8223 | |
| 8224 | The reason is a sentence a reviewer can check against the code around it |
| 8225 | (""box configuration"", ""system write after the access check above"", |
| 8226 | ""capability link: the invoice is found by its secret portal_token"", |
| 8227 | ""public catalog"", ""the caller's own row: owner_id is the caller's |
| 8228 | user_id""). Two reasons are checked against the rules files: `admin-only |
| 8229 | object (...)` needs every `execute` grant for the object to be |
| 8230 | `role:admin` (none at all also counts), and `role-only object (...)` |
| 8231 | needs at least one grant, all of them `role:*`. `public ...` needs a |
| 8232 | rule letting `public` read the collection, and covers reads only. |
| 8233 | |
| 8234 | A hand-written `owner_id == user_id` test is not an exemption for the |
| 8235 | reason in [Objects That Read Storage Directly](#objects-that-read-storage-directly): |
| 8236 | the ones that let a row with a blank owner through disagreed with the API |
| 8237 | for admins, roles and unowned rows, and were the bugs. Where the filter is |
| 8238 | strictly tighter than the engine (the caller's own rows and nothing else) |
| 8239 | say so in the comment; where it can pass a row the engine would refuse, use |
| 8240 | `object_access`. |
| 8241 | |
| 8242 | New public functions in `object_records` must be classified in the test |
| 8243 | (reads rows, writes rows, or neither), so the list the guard enforces |
| 8244 | cannot go stale. Objects under `objects/system`, `hook` and `webhook`, and |
| 8245 | helper modules at the repository root, are not scanned. |
| 8246 | |
| 8247 | ## Package Rules And Upgrades |
| 8248 | |
| 8249 | An installed package's rules sit in the same policy file as the operator's, |
| 8250 | each stamped `""package"": ""<id>""` when the install appended it. Installing a |
| 8251 | package again (an upgrade) does two things to that file, in this order: |
| 8252 | |
| 8253 | 1. **Retires the rules the package has withdrawn.** A live rule is removed |
| 8254 | only when BOTH hold: it is tagged as this package's, and it is identical |
| 8255 | (everything but `reason`) to a rule the package is known to have shipped |
| 8256 | and no longer ships. ""Known"" is the rules recorded at the package's last |
| 8257 | install (`permissions` in `data/package_baselines/<id>.json`), or the |
| 8258 | `retracted` list in the package's permissions file |
| 8259 | ([`package-authoring.md`](/docs/package-authoring)). |
| 8260 | 2. **Appends the rules it ships that are not in the policy.** |
| 8261 | |
| 8262 | Until 2026-11-28 only step 2 existed, so a package that deleted a grant or |
| 8263 | added a row filter to one (a different rule) fixed new installs only: an |
| 8264 | existing box kept the old, wider rule, and an allow rule that is still in |
| 8265 | the policy still allows. |
| 8266 | |
| 8267 | What an upgrade will not do is remove something it cannot prove the package |
| 8268 | put there: |
| 8269 | |
| 8270 | - a rule with no `package` tag is the operator's, even when it is identical |
| 8271 | to one a package withdrew (reported as `operator_rule`: it is now the |
| 8272 | only thing keeping that grant alive); |
| 8273 | - a rule the operator edited keeps its tag but no longer matches what was |
| 8274 | shipped, so it stays (reported as `unaccounted`). To keep such a rule and |
| 8275 | stop it being reported, delete its `package` field; to drop it, delete the |
| 8276 | rule; |
| 8277 | - a rule another installed package still ships changes hands |
| 8278 | (`reassign`) instead of being removed. |
| 8279 | |
| 8280 | A box installed before the baseline recorded rules has no record of what it |
| 8281 | was given. On it, only the rules a package explicitly `retracted` are |
| 8282 | removed; any other tagged rule the package does not ship is `unaccounted` |
| 8283 | until its first upgrade has recorded a baseline. |
| 8284 | |
| 8285 | Where to look: |
| 8286 | |
| 8287 | - the dry run (`GET /packages/{id}?dry_run=true`) and the install response |
| 8288 | carry `permission_retractions`: one entry per rule with `action` |
| 8289 | (`remove`, `reassign`, `keep`), `because`, `why` and the whole `rule`; |
| 8290 | - `GET /packages/{id}/changes` keeps every removed or reassigned rule |
| 8291 | whole, so a grant an upgrade took away can be read back and, if it was |
| 8292 | wanted, put back by hand without a package tag; |
| 8293 | - the restore point taken before the install includes the policy file; |
| 8294 | - at any time, the rules in the policy that no installed package ships: |
| 8295 | |
| 8296 | ```http |
| 8297 | GET /permissions/unshipped |
| 8298 | Authorization: Token <admin-token> |
| 8299 | ``` |
| 8300 | |
| 8301 | ```json |
| 8302 | { |
| 8303 | ""status"": ""ok"", |
| 8304 | ""rules"": [ |
| 8305 | {""index"": 41, ""state"": ""retracted"", ""package"": ""app-notes"", |
| 8306 | ""rule"": {""effect"": ""allow"", ""principal"": ""public"", ""actions"": [""execute""], |
| 8307 | ""object_id"": ""site_notes"", ""package"": ""app-notes"", ""..."": ""...""}} |
| 8308 | ], |
| 8309 | ""count"": 1, |
| 8310 | ""policy_rules"": 212, |
| 8311 | ""installed_packages"": [""app-notes"", ""app-tasks""], |
| 8312 | ""wide_rules"": [], |
| 8313 | ""warnings"": [] |
| 8314 | } |
| 8315 | ``` |
| 8316 | |
| 8317 | `state` is `operator` (no package tag), `retracted` (the package's next |
| 8318 | install will remove it), `unaccounted` (tagged for an installed package |
| 8319 | that neither ships nor retracts it) or `package_missing` (tagged for a |
| 8320 | package that is not installed or whose files are not on this box). A listed |
| 8321 | rule that is wide (see ""A wide rule left over from an older starter policy"") |
| 8322 | also has a `wide` string, and `wide_rules` lists every wide rule in the whole |
| 8323 | policy as `{index, package, why, rule}`. The report is read-only. |
| 8324 | |
| 8325 | **Upgrading a box that predates this:** reinstall each installed package |
| 8326 | (`POST /packages/{id}/install` with `{""allow_replace"": true}`; take one |
| 8327 | `POST /admin/backups` first and add `""restore_point"": ""<backup id>""` to each |
| 8328 | install so the run does not write a full archive per package), read |
| 8329 | `permission_retractions` in each response, then read |
| 8330 | `GET /permissions/unshipped` once and decide about whatever is left. |
| 8331 | |
| 8332 | ## What Runs Outside The Policy |
| 8333 | |
| 8334 | The policy decides what a *request* may do. The daemon and the scheduler are |
| 8335 | not requests. They run as the system, with no user behind them, so the policy |
| 8336 | is never consulted for what they do: |
| 8337 | |
| 8338 | - The daemon (`object_daemon.py`) imports no permission code. Its passes |
| 8339 | (scheduler, queue, rollups, auto-transitions, notifications, mail sync, |
| 8340 | scheduled backups and the rest) read and write through `object_records` |
| 8341 | with a fixed system actor such as `daemon:scheduler`, which never asks |
| 8342 | `object_permissions` for a decision. |
| 8343 | - A scheduled object method runs through `execute_object` with an empty |
| 8344 | payload and no identity: it runs as itself, not as whoever scheduled it and |
| 8345 | not as the admin. `execute_object` makes no policy decision either; the |
| 8346 | policy is only applied by the HTTP routes in front of it. |
| 8347 | |
| 8348 | Why: there is nobody to ask. A nightly backup or a queue drain has no session, |
| 8349 | and a rule written for ""registered users"" or ""owners"" has no meaning for it. |
| 8350 | Making these jobs depend on the policy would also let a broken or restrictive |
| 8351 | policy stop backups and queues. |
| 8352 | |
| 8353 | What an admin should take from this: |
| 8354 | |
| 8355 | - A deny-all policy does not stop scheduled work. Rules cannot be used to |
| 8356 | switch off a scheduled job; remove the task instead (the scheduler task |
| 8357 | endpoints under `/daemon/scheduler/tasks` need the admin token). |
| 8358 | - Whoever can install an object that schedules itself, or create a scheduler |
| 8359 | task, is in effect granting that code system-level access to records. Treat |
| 8360 | that as an admin decision. |
| 8361 | - User-namespace objects (`u_<uid>_*`) are the exception to ""unrestricted"": |
| 8362 | when scheduled they still run in the sandboxed worker described at the top |
| 8363 | of this page, so they reach only their own state, logs and files. The |
| 8364 | sandbox is the boundary there, not the policy. |
| 8365 | - Decisions made by these jobs are not in the permission audit log, because no |
| 8366 | decision is made. Look at the daemon log, `scheduler_runs` and the activity |
| 8367 | log instead. |
| 8368 | |
| 8369 | ## Ownership |
| 8370 | |
| 8371 | The old object convention still matters: |
| 8372 | |
| 8373 | ```text |
| 8374 | u_42_report |
| 8375 | ``` |
| 8376 | |
| 8377 | That object belongs to user `42`. Owners can read, execute, update, inspect, |
| 8378 | share, and delete their own user objects unless a future stricter policy blocks |
| 8379 | that behavior. |
| 8380 | |
| 8381 | Records can also carry ownership fields: |
| 8382 | |
| 8383 | ```json |
| 8384 | { |
| 8385 | ""owner_id"": ""42"", |
| 8386 | ""customer_account_id"": ""customer-acme"" |
| 8387 | } |
| 8388 | ``` |
| 8389 | |
| 8390 | The server can use `owner_id`, `user_id`, or `created_by` as owner fields for the |
| 8391 | basic fallback. Application objects can add richer policy around account, |
| 8392 | department, project, team, or customer ownership. |
| 8393 | |
| 8394 | ### The fallback applies after your rules, not instead of them |
| 8395 | |
| 8396 | The owner fallback is the last step of the decision: when no allow rule |
| 8397 | matches, whoever one of those three fields names may still `read`, `update` |
| 8398 | and `delete` the record (and `execute`, `source`, `state`, `logs`, `files`, |
| 8399 | `versions`, `share`). **Leaving an action out of a collection's rules |
| 8400 | therefore does not refuse it to the row's owner.** A collection whose only |
| 8401 | rule is ""the owner may read their own rows"" is, as far as the engine is |
| 8402 | concerned, also updatable and deletable by that owner. |
| 8403 | |
| 8404 | Where that answer reaches: |
| 8405 | |
| 8406 | - `object_access` (pages, actions, hooks): always. `Access.can(""update"", |
| 8407 | collection, record)` is true for the owner. |
| 8408 | - The record API (`PUT` / `DELETE /collections/{c}/records/{id}`): only when |
| 8409 | the subject first passes the collection-level question the API asks |
| 8410 | before it looks the record up, which has no record and so no fallback. |
| 8411 | With no update or delete rule on the collection that question is a 403, |
| 8412 | which is why a stock install refuses the owner. It stops refusing as |
| 8413 | soon as ANY allow rule for that action matches the subject at the |
| 8414 | collection level, row filter or not: a rule ""support may update runs |
| 8415 | that need review"" lets a support user update their own settled runs, |
| 8416 | through the fallback. Do not rely on the first question as access |
| 8417 | control; it exists so a missing id cannot be told from a forbidden one. |
| 8418 | - Files (`/api/files/{id}`, the WebDAV folder, and a file attached to an |
| 8419 | AI chat turn, `POST /api/ai/chat` with `attachments`): the same as the |
| 8420 | record API. With no `files` rule for the action, the owner is refused |
| 8421 | there too. An attachment is a `read`; a refused one fails the turn with |
| 8422 | a 400 before anything is sent to the provider, and a file refused on |
| 8423 | its record reads like a missing one. Attachments are owner-only on top |
| 8424 | of that, whatever the policy says. In audit mode the attachment is sent |
| 8425 | as before, and both questions are recorded in the permission audit log |
| 8426 | (`enforced: false`), a would-be refusal included. |
| 8427 | - ""Owner"" is whoever those fields name. A grant row that names its grantee |
| 8428 | in `user_id` makes the grantee its owner. |
| 8429 | |
| 8430 | ### Switching the fallback off for a collection |
| 8431 | |
| 8432 | A package (or an operator) that means ""only what the rules say"" ships a |
| 8433 | rule that says so: |
| 8434 | |
| 8435 | ```json |
| 8436 | { |
| 8437 | ""effect"": ""deny"", |
| 8438 | ""principal"": ""owner_fallback"", |
| 8439 | ""actions"": [""update"", ""delete""], |
| 8440 | ""collection"": ""template_runs"", |
| 8441 | ""reason"": ""a run is read-only to the person it belongs to"" |
| 8442 | } |
| 8443 | ``` |
| 8444 | |
| 8445 | It is consulted in one place: after the allow rules have found nothing, and |
| 8446 | only when the fallback would otherwise have allowed. So: |
| 8447 | |
| 8448 | - an explicit allow rule for the same action still grants. This is the |
| 8449 | difference from an ordinary `deny`, which is checked first and beats |
| 8450 | every allow. ""Owners may edit their own drafts"" beside an opt-out for |
| 8451 | `update` lets drafts be edited and nothing else; |
| 8452 | - admins are decided before any rule, and in-process writers |
| 8453 | (`object_records`, the daemon, an action's own writes) never ask; |
| 8454 | - the refusal is a 403 carrying the rule's `reason`; |
| 8455 | - `actions` may be `[""*""]`; a rule naming neither a collection nor an |
| 8456 | object switches the fallback off for the whole policy; a `row_filter` |
| 8457 | limits it to the rows it names; `valid_from` / `expires_at` work as on |
| 8458 | any rule; |
| 8459 | - naming an `object_id` covers the `u_<id>_...` convention above, except in |
| 8460 | `private` access mode, where object ownership is the access mode itself. |
| 8461 | |
| 8462 | `owner_fallback` on an allow rule does not parse: it would grant nothing |
| 8463 | while reading as if it did. |
| 8464 | |
| 8465 | The packages that ship one, and the collections whose packages are silent |
| 8466 | about whether the owner may update or delete, are both listed in |
| 8467 | `tests/test_owner_fallback_opt_out.py` (`OPTED_OUT`, `UNDECIDED`), which |
| 8468 | fails when a new collection or a narrowed grant leaves an owner's update |
| 8469 | or delete resting on the fallback alone. |
| 8470 | |
| 8471 | ### Who owns a record you create |
| 8472 | |
| 8473 | On `POST /collections/<name>/records`, for a collection whose schema declares |
| 8474 | an `owner_id` field and a caller signed in as a person (a session or one of |
| 8475 | their API keys): |
| 8476 | |
| 8477 | | `owner_id` sent | What happens | |
| 8478 | |---|---| |
| 8479 | | left out, or blank | The caller owns the row: the server fills in their id **before** the permission check, so a rule filtered on `{""owner_id"": ""$user_id""}` judges the row they will actually own. The returned record shows it. | |
| 8480 | | the caller's own id | Kept. | |
| 8481 | | somebody else's id | Kept exactly as sent, and refused with `403 {""code"": ""forbidden"", ""field"": ""owner_id""}` unless the caller holds an admin role or an allow rule with `""on_behalf"": true` covers this create. Nothing is written. | |
| 8482 | |
| 8483 | The server never rewrites an `owner_id` the client sent. It used to: a |
| 8484 | treasurer recording a donation for a donor got `201` and a row the server had |
| 8485 | quietly made the treasurer's own, so the donor never saw it. |
| 8486 | |
| 8487 | `on_behalf` is the grant for staff entering records for members, donors or |
| 8488 | patients: |
| 8489 | |
| 8490 | ```json |
| 8491 | {""effect"": ""allow"", ""principal"": ""role:treasurer"", ""actions"": [""create"", ""read""], |
| 8492 | ""collection"": ""donations"", ""on_behalf"": true, |
| 8493 | ""reason"": ""the treasurer enters donations for donors""} |
| 8494 | ``` |
| 8495 | |
| 8496 | It is deliberately narrow, and a rule outside this shape makes the policy |
| 8497 | invalid rather than granting nothing: an allow, naming a collection, covering |
| 8498 | `create`, for a `role:<name>` or `user:<id>` principal. `registered`, `public`, |
| 8499 | `owner`, `account:` and `subscription:` are refused, because a row owned by |
| 8500 | someone else is theirs to read, change and delete (the owner fallback above), |
| 8501 | and ""any signed-in user may plant rows in anyone's account"" is the forgery |
| 8502 | this check exists to stop. The rule's `row_filter` still has to match the |
| 8503 | record as sent (an on-behalf grant limited to `{""fund"": ""general""}` does not |
| 8504 | cover other funds), and an explicit deny still wins. A create grant without |
| 8505 | `on_behalf` -- even one with no row filter -- lets its principal create rows |
| 8506 | they own, and only those. |
| 8507 | |
| 8508 | The admin token is not a person: seeding, migration and scripts that send an |
| 8509 | `owner_id` keep it. Only `owner_id` is handled this way; `user_id` and |
| 8510 | `created_by` are written as sent and judged by the rules like any other field. |
| 8511 | `tests/test_create_owner_id.py` walks each case through HTTP. |
| 8512 | |
| 8513 | ### Changing who owns a record |
| 8514 | |
| 8515 | On `PUT /collections/<name>/records/<id>` under enforcement, an `owner_id` |
| 8516 | that differs from the stored one is a change of owner, and it needs exactly |
| 8517 | what creating the row with that `owner_id` needs: an admin role, or an allow |
| 8518 | rule with `""on_behalf"": true` covering `create` on the collection whose row |
| 8519 | filter matches the record as it would be. Anything else is |
| 8520 | `403 {""code"": ""forbidden"", ""field"": ""owner_id""}` and nothing is written. |
| 8521 | |
| 8522 | - An `owner_id` sent unchanged is no change: clients that PUT back the whole |
| 8523 | record they read are not refused. |
| 8524 | - Taking a row for yourself, or clearing its owner, is a change of owner too |
| 8525 | (the old owner loses it) and is asked the same way. |
| 8526 | - An owner's own row-filtered grant (`owner_id: $user_id`) already refused |
| 8527 | giving a row away, because the rule is judged on the record as it would |
| 8528 | be. This closes the other door: a role with an unconditional update grant |
| 8529 | (a billing manager on invoices, a manager on expenses and time logs, an |
| 8530 | assignee on a task) could hand any row to any user. |
| 8531 | - The admin token and in-process writers (actions, the daemon) are not |
| 8532 | asked; an action that moves records between owners decides that itself. |
| 8533 | |
| 8534 | ## Sharing |
| 8535 | |
| 8536 | Sharing is just a rule: |
| 8537 | |
| 8538 | ```python |
| 8539 | PermissionRule.allow( |
| 8540 | ""user:99"", |
| 8541 | [""read"", ""update""], |
| 8542 | object_id=""u_42_shared_report"", |
| 8543 | reason=""shared by owner"", |
| 8544 | ) |
| 8545 | ``` |
| 8546 | |
| 8547 | A user object is shared only this way, by `object_id`. An object is |
| 8548 | checked under the collection its name starts with (`tools_export` under |
| 8549 | `tools`), but a user object `u_<id>_<name>` is in no collection's scope: |
| 8550 | an allow rule that names a collection never grants on it, whatever the |
| 8551 | owner called it (`u_42_tools_export` is not opened by a grant on `tools`). |
| 8552 | Deny rules that name the collection still apply to it, as they always did. |
| 8553 | The access mode does not share it either: see |
| 8554 | [Access Modes](#access-modes). |
| 8555 | |
| 8556 | Account sharing uses the same shape: |
| 8557 | |
| 8558 | ```python |
| 8559 | PermissionRule.allow( |
| 8560 | ""account:customer-acme"", |
| 8561 | [""read""], |
| 8562 | collection=""invoices"", |
| 8563 | row_filter={""customer_account_id"": ""$account_id""}, |
| 8564 | ) |
| 8565 | ``` |
| 8566 | |
| 8567 | That covers the common case where a customer has multiple employees and they all |
| 8568 | need access to the customer portal, invoices, files, or support tickets. |
| 8569 | |
| 8570 | Project sharing — ""records I own OR records in a project shared with me"" — |
| 8571 | uses grant records plus one filter value. Grants are rows in the plain |
| 8572 | `project_access` collection (`project_id`, `user_id`), so sharing is data: |
| 8573 | browseable, audited, versioned. Before checks run, the server resolves the |
| 8574 | subject's grants; rules opt in with `$accessible_projects`, which matches |
| 8575 | when the record's field value is any granted project id: |
| 8576 | |
| 8577 | ```python |
| 8578 | PermissionRule.allow( |
| 8579 | ""registered"", |
| 8580 | [""read""], |
| 8581 | collection=""notes"", |
| 8582 | row_filter={""project_id"": ""$accessible_projects""}, |
| 8583 | reason=""notes in shared projects are readable"", |
| 8584 | ) |
| 8585 | ``` |
| 8586 | |
| 8587 | Pair it with an owner rule on the same collection: matching stays |
| 8588 | first-rule-wins at the collection level, but list, single-record, and |
| 8589 | search reads evaluate rules per record, so ""own"" and ""shared"" rules |
| 8590 | combine naturally. The engine itself stays pure — grant resolution is IO |
| 8591 | the server does once per request, and the subject carries the result. |
| 8592 | |
| 8593 | Granting is self-serve through the companion value `$owned_projects`, |
| 8594 | which resolves to the projects whose `owner_id` is the subject. ""Only a |
| 8595 | project's owner may share it"" — a cross-record condition — becomes a |
| 8596 | plain row filter on the grant collection itself: |
| 8597 | |
| 8598 | ```python |
| 8599 | PermissionRule.allow( |
| 8600 | ""registered"", |
| 8601 | [""create"", ""read"", ""delete""], |
| 8602 | collection=""project_access"", |
| 8603 | row_filter={""project_id"": ""$owned_projects""}, |
| 8604 | reason=""project owners share and revoke access to their own projects"", |
| 8605 | ) |
| 8606 | ``` |
| 8607 | |
| 8608 | Creating a grant is creating a record; revoking is deleting it; both are |
| 8609 | audited and appear in the change history like every other write. |
| 8610 | |
| 8611 | Grants carry a `permission` of `read` or `write`. Most rules only need |
| 8612 | membership (`$accessible_projects`), but some need to tell read grants |
| 8613 | apart from write grants — ""only project writers may publish"" — and that |
| 8614 | narrower set is `$writable_projects`, resolved from the same |
| 8615 | `project_access` rows filtered to `permission == ""write""`: |
| 8616 | |
| 8617 | ```python |
| 8618 | PermissionRule.allow( |
| 8619 | ""registered"", |
| 8620 | [""update""], |
| 8621 | collection=""docs"", |
| 8622 | row_filter={""project_id"": ""$writable_projects""}, |
| 8623 | reason=""only writers may edit docs in a shared project"", |
| 8624 | ) |
| 8625 | ``` |
| 8626 | |
| 8627 | It resolves the same way and is available everywhere |
| 8628 | `$accessible_projects` and `$owned_projects` are: row filters and, for |
| 8629 | schema-declared lifecycle fields, transition guards (see the |
| 8630 | `transitions` field key in `docs/schema-forms.md`). |
| 8631 | |
| 8632 | ## Row And Field Rules |
| 8633 | |
| 8634 | Row filters model rules like: |
| 8635 | |
| 8636 | ```text |
| 8637 | sales reps only see their own leads |
| 8638 | ``` |
| 8639 | |
| 8640 | As data: |
| 8641 | |
| 8642 | ```python |
| 8643 | PermissionRule.allow( |
| 8644 | ""role:sales"", |
| 8645 | [""read""], |
| 8646 | collection=""contacts"", |
| 8647 | row_filter={""owner_id"": ""$user_id""}, |
| 8648 | ) |
| 8649 | ``` |
| 8650 | |
| 8651 | A row filter never matches a field the record does not have. A collection's |
| 8652 | file only gains a column once some record is written with it, so ""the record |
| 8653 | has no `owner_id` at all"" is an ordinary state, not a corrupt one, and it is |
| 8654 | treated exactly like the column being present and empty: |
| 8655 | |
| 8656 | | the filter value | field missing or null | field present, empty | field has a value | |
| 8657 | |---|---|---|---| |
| 8658 | | `$user_id` / `$account_id`, resolved | no match | no match | match when equal | |
| 8659 | | `$user_id` / `$account_id`, unresolved (anonymous visitor, user with no account) | no match | no match | no match | |
| 8660 | | `$accessible_projects` and the other set-valued variables | no match | no match | match when a member | |
| 8661 | | a literal value | no match | match only for the literal `""""` | match when equal | |
| 8662 | | a literal `null` | no match | no match | no match | |
| 8663 | |
| 8664 | This is the same answer for an allow rule and for a deny rule: there is one |
| 8665 | comparison, and the effect only decides what a match means. So the account |
| 8666 | example above stays correct if it is generalised from |
| 8667 | `account:customer-acme` to `registered` (""every customer sees their own |
| 8668 | invoices""): a signed-in user with no account matches no invoice, including |
| 8669 | in a collection where no invoice has a `customer_account_id` yet. Before |
| 8670 | this was pinned (tests/test_permission_missing_column.py) an unresolved |
| 8671 | variable compared equal to a missing field and such a rule matched every |
| 8672 | row until the column was first written. |
| 8673 | |
| 8674 | (The set-valued row assumes what the server guarantees: it drops grant rows |
| 8675 | with an empty id before building those sets, so `""""` is never a member.) |
| 8676 | |
| 8677 | The table is about equality and membership. The `ne` operator is not part |
| 8678 | of it and is unchanged: `{""op"": ""ne"", ""value"": X}` is plain inequality with |
| 8679 | a missing field read as null, so a missing field matches `ne` for any real |
| 8680 | `X` and does not match it when `X` is unresolved or null -- while an empty |
| 8681 | field does match `ne` against an unresolved `X`. A rule that depends on |
| 8682 | that corner should say what it means with a second clause. |
| 8683 | |
| 8684 | The ordered operators (`gte`, `lte`, `gt`, `lt`) compare numbers as numbers |
| 8685 | and ISO dates and datetimes as instants in UTC: a trailing `Z` or an offset |
| 8686 | says the zone, a value with no offset is UTC, and a date alone is UTC |
| 8687 | midnight. So `{""created_at"": {""op"": ""lt"", ""value"": ""2026-01-01""}}` compares |
| 8688 | with the `created_at` the server stamps (`...Z`). Before 2026-12-03 a date |
| 8689 | alone was read with no zone, comparing it with a stamped datetime failed, |
| 8690 | and the failure was read as ""no match"": such a deny refused nothing and |
| 8691 | such an allow granted nothing. |
| 8692 | |
| 8693 | An ordered condition can also be impossible to judge: the record has no |
| 8694 | such field, the bound is a `$`-variable with no value (or a set), or the |
| 8695 | bound is a number or a date and the stored value is blank or text. That is |
| 8696 | the one place the effect changes the answer: |
| 8697 | |
| 8698 | | rule | cannot judge | |
| 8699 | |---|---| |
| 8700 | | allow (and attention counts, list filters) | no match: grants nothing | |
| 8701 | | deny (and the `owner_fallback` opt-out) | the deny holds: refused | |
| 8702 | |
| 8703 | A deny's other conditions still decide, since a filter's conditions are |
| 8704 | ANDed: a deny that names a status or an owner still spares a row with |
| 8705 | another one. A deny that should spare blank rows says so beside its bound: |
| 8706 | `{""approved_at"": [{""op"": ""lt"", ""value"": ""2026-01-01""}, {""op"": ""ne"", ""value"": """"}]}`. |
| 8707 | A bound that is plain text (neither a number nor a date) is compared as |
| 8708 | text and can always be judged. |
| 8709 | |
| 8710 | Field rules model cases like hiding salary, internal notes, cost, or private |
| 8711 | metadata: |
| 8712 | |
| 8713 | ```python |
| 8714 | PermissionRule.allow( |
| 8715 | ""account:customer-acme"", |
| 8716 | [""read""], |
| 8717 | collection=""invoices"", |
| 8718 | fields=[""invoice_id"", ""status"", ""total""], |
| 8719 | denied_fields=[""internal_notes""], |
| 8720 | ) |
| 8721 | ``` |
| 8722 | |
| 8723 | Schema field permissions add the generated-form version of the same idea. They |
| 8724 | live next to field metadata so Scroll can render the right controls and the |
| 8725 | server can enforce the same decision: |
| 8726 | |
| 8727 | ```json |
| 8728 | { |
| 8729 | ""name"": ""margin"", |
| 8730 | ""type"": ""currency"", |
| 8731 | ""permissions"": { |
| 8732 | ""admin"": ""edit"", |
| 8733 | ""sales"": ""hidden"", |
| 8734 | ""viewer"": ""hidden"" |
| 8735 | } |
| 8736 | } |
| 8737 | ``` |
| 8738 | |
| 8739 | The access levels are: |
| 8740 | |
| 8741 | - `edit` - visible and writable |
| 8742 | - `read` - visible but not writable |
| 8743 | - `hidden` - removed from reads and not writable |
| 8744 | |
| 8745 | Principal keys can be role names such as `sales`, or full principals such as |
| 8746 | `role:sales`, `user:42`, `account:customer-acme`, `subscription:pro`, |
| 8747 | `registered`, `public`, or `owner`. Grouped access lists are also accepted: |
| 8748 | |
| 8749 | ```json |
| 8750 | { |
| 8751 | ""name"": ""notes"", |
| 8752 | ""permissions"": { |
| 8753 | ""edit"": [""owner"", ""role:admin""], |
| 8754 | ""read"": [""role:support""], |
| 8755 | ""default"": ""hidden"" |
| 8756 | } |
| 8757 | } |
| 8758 | ``` |
| 8759 | |
| 8760 | When multiple principals match one subject, the most restrictive field access |
| 8761 | wins. Schema field permissions only refine fields after the broader policy has |
| 8762 | already allowed access to the row. |
| 8763 | |
| 8764 | ### Field permissions on writes: what is checked, and the known limits |
| 8765 | |
| 8766 | **Known limits, pending the owner's rule-combining design.** This is what the |
| 8767 | engine does today, pinned by `tests/test_field_permission_semantics.py`; do |
| 8768 | not build on the corners below as if they were promises, and expect them to |
| 8769 | change together with that design. |
| 8770 | |
| 8771 | - **Only the keys a write submits are checked.** A `PUT` that sends `title` |
| 8772 | is not stopped by a field it did not send, however restricted that field |
| 8773 | is. A key that is sent is checked even when its value is unchanged or |
| 8774 | blank (`{""secret"": """"}` is refused where the field is `read`). |
| 8775 | - **Create is checked too**, against the keys of the new record, with |
| 8776 | `owner` evaluated on the record being created. The refusal is `403` with |
| 8777 | `""code"": ""forbidden""` and `""denied_fields"": [...]`; nothing is written. |
| 8778 | - **The most restrictive access across ALL of a subject's matching |
| 8779 | principals wins, in either direction.** A field set `{""owner"": ""edit"", |
| 8780 | ""role:auditor"": ""read""}` is read-only for a person who is both the row's |
| 8781 | owner and an auditor: holding the extra role takes edit rights away. There |
| 8782 | is no ""most specific wins"" and no way to say ""owner overrides role"". Give |
| 8783 | a person who must edit their own rows a role set that does not also appear |
| 8784 | in the field's restricted list, or restrict by `default` and list who may |
| 8785 | edit. |
| 8786 | - **An allow rule's `fields` and `denied_fields` apply to reads only.** They |
| 8787 | remove keys from what a read returns (and from what can be filtered on); |
| 8788 | they do not stop a write that sends those keys. The answer to a create, |
| 8789 | update or delete is the row as the writer's own `GET` shows it, so it |
| 8790 | leaves those keys out too (docs/http-api-contract.md, ""Write answers""). |
| 8791 | To stop writes to a field, use the field's schema `permissions`. |
| 8792 | - **Transition guards cannot reference roles.** A guarded move's `when` is |
| 8793 | the row-filter language over the record's current values with the closed |
| 8794 | set of subject variables (`$user_id`, `$account_id`, and the project and |
| 8795 | shared-record sets). Each `when` value is a single string, a literal or |
| 8796 | one of those variables, compared for equality: no `ne`, `in` or other |
| 8797 | operators, so a guard cannot say ""not your own row"". To let only a role |
| 8798 | make a move, put the move behind a field permission on the field it |
| 8799 | changes, or a pre-write hook that gets the caller. |
| 8800 | |
| 8801 | ### Notifications, activity feeds and history lines |
| 8802 | |
| 8803 | With enforcement on (`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT`, the mode |
| 8804 | `/permissions/status` calls ""enforced""; the daemon reads the same setting |
| 8805 | through `object_access.enforcement_enabled`), anything shown to a user that |
| 8806 | is built from a change to a record follows the same read decision as the |
| 8807 | record, for that user, on that row, at the moment it is built. With |
| 8808 | enforcement off or audit-only the record API serves that user every row and |
| 8809 | field, so notifications and history lines are delivered whole, exactly as |
| 8810 | before; if the mode cannot be determined, notifications are not delivered. Fields a rule's `fields` / `denied_fields` or the |
| 8811 | schema's field `permissions` hide from them are left out, and a change that |
| 8812 | touched only such fields produces nothing for them. |
| 8813 | |
| 8814 | - **Notify rules** (`app-notify`, in-app and email), with enforcement on. A recipient gets a |
| 8815 | notification only if they are an active user who may read the row; its |
| 8816 | text is rendered from the row as that user may read it, so a template's |
| 8817 | `{salary_band}` renders empty for someone who cannot read it. A rule whose |
| 8818 | `match` names a field the recipient cannot read does not fire for them |
| 8819 | (firing would tell them the value). An update none of whose changed fields |
| 8820 | they can read notifies them of nothing. An unknown recipient id, an |
| 8821 | inactive user, or an unreadable policy delivers nothing. The check is made |
| 8822 | when the daemon processes the change, not when the rule is written. |
| 8823 | - **Declared attention counts** (a package's `attention` entry with |
| 8824 | `collection` + `where`, shown on the home page and the menu), with |
| 8825 | enforcement on. The count, and the sums, ages and sub-counts of its |
| 8826 | detail sentence, are computed from each row as the viewer may read it. A |
| 8827 | row they may not read is not counted. A `where` condition on a field they |
| 8828 | cannot read is false for that row, so the count means ""rows where this |
| 8829 | field, which you can see, matches"" and is `0` for someone who cannot read |
| 8830 | the field at all. A sum or age adds nothing from a row whose field is |
| 8831 | hidden, and a detail part that depends on a field hidden in every counted |
| 8832 | row is left out of the sentence, zero or not. With enforcement off the |
| 8833 | counts are row-level, as before; if the mode cannot be determined nothing |
| 8834 | is counted. Counts are computed on each page view, so there is no stored |
| 8835 | number to go stale. A code provider's number (`object_id`) is not |
| 8836 | per-viewer: it is shown only to a viewer who reads every row of each |
| 8837 | collection in its `reads`, and, with enforcement on, from whom no schema |
| 8838 | field permission of those collections could hide a field |
| 8839 | ([package-authoring.md](/docs/package-authoring#who-sees-a-providers-number)). |
| 8840 | - **`GET /api/activity`** (a user's own recent changes): with enforcement on, |
| 8841 | an entry's title comes from the fields the caller may read; a row they may |
| 8842 | not read is titled by its id. |
| 8843 | - **`action_counter_history`**: before/after snapshots and `changed_fields` |
| 8844 | carry only the fields the caller may read. |
| 8845 | - **Realtime (`/ws`)** sends only collection, id and action, after a read |
| 8846 | check on the row. It does not look at which fields changed: a reader of a |
| 8847 | row is told the row changed even when only a field they cannot read did, |
| 8848 | exactly as the row's `rev` tells them on the next read. That the row |
| 8849 | changed is treated as visible to anyone who can read the row; which field, |
| 8850 | and to what, never is. |
| 8851 | - **Admin routes** (`/collections/{c}/changes`, `/admin/changes`, the event |
| 8852 | log, subscriptions) are admin-token only and show everything, including |
| 8853 | `changed_fields`. |
| 8854 | |
| 8855 | Known limits: a notification already stored in `notifications` was rendered |
| 8856 | for its recipient when it was written; if their access to the row or field |
| 8857 | is narrowed afterwards, the stored text stays as it was. Nothing re-renders |
| 8858 | or purges stored notifications on a permission change. |
| 8859 | |
| 8860 | ### Comment moderation |
| 8861 | |
| 8862 | Both comment collections are moderated by one role, `moderator`, and |
| 8863 | nobody else: app-thread's `thread_comments` (statuses `published`, |
| 8864 | `pending`, `flagged`, `removed`) and app-worker's guestbook |
| 8865 | `profile_comments` (`pending`, `approved`, `rejected`). The admin token is |
| 8866 | not a moderator. It is built from the pieces above, and the limits above |
| 8867 | are why it has the shape it has: |
| 8868 | |
| 8869 | - **A rule lets a moderator reach every comment.** Each package ships |
| 8870 | `role:moderator` `read` (pending, flagged, removed and rejected rows |
| 8871 | included: the pending ones are the queue) and `update`, with no row |
| 8872 | filter. No `delete`: a moderated comment is removed or rejected by its |
| 8873 | status, not erased. |
| 8874 | - **Field permissions make `status` the only thing that update can |
| 8875 | change.** An allow rule's `fields` do not restrict writes, so the other |
| 8876 | client-writable fields (the text, the author's name and URL, the thread |
| 8877 | or profile a comment hangs off, the reply target, `owner_id` on the |
| 8878 | guestbook) say `{""owner"": ""edit"", ""role:admin"": ""edit"", |
| 8879 | ""role:superuser"": ""edit"", ""default"": ""read""}`: the comment's author and |
| 8880 | admins edit them, everyone else (moderators included) reads them. A |
| 8881 | moderator's `PUT` that sends any of them is `403` with `denied_fields`, |
| 8882 | and nothing is written, status included. A change of owner is refused |
| 8883 | before that anyway (""Changing who owns a record""). Server-owned fields |
| 8884 | (`created_at`, `edited_at`) were never writable by a client. |
| 8885 | - **`status` says `{""owner"": ""read"", ""role:moderator"": ""edit"", ""default"": |
| 8886 | ""hidden""}`.** The author reads their own comment's status and cannot set |
| 8887 | it; a moderator edits it on other people's comments; on a moderator's own |
| 8888 | comment both entries match and the more restrictive, `read`, wins, so |
| 8889 | **nobody approves their own comment**. Everyone else (other users, |
| 8890 | visitors, the admin token) does not see the field at all; the read rules |
| 8891 | give them only published or approved rows. |
| 8892 | - **The moves are the schema's `transitions` map**, unguarded: |
| 8893 | `thread_comments` pending to published (approve), flagged or removed |
| 8894 | (reject); published to flagged or removed; flagged to published or |
| 8895 | removed; removed is final. `profile_comments` pending to approved or |
| 8896 | rejected; approved to rejected (un-approving); rejected is final. Nothing |
| 8897 | moves back to pending. Any other move is `400`. |
| 8898 | - **Moderators have a queue on the home page**: the declared attention |
| 8899 | counts `thread_comments_to_moderate` and `profile_comments_to_moderate` |
| 8900 | count other people's pending comments the viewer may read, so they are |
| 8901 | zero for everyone who is not a moderator (or an admin, who reads every |
| 8902 | row). Each count opens a seeded page listing the pending comments |
| 8903 | oldest first, `/comments/pending` and `/guestbook/pending` (app-views |
| 8904 | list views; site routes must be on, `DBBASIC_ENABLE_SITE_ROUTES=true`). |
| 8905 | The page lists, it does not decide: a decision is a `PUT` of `status` |
| 8906 | over the record API. It also lists the moderator's own pending comments, |
| 8907 | which the count leaves out (a list's `where` cannot say ""not mine""); to |
| 8908 | anyone who may not filter on `status` (authors, other users, visitors) |
| 8909 | it says ""Not available"". The same queue over the API is |
| 8910 | `GET /collections/<collection>/records?status=pending`. |
| 8911 | |
| 8912 | What changes for whom, against app-thread 0.1.1 and app-worker 0.1.2: |
| 8913 | |
| 8914 | | Caller | Before | After | |
| 8915 | |---|---|---| |
| 8916 | | the author | reads their comment and its status in any state; edits its text; cannot set status | the same | |
| 8917 | | a moderator, someone else's comment | thread: reads it, status included, cannot update it. Guestbook: approved rows only (with their status), cannot update | reads it in any state with its status; moves status along the map; cannot change any other field or delete it | |
| 8918 | | a moderator, their own comment | reads it, edits its text, cannot set status | the same | |
| 8919 | | another signed-in user | thread: published rows; guestbook: approved rows; no status, cannot update | the same | |
| 8920 | | a visitor | thread: nothing; guestbook: approved rows, no status | the same | |
| 8921 | | the admin token | reads every row, status hidden; edits the text; cannot set status | the same | |
| 8922 | | anyone else an operator's own rule lets update other people's comments (a role other than `moderator`, `admin`, `superuser`; also a custom name in the policy's `admin_roles`) | could change any field | can change none of the fields above (they are `read` for it) | |
| 8923 | |
| 8924 | On upgrade, reinstall both packages (`POST /packages/app-thread/install` |
| 8925 | and `/packages/app-worker/install` with `{""allow_replace"": true}`): the |
| 8926 | moderator rules are added and nothing is retracted. Then give the role to |
| 8927 | whoever moderates, `PUT /identity/users/{user_id}/roles` with |
| 8928 | `{""roles"": [..., ""moderator""]}` (it takes effect on their next request). |
| 8929 | The guestbook's commenters' rule keeps its old `reason` text on an upgraded |
| 8930 | box, because an upgrade matches rules on everything but `reason`; edit it |
| 8931 | in the policy if the stale wording bothers you. |
| 8932 | |
| 8933 | **An AI agent that moderates is a user with the moderator role and an API |
| 8934 | key, not the admin token.** Create a user for it (`POST /identity/users` |
| 8935 | with `""roles"": [""moderator""]`), mint it a key (`POST |
| 8936 | /identity/users/{user_id}/api-keys`), and give the agent that key. It then |
| 8937 | works the queue exactly as a person would (`GET ...?status=pending`, `PUT |
| 8938 | {""status"": ""approved""}`), can do nothing else a moderator cannot, is recorded |
| 8939 | under its own user id in the change history, and is switched off by revoking the key |
| 8940 | or the role. The admin token would be the wrong credential twice over: it |
| 8941 | reaches every collection on the box, and it cannot moderate at all |
| 8942 | (`status` does not name it). |
| 8943 | |
| 8944 | ## Subscription And Temporary Access |
| 8945 | |
| 8946 | Subscriptions can be broad: |
| 8947 | |
| 8948 | ```python |
| 8949 | PermissionPolicy(access_mode=""subscription"") |
| 8950 | ``` |
| 8951 | |
| 8952 | Or plan-specific: |
| 8953 | |
| 8954 | ```python |
| 8955 | PermissionRule.allow( |
| 8956 | ""subscription:pro"", |
| 8957 | [""read""], |
| 8958 | collection=""premium_reports"", |
| 8959 | ) |
| 8960 | ``` |
| 8961 | |
| 8962 | Temporary pay-per-view style access is a time-boxed grant: |
| 8963 | |
| 8964 | ```python |
| 8965 | PermissionRule.allow( |
| 8966 | ""user:42"", |
| 8967 | [""read""], |
| 8968 | object_id=""reports_market_snapshot"", |
| 8969 | valid_from=""2026-06-01T00:00:00Z"", |
| 8970 | expires_at=""2026-07-01T00:00:00Z"", |
| 8971 | ) |
| 8972 | ``` |
| 8973 | |
| 8974 | If access should be consumed after one or more views, that should be tracked by |
| 8975 | an entitlement or ledger object. The permission rule says access is possible; |
| 8976 | the ledger object records purchases, consumption, refunds, and audit history. |
| 8977 | |
| 8978 | For HTTP APIs, missing or expired paid entitlement should map to: |
| 8979 | |
| 8980 | ```text |
| 8981 | 402 Payment Required |
| 8982 | ``` |
| 8983 | |
| 8984 | That is different from: |
| 8985 | |
| 8986 | - `401 Unauthorized` - the server does not know who the user is yet. |
| 8987 | - `403 Forbidden` - the server knows the user, but the user is not allowed. |
| 8988 | - `402 Payment Required` - the user may be allowed after subscription, |
| 8989 | purchase, credit, or another payment entitlement. |
| 8990 | |
| 8991 | ## Scroll Contract |
| 8992 | |
| 8993 | Scroll should eventually call a server endpoint that exposes the same decision |
| 8994 | shape: |
| 8995 | |
| 8996 | ```json |
| 8997 | { |
| 8998 | ""allowed"": true, |
| 8999 | ""reason"": ""sales reps only see own contacts"", |
| 9000 | ""code"": ""allowed"", |
| 9001 | ""http_status"": 200, |
| 9002 | ""row_filter"": {""owner_id"": ""$user_id""}, |
| 9003 | ""fields"": null, |
| 9004 | ""denied_fields"": [] |
| 9005 | } |
| 9006 | ``` |
| 9007 | |
| 9008 | That lets Scroll show permission previews, generated matrices, ""test as role"", |
| 9009 | and AI-generated rules without becoming the authority. |
| 9010 | " |
| 9011 | secrets-and-credentials Secrets, Credentials, and the Trust Boundary Security & Limits 610 Where secrets live in DBBASIC, why a secret is never a record field, and the honest threat model behind the write-only identity vault. "This is the doctrine for **where secrets live** in DBBASIC and why. It matters |
| 9012 | to anyone writing a package that touches a credential — a user's third-party |
| 9013 | API key, an outbound-mail relay password, an email-hosting mailbox password, a |
| 9014 | signing token. Get this wrong and a secret ends up in a record collection, |
| 9015 | which means it ends up in an export, a backup, or an API read. Get it right and |
| 9016 | secrets stay in one place, with one honest boundary, that every other part of |
| 9017 | the system already trusts. |
| 9018 | |
| 9019 | The one-line rule: **a secret is never a record field.** Records are readable, |
| 9020 | listable, exportable, and included in portable backups by design. A secret must |
| 9021 | be none of those things. So secrets go somewhere else, through a different door. |
| 9022 | |
| 9023 | ## Where secrets live |
| 9024 | |
| 9025 | There are exactly two homes, by lifetime and ownership: |
| 9026 | |
| 9027 | ### 1. Deploy-time, server-wide secrets → the environment file |
| 9028 | |
| 9029 | A credential the *whole deployment* shares — the SMTP relay password |
| 9030 | (`DBBASIC_SMTP_PASSWORD`), a connector's API key (`DBBASIC_MAILCOW_API_KEY`), |
| 9031 | the admin token (`DBBASIC_ADMIN_TOKEN`) — lives in |
| 9032 | `/etc/dbbasic-object-server.env`, `640 root:dbbasic` (see |
| 9033 | [`single-vm-deployment.md`](/docs/single-vm-deployment)). It is set by the operator, read by the server |
| 9034 | process, and never appears in a schema field, a record, an API response, or a |
| 9035 | backup archive. A package that needs one **declares the env var name in its |
| 9036 | docs and reads it at runtime** — it never ships the value and never stores it. |
| 9037 | |
| 9038 | ### 1a. The box's exchange signing key → a file the server makes |
| 9039 | |
| 9040 | Box-to-box exchange (`box-to-box-exchange.md`) signs |
| 9041 | with an Ed25519 private key the server generates itself, so it cannot come |
| 9042 | from the environment file. It is written once to |
| 9043 | `<data dir>/exchange/private/<hex>.key`, mode 0600 in a 0700 directory, with |
| 9044 | O_EXCL so it is never briefly readable by others. It is never a record, never |
| 9045 | served (only its public half is, in `/.well-known/dbbasic`), never logged, |
| 9046 | and never in a runtime backup: that directory is outside every directory a |
| 9047 | backup copies, and `tests/test_exchange_core.py` opens a real archive to |
| 9048 | check. Back it up yourself, with the other deployment secrets. A rotated |
| 9049 | key's file is deleted. |
| 9050 | |
| 9051 | ### 1b. The record revision key → a file the server makes |
| 9052 | |
| 9053 | The `_rev` a client is given for a record is an HMAC keyed with 32 random |
| 9054 | bytes the server writes on first use to `<data dir>/record_rev/secret.key`, |
| 9055 | mode 0600 in a 0700 directory (written under a temporary name and linked |
| 9056 | into place, so workers racing to make it all read the same one). Every |
| 9057 | worker on the data dir reads that file; it is never served, logged, or in a |
| 9058 | runtime backup. Losing it only means every `_rev` changes once (each held |
| 9059 | `If-Match` gets one `409`); copy it with the other deployment secrets to |
| 9060 | keep revs across a move to a new box. A damaged file is refused, not |
| 9061 | replaced: delete it and restart. See ""Optimistic Concurrency"" in |
| 9062 | [`http-api-contract.md`](/docs/http-api-contract). |
| 9063 | |
| 9064 | ### 2. Per-user recoverable secrets → the identity vault |
| 9065 | |
| 9066 | A secret that belongs to *one user* and must be *recoverable to be used* (a BYO |
| 9067 | API key the server calls a provider with; a mailbox password handed to the mail |
| 9068 | server) lives in the **write-only identity vault**, `object_service_keys` |
| 9069 | (`identity/service_keys.tsv`). Its contract: |
| 9070 | |
| 9071 | - **Owner-only file**, `0600`, next to `credentials.tsv` — same filesystem |
| 9072 | trust boundary as the admin token. |
| 9073 | - **Write-only**: a caller can *set* a key, *list which services have one*, and |
| 9074 | *delete* one. **No surface ever reads key material back** — not the HTTP API, |
| 9075 | not the shell, not an agent, not a package. The server uses a stored key |
| 9076 | internally (to call the provider) so it never travels to a browser. |
| 9077 | - **Stored as-provided, not encrypted, not hashed.** Passwords are hashed |
| 9078 | because they only need to be *verified*; these must be *used*, so they must be |
| 9079 | recoverable. On-record encryption with a key derived from a server secret |
| 9080 | (the pattern many frameworks reach for) is *theater* here — the ciphertext and |
| 9081 | the key it's decrypted with live in the same blast radius, so they leak |
| 9082 | together (see the Trust Boundary section). The real protection is the `0600` |
| 9083 | file and the write-only contract, not a cipher. |
| 9084 | - **Excluded from portable backups and source control** — so a leaked backup |
| 9085 | archive, the most common accidental exposure, contains no secret material. |
| 9086 | (See [`backup-restore.md`](/docs/backup-restore); a package must never undo this by copying a secret |
| 9087 | into a record it *does* back up.) |
| 9088 | |
| 9089 | **Concrete example**: the AI chat, cloud TTS, and cloud STT features |
| 9090 | (`docs/shell-and-ai.md`) all read from this vault, not the env file — a |
| 9091 | user's own `anthropic` and/or `openai` key, set via `PUT |
| 9092 | /identity/users/{you}/service-keys`. One stored `openai` key covers chat, |
| 9093 | `POST /api/tts` with `engine: ""openai""`, and `POST /api/stt` — no separate |
| 9094 | signup per feature. This is also why those features are per-user opt-in |
| 9095 | rather than deployment-wide: `DBBASIC_ENABLE_AI_CHAT`/`_TTS`/`_STT` in the |
| 9096 | env file only unlock the *capability*; each user still needs their own |
| 9097 | stored key before any of it does anything for them. |
| 9098 | |
| 9099 | A second example with one entry per record: mail sync (`app-mail-sync`) |
| 9100 | keeps each IMAP account's password as `imap-<account id>`, resolved by the |
| 9101 | **account row's** `owner_id`. The account record has no password field, |
| 9102 | and its page shows only whether the entry is set. |
| 9103 | |
| 9104 | ## How a secret gets written (it is not a record write) |
| 9105 | |
| 9106 | The vault has its own door, deliberately separate from the generic record API: |
| 9107 | |
| 9108 | ``` |
| 9109 | GET /identity/users/{user_id}/service-keys → which services are set (status only) |
| 9110 | PUT /identity/users/{user_id}/service-keys → { ""service"": ""..."", ""key"": ""..."" } |
| 9111 | DELETE /identity/users/{user_id}/service-keys/{service} → clear one |
| 9112 | ``` |
| 9113 | |
| 9114 | - **Owner-scoped**: only the account owner's own session may write their vault |
| 9115 | (or the operator admin gate). Identity is resolved server-side from an opaque |
| 9116 | session token — it cannot be spoofed by a client-supplied user id. |
| 9117 | - **CSRF-guarded**: cross-origin cookie writes are refused. |
| 9118 | - **Never echoes material**: `PUT` returns metadata (`service`, timestamps) |
| 9119 | only; `GET` returns presence only. |
| 9120 | |
| 9121 | `POST /collections/{c}/records` — the generic record write — **cannot reach the |
| 9122 | vault at all.** That is the point: there is no record surface to misconfigure |
| 9123 | into leaking a secret. |
| 9124 | |
| 9125 | **In a generated UI**, a secret is a *write-only field*: it renders as ""set / |
| 9126 | not set"" with an input that only ever POSTs to the vault endpoint above and |
| 9127 | never displays a stored value. The form still looks uniform to the user — one |
| 9128 | field just writes to a different door than the record. |
| 9129 | |
| 9130 | ## Reserved namespaces: user-writable vs platform-owned |
| 9131 | |
| 9132 | A vault entry is keyed by a **service name**. Two kinds: |
| 9133 | |
| 9134 | - **User-writable** (a person's own BYO credential): a plain name — `openai`, |
| 9135 | `anthropic`, `stripe`. The self-service endpoint above writes these. |
| 9136 | - **Platform-owned** (a secret the *platform* provisions on the user's behalf — |
| 9137 | a generated mailbox password): a **reserved name**, prefixed `sys-` |
| 9138 | (e.g. `sys-mailbox-<mailbox_id>`). **The self-service HTTP endpoint refuses to |
| 9139 | write or delete a reserved name.** Only in-process server code (a connector, a |
| 9140 | provisioning verb) may set one. |
| 9141 | |
| 9142 | This is the control that stops a user from **overwriting a secret the platform |
| 9143 | owns**. Without it, a user could `PUT` their own `sys-mailbox-<id>` and clobber |
| 9144 | the password the mail server actually uses. `object_service_keys.is_reserved_service()` |
| 9145 | is the single source of truth for the rule; the HTTP handler enforces it. |
| 9146 | |
| 9147 | Two more rules for platform-owned secrets a package must follow: |
| 9148 | |
| 9149 | - **Scope every read by the record's owner**, never by caller input. Resolve a |
| 9150 | mailbox's secret from *the mailbox record's `owner_id`* — never from a |
| 9151 | `mailbox_id` a request supplied — or a user could plant an entry in their own |
| 9152 | vault and hope a global lookup reads it. |
| 9153 | - **Generate, don't collect, when you can.** A provisioned password should be |
| 9154 | generated server-side (`secrets.token_urlsafe`), stored in the vault, and |
| 9155 | revealed to the user *exactly once* in the provisioning response — never read |
| 9156 | back afterward. |
| 9157 | |
| 9158 | ## The trust boundary (threat model) |
| 9159 | |
| 9160 | Be honest about what actually protects the vault, because it changes what's |
| 9161 | worth building. A secret is reachable only by one of these, and **every one of |
| 9162 | them also compromises the entire system** — so the vault is not a weaker link, |
| 9163 | it inherits the system's security: |
| 9164 | |
| 9165 | | Vector | What it takes | Does encryption-at-rest help? | |
| 9166 | |---|---|---| |
| 9167 | | **A logged-in user** reaching another user's secret | Impossible via the API: owner-scoped, server-derived identity, reserved-namespace guard | N/A — blocked at the app layer | |
| 9168 | | **Code execution as the service user** | An RCE in the server, or an installed package/connector (both run as the service user and legitimately read the vault) | **No** — the running process holds the key too | |
| 9169 | | **Root on the host** | Kernel/sudo/other-service exploit; `0600` is nothing to root | **No** — same blast radius | |
| 9170 | | **The raw disk** | A VM snapshot, an attached volume, a stolen *unencrypted* backup | **Only here** — and only if the key lives off-box (a KMS) | |
| 9171 | | **The deploy path** | A dev-box SSH key or a push-to-prod pipeline → arbitrary code as the service user | **No** — it's code execution with a login | |
| 9172 | |
| 9173 | Conclusions that follow: |
| 9174 | |
| 9175 | - **A plain user cannot reach it.** They are boxed into their own namespace by a |
| 9176 | server-resolved identity and the reserved-namespace guard. |
| 9177 | - **On-box encryption of the vault is theater** against every vector except a |
| 9178 | raw-disk/snapshot theft — because for all the others the decryption key rides |
| 9179 | in the same boundary. The genuinely stronger option is **envelope encryption |
| 9180 | with a KMS-held root key**, and only when you have a KMS (not on a single VM). |
| 9181 | Until then, the higher-leverage move is to **encrypt backups/snapshots with an |
| 9182 | off-box key and lock the hosting account with 2FA** — the deploy credential |
| 9183 | and the hosting account are, in effect, vault keys. |
| 9184 | - **""Installed package = code execution as the service user""** is a stated trust |
| 9185 | fact, which is why package installs (and any dynamically loaded connector |
| 9186 | code) are admin-gated. Fine while packages are first-party; it needs a |
| 9187 | stronger answer before any third-party marketplace. |
| 9188 | |
| 9189 | ## Checklist for package authors |
| 9190 | |
| 9191 | - [ ] **Never** put a secret in a schema field or a record. |
| 9192 | - [ ] Server-wide credential → read from a documented `DBBASIC_*` env var; never ship or store the value. |
| 9193 | - [ ] Per-user recoverable secret → the identity vault (`object_service_keys`), write-only. |
| 9194 | - [ ] Platform-provisioned secret → a `sys-`-prefixed reserved service name; write it only from server-side code. |
| 9195 | - [ ] Resolve a secret by the owning record's `owner_id`, never by caller-supplied input. |
| 9196 | - [ ] Prefer generating a secret and revealing it once over collecting and storing it. |
| 9197 | - [ ] In a UI, a secret field is write-only (set/not-set), posting to the vault endpoint, never rendering the value. |
| 9198 | - [ ] Never copy a secret into anything that lands in a backup or an export. |
| 9199 | |
| 9200 | ## See also |
| 9201 | |
| 9202 | - [`single-vm-deployment.md`](/docs/single-vm-deployment) — the env-file trust boundary and admin-route posture. |
| 9203 | - [`permissions-model.md`](/docs/permissions-model) — owner-scoping and the admin bypass. |
| 9204 | - [`backup-restore.md`](/docs/backup-restore) — what is and isn't in a portable backup. |
| 9205 | - [`package-authoring.md`](/docs/package-authoring) — how a package ships schemas, permissions, and (soon) connectors. |
| 9206 | " |
| 9207 | traffic-limits Traffic Limits Security & Limits 620 How the DBBASIC Object Server rejects oversized, overloaded, or runaway traffic before object code runs, and the env vars that control each limit. "DBBASIC should reject bad or oversized traffic before object code runs. The |
| 9208 | runtime keeps the object loop fast by failing early when a request is too large |
| 9209 | or when the server is under pressure. |
| 9210 | |
| 9211 | ## Request Body Size |
| 9212 | |
| 9213 | The ASGI server enforces a request body cap: |
| 9214 | |
| 9215 | ```text |
| 9216 | DBBASIC_MAX_REQUEST_BYTES=1048576 |
| 9217 | ``` |
| 9218 | |
| 9219 | The default is `1048576` bytes, or 1 MiB. If a request body is larger than the |
| 9220 | configured value, the server returns: |
| 9221 | |
| 9222 | ```http |
| 9223 | 413 Payload Too Large |
| 9224 | ``` |
| 9225 | |
| 9226 | ```json |
| 9227 | { |
| 9228 | ""status"": ""error"", |
| 9229 | ""error"": ""Request body too large"", |
| 9230 | ""max_bytes"": 1048576 |
| 9231 | } |
| 9232 | ``` |
| 9233 | |
| 9234 | This applies before JSON parsing and before object execution. It checks |
| 9235 | `Content-Length` when present and also counts streamed ASGI body chunks. |
| 9236 | |
| 9237 | Large file upload paths should get their own file API and their own explicit |
| 9238 | limits. Normal object `POST`, `PUT`, and `DELETE` requests should stay small. |
| 9239 | |
| 9240 | ## Concurrency |
| 9241 | |
| 9242 | The ASGI server also enforces per-process concurrency caps: |
| 9243 | |
| 9244 | ```text |
| 9245 | DBBASIC_MAX_CONCURRENT_REQUESTS=64 |
| 9246 | DBBASIC_MAX_CONCURRENT_EXECUTIONS=8 |
| 9247 | ``` |
| 9248 | |
| 9249 | `DBBASIC_MAX_CONCURRENT_REQUESTS` limits non-health HTTP requests that are in |
| 9250 | flight inside one server process. `/health` bypasses this limit so a monitor can |
| 9251 | still check whether the process is alive under load. |
| 9252 | |
| 9253 | `DBBASIC_MAX_CONCURRENT_EXECUTIONS` limits object method executions inside one |
| 9254 | server process. Introspection routes, health checks, and other non-execution |
| 9255 | requests do not consume object execution slots. |
| 9256 | |
| 9257 | When either limit is full, the server returns: |
| 9258 | |
| 9259 | ```http |
| 9260 | 503 Service Unavailable |
| 9261 | ``` |
| 9262 | |
| 9263 | ```json |
| 9264 | { |
| 9265 | ""status"": ""error"", |
| 9266 | ""error"": ""Server is busy"", |
| 9267 | ""limit"": ""object_executions"", |
| 9268 | ""max_concurrent"": 8 |
| 9269 | } |
| 9270 | ``` |
| 9271 | |
| 9272 | A third cap protects customers from each other: a user's objects |
| 9273 | (`u_<id>_*`) may run at most `DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER=3` |
| 9274 | at once, and the next request is `429` with `Retry-After` for that user only, |
| 9275 | so one customer's slow requests cannot fill the shared pool. The operator and |
| 9276 | system objects are not capped per user. |
| 9277 | |
| 9278 | Set either concurrency value to `0` to disable that app-level limit for local |
| 9279 | experiments. Production and staging deployments should keep explicit limits. |
| 9280 | |
| 9281 | These caps are per process. If uvicorn runs multiple workers, each worker has |
| 9282 | its own counters. A reverse proxy or process manager still controls the total |
| 9283 | machine-level shape. |
| 9284 | |
| 9285 | ## Rate Limits |
| 9286 | |
| 9287 | Rate limiting is opt-in: |
| 9288 | |
| 9289 | ```text |
| 9290 | DBBASIC_RATE_LIMIT_REQUESTS=1000 |
| 9291 | DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60 |
| 9292 | ``` |
| 9293 | |
| 9294 | The default `DBBASIC_RATE_LIMIT_REQUESTS=0` leaves the app-level limiter |
| 9295 | disabled for local development. Public staging and production deployments should |
| 9296 | set an explicit value. |
| 9297 | |
| 9298 | When enabled, the server checks the rate limit before reading the request body |
| 9299 | or running object code. Plain `GET /health` is excluded so external monitoring |
| 9300 | can still tell whether the process is alive. Detailed health via |
| 9301 | `capacity=true` or `metrics=true` is rate-limited and still requires the admin |
| 9302 | token. |
| 9303 | |
| 9304 | The limiter stores one timestamp bucket per identity under: |
| 9305 | |
| 9306 | ```text |
| 9307 | data/ratelimit/ |
| 9308 | ``` |
| 9309 | |
| 9310 | Those files are runtime guardrails, not application data. Backups exclude them. |
| 9311 | |
| 9312 | Valid admin-token requests use a token bucket. Other requests use the client IP. |
| 9313 | By default the server ignores `X-Forwarded-For` and `X-Real-IP`; enable proxy |
| 9314 | header trust only when uvicorn is bound privately behind a trusted reverse |
| 9315 | proxy: |
| 9316 | |
| 9317 | ```text |
| 9318 | DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true |
| 9319 | ``` |
| 9320 | |
| 9321 | When the limit is full, the server returns: |
| 9322 | |
| 9323 | ```http |
| 9324 | 429 Too Many Requests |
| 9325 | Retry-After: 30 |
| 9326 | ``` |
| 9327 | |
| 9328 | ```json |
| 9329 | { |
| 9330 | ""status"": ""error"", |
| 9331 | ""error"": ""Rate limit exceeded"", |
| 9332 | ""retry_after"": 30, |
| 9333 | ""limit"": 1000, |
| 9334 | ""window_seconds"": 60 |
| 9335 | } |
| 9336 | ``` |
| 9337 | |
| 9338 | ## Object Execution Timeout |
| 9339 | |
| 9340 | Object execution timeout is opt-in: |
| 9341 | |
| 9342 | ```text |
| 9343 | DBBASIC_OBJECT_TIMEOUT_SECONDS=5 |
| 9344 | ``` |
| 9345 | |
| 9346 | The default `0` keeps local development on the direct in-process execution path. |
| 9347 | When the value is above zero, object methods run in a short-lived worker process. |
| 9348 | If the object does not finish before the wall-clock timeout, the server |
| 9349 | terminates the worker and returns: |
| 9350 | |
| 9351 | ```http |
| 9352 | 504 Gateway Timeout |
| 9353 | ``` |
| 9354 | |
| 9355 | ```json |
| 9356 | { |
| 9357 | ""status"": ""error"", |
| 9358 | ""error"": ""Execution failed: GET timed out for object basics_slow after 5 seconds"" |
| 9359 | } |
| 9360 | ``` |
| 9361 | |
| 9362 | Timeout failures are written to the object log with |
| 9363 | `ObjectExecutionTimeoutError`, so Scroll and operators can see which object |
| 9364 | timed out. |
| 9365 | |
| 9366 | Trusted server-owned objects can opt back into the fast in-process path even |
| 9367 | when timeouts are enabled: |
| 9368 | |
| 9369 | ```text |
| 9370 | DBBASIC_TRUSTED_IN_PROCESS_OBJECTS=site_home,system_health |
| 9371 | ``` |
| 9372 | |
| 9373 | Use that only for reviewed objects shipped or controlled by the server operator, |
| 9374 | such as a public homepage that receives frequent hits. Untrusted user objects |
| 9375 | should stay on the timeout-enabled worker path. |
| 9376 | |
| 9377 | ### Warm worker pool |
| 9378 | |
| 9379 | With a timeout set and nothing else, every HTTP-invoked object (page objects |
| 9380 | served by site routes, `/objects/*`, webhooks) runs in a freshly spawned |
| 9381 | interpreter. That is safe but slow. `DBBASIC_WORKER_POOL_SIZE` is off by |
| 9382 | default (`0`); set it to keep that many long-lived worker processes warm: |
| 9383 | |
| 9384 | ```text |
| 9385 | DBBASIC_OBJECT_TIMEOUT_SECONDS=5 |
| 9386 | DBBASIC_WORKER_POOL_SIZE=2 |
| 9387 | ``` |
| 9388 | |
| 9389 | A pooled worker hands its result back as JSON. An object that returns a value |
| 9390 | JSON cannot hold (bytes, a set, a tuple as a dict key) is answered `500` with |
| 9391 | `Execution failed: object returned a value that is not JSON: bytes at body` |
| 9392 | -- the type and the key path -- and the worker writes one line to the server |
| 9393 | log with the object id and the type, never the value. The worker stays up. Without |
| 9394 | the pool the answer is the same `500` and log line, given by the server when |
| 9395 | it builds the JSON answer (a `bytes` body beside a `content_type` is not JSON |
| 9396 | and is served as before, though not through the pool). |
| 9397 | |
| 9398 | What stays the same: objects still run outside the server process, a call that |
| 9399 | exceeds the timeout still returns the same `504` (the worker is replaced and |
| 9400 | the pool keeps serving), errors come back in the same shape, and a source edit |
| 9401 | to an object is picked up on the next request. The pool's workers are shut down |
| 9402 | with the server. Objects listed in `DBBASIC_TRUSTED_IN_PROCESS_OBJECTS` still |
| 9403 | bypass the pool and run in the server process. `DBBASIC_MAX_CONCURRENT_EXECUTIONS` |
| 9404 | still caps how many executions are admitted; the pool size is how many of them |
| 9405 | can actually run in parallel, so keep the pool at or below that cap. |
| 9406 | |
| 9407 | A reasonable starting size is `2` on a small VM. Each worker used about 32 MB |
| 9408 | of RSS after rendering one page, so budget that per worker. |
| 9409 | |
| 9410 | Measured on one machine (Apple M1 Pro), rendering the real app-notes `/notes` |
| 9411 | page (`site_view_render`) with 200 notes, so treat these as indicative, not as |
| 9412 | a capacity plan: |
| 9413 | |
| 9414 | | Mode | Page shell | Throughput | |
| 9415 | | --- | --- | --- | |
| 9416 | | in-process (no timeout) | about 5 ms | | |
| 9417 | | timeout, no pool (spawn per call) | about 68 ms | about 14 req/s at 8 connections, p50 544 ms | |
| 9418 | | timeout + pool of 4 | about 5.7 ms | about 257 req/s at 8 connections | |
| 9419 | |
| 9420 | The benchmark is `scripts/bench/experiments/real_page_modes.sh`. The test |
| 9421 | `tests/test_worker_pool_real_pages.py` checks that the real notes page, the |
| 9422 | identity payload, error shape, live edits and the timeout behave the same with |
| 9423 | and without the pool. |
| 9424 | |
| 9425 | This boundary is intentionally narrow. It stops hung object work and releases |
| 9426 | the execution slot, but it is not the final sandbox. CPU quotas and memory |
| 9427 | limits are still future hardening steps. |
| 9428 | |
| 9429 | ## Capacity Health |
| 9430 | |
| 9431 | `GET /health` stays public and cheap: |
| 9432 | |
| 9433 | ```json |
| 9434 | { |
| 9435 | ""status"": ""ok"" |
| 9436 | } |
| 9437 | ``` |
| 9438 | |
| 9439 | Detailed capacity is an operator surface and requires the admin token: |
| 9440 | |
| 9441 | ```http |
| 9442 | GET /health?capacity=true |
| 9443 | Authorization: Token <token> |
| 9444 | ``` |
| 9445 | |
| 9446 | It reports the configured request and object execution limits, current |
| 9447 | in-flight slot counts, object count, storage status, version, uptime, request |
| 9448 | counts, recent response timing, and basic process/system information. Scroll and |
| 9449 | future station routers should use this detailed shape instead of guessing from |
| 9450 | logs. |
| 9451 | |
| 9452 | `GET /health?metrics=true` includes the same capacity payload plus detailed |
| 9453 | request metrics such as status counts, top paths, and recent HTTP errors. |
| 9454 | |
| 9455 | ## High-Traffic Shape |
| 9456 | |
| 9457 | Use layered limits: |
| 9458 | |
| 9459 | - reverse proxy body limit before Python receives the request |
| 9460 | - app body limit through `DBBASIC_MAX_REQUEST_BYTES` |
| 9461 | - app request and object execution limits through the concurrency env vars |
| 9462 | - per-IP and per-token rate limits before write or execute paths |
| 9463 | - object execution wall-clock timeouts |
| 9464 | - later CPU and memory isolation around worker processes |
| 9465 | |
| 9466 | When the server is overloaded, it should return `429 Too Many Requests` for rate |
| 9467 | limits or `503 Service Unavailable` for temporary capacity pressure. That is |
| 9468 | better than letting a small VM run out of memory or accumulate unbounded object |
| 9469 | work. |
| 9470 | |
| 9471 | ## Staging Defaults |
| 9472 | |
| 9473 | For the first public staging VM: |
| 9474 | |
| 9475 | ```text |
| 9476 | DBBASIC_MAX_REQUEST_BYTES=1048576 |
| 9477 | DBBASIC_MAX_CONCURRENT_REQUESTS=64 |
| 9478 | DBBASIC_MAX_CONCURRENT_EXECUTIONS=8 |
| 9479 | DBBASIC_OBJECT_TIMEOUT_SECONDS=5 |
| 9480 | DBBASIC_WORKER_POOL_SIZE=2 |
| 9481 | DBBASIC_RATE_LIMIT_REQUESTS=1000 |
| 9482 | DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60 |
| 9483 | DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true |
| 9484 | DBBASIC_ENABLE_SOURCE_WRITES=false |
| 9485 | ``` |
| 9486 | |
| 9487 | Keep source writes closed until auth, permissions, backups, and rollback checks |
| 9488 | are working. Keep public routes narrow. Let the object server prove the loop |
| 9489 | without allowing arbitrary public code changes. |
| 9490 | |
| 9491 | ## Cluster Direction |
| 9492 | |
| 9493 | Local capacity should become a station signal. A single station can already |
| 9494 | return `503` when it is full. Later, station heartbeat or health data should |
| 9495 | include capacity fields so a cluster router can avoid saturated stations before |
| 9496 | forwarding object work. |
| 9497 | |
| 9498 | That signal should include request slots, execution slots, recent error rate, |
| 9499 | and basic machine load such as CPU and memory pressure. That keeps the cluster |
| 9500 | model simple: each station knows its own limits, and the router uses those |
| 9501 | limits to choose where work should go. |
| 9502 | |
| 9503 | ## Logs And Garbage Collection |
| 9504 | |
| 9505 | Traffic controls also need disk controls: |
| 9506 | |
| 9507 | - rotate object logs before they grow forever |
| 9508 | - gzip rotated logs at rest |
| 9509 | - keep a bounded number of rotated logs per object |
| 9510 | - disable noisy uvicorn access logs in systemd and rely on object logs, |
| 9511 | request metrics, and deliberate analytics objects |
| 9512 | - cap journald retention for process logs |
| 9513 | - keep backup retention explicit |
| 9514 | - delete temp files and stale lock files only through known runtime paths |
| 9515 | |
| 9516 | The active object log stays plain TSV so tools can tail it. Rotated logs can be |
| 9517 | read in place with normal Unix tools such as `gzip -cd`. |
| 9518 | |
| 9519 | ## Next Limits |
| 9520 | |
| 9521 | The request, concurrency, rate-limit, and timeout caps are only the first |
| 9522 | boundaries. The next production-hardening steps are: |
| 9523 | |
| 9524 | - CPU and memory isolation for untrusted object code |
| 9525 | - a longer-lived worker pool so timeout-enabled execution does not need a new |
| 9526 | process per request |
| 9527 | " |
| 9528 | single-vm-deployment Single VM Deployment Deployment & Operations 700 How to deploy DBBASIC Object Server on a single VM: layout, install, environment, systemd, HTTPS proxy, backups, and upgrade procedure. "This is the first deployment target for DBBASIC Object Server: one small VM, |
| 9529 | one ASGI process, one object source directory, and one data directory. |
| 9530 | |
| 9531 | The goal is not to claim the public runtime is production-ready. The goal is to |
| 9532 | keep a clean staging server running so install, restart, logs, object storage, |
| 9533 | and the edit/run/inspect loop are tested on a real machine. |
| 9534 | |
| 9535 | This shape should stay cheap and understandable: one small VM can run the |
| 9536 | server, objects, TSV-backed state, logs, versions, HTTPS proxy, and monitoring |
| 9537 | without requiring a separate database tier for the first useful app. |
| 9538 | |
| 9539 | ## Deployment Goal |
| 9540 | |
| 9541 | The first deployment path should stay closer to a simple Unix/PHP-style upload |
| 9542 | than a large multi-service app stack: |
| 9543 | |
| 9544 | - one VM is enough for the first useful business app |
| 9545 | - no container runtime is required for the base deployment |
| 9546 | - no separate database server is required before the app proves itself |
| 9547 | - server code, live object source, runtime data, and secrets live in separate |
| 9548 | Unix paths |
| 9549 | - normal upgrades are `git pull`, package install, service restart, checks |
| 9550 | - object edits do not require a full server redeploy |
| 9551 | - every manual step should become scriptable after it stays boring |
| 9552 | |
| 9553 | This does not mean skipping safety. The simple path still uses a service user, |
| 9554 | systemd, a reverse proxy, HTTPS, private config, filesystem checks, backups, and |
| 9555 | explicit public route allowlists. |
| 9556 | |
| 9557 | ## Verified Baseline |
| 9558 | |
| 9559 | The first staging install was verified on: |
| 9560 | |
| 9561 | - Ubuntu 24.04.4 LTS |
| 9562 | - Python 3.12.3 |
| 9563 | - Git 2.43.0 |
| 9564 | - Caddy 2.11.4 |
| 9565 | - systemd with the DBBASIC service and Caddy running as separate units |
| 9566 | |
| 9567 | Record the baseline on each new VM. Run the Caddy commands after Caddy is |
| 9568 | installed, if the VM does not already have it. |
| 9569 | |
| 9570 | ```bash |
| 9571 | lsb_release -a |
| 9572 | python3 --version |
| 9573 | git --version |
| 9574 | caddy version |
| 9575 | systemctl is-active dbbasic-object-server caddy |
| 9576 | cd /opt/dbbasic-object-server |
| 9577 | sudo -u dbbasic git rev-parse --short HEAD |
| 9578 | ``` |
| 9579 | |
| 9580 | Do not commit the VM's real IP address, hostname, or provider-specific details |
| 9581 | to this repository. |
| 9582 | |
| 9583 | ## System Updates |
| 9584 | |
| 9585 | Before using a new VM for staging, apply normal OS updates and reboot if Ubuntu |
| 9586 | requests it: |
| 9587 | |
| 9588 | ```bash |
| 9589 | sudo apt update |
| 9590 | apt list --upgradable |
| 9591 | sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y |
| 9592 | sudo DEBIAN_FRONTEND=noninteractive apt-get autoremove -y |
| 9593 | test -f /var/run/reboot-required && cat /var/run/reboot-required || true |
| 9594 | ``` |
| 9595 | |
| 9596 | If packages are kept back because they need new dependencies, install them |
| 9597 | explicitly when they are normal platform packages: |
| 9598 | |
| 9599 | ```bash |
| 9600 | sudo DEBIAN_FRONTEND=noninteractive apt-get install -y fwupd |
| 9601 | ``` |
| 9602 | |
| 9603 | After a reboot, verify the services and endpoint again: |
| 9604 | |
| 9605 | ```bash |
| 9606 | sudo systemctl is-active dbbasic-object-server caddy |
| 9607 | curl https://dbbasic.example.com/ |
| 9608 | ``` |
| 9609 | |
| 9610 | ## Provider Monitoring |
| 9611 | |
| 9612 | For DigitalOcean Droplets, the metrics agent is useful on staging VMs because it |
| 9613 | adds CPU, memory, disk, and network graphs plus alerting while the server is |
| 9614 | under active development. DigitalOcean describes this as a free opt-in service. |
| 9615 | It sends system telemetry for monitoring, not customer content. |
| 9616 | |
| 9617 | Install it after normal OS updates: |
| 9618 | |
| 9619 | ```bash |
| 9620 | curl -fsSL https://repos.insights.digitalocean.com/install.sh -o /tmp/do-agent-install.sh |
| 9621 | sudo bash /tmp/do-agent-install.sh |
| 9622 | ``` |
| 9623 | |
| 9624 | Verify it: |
| 9625 | |
| 9626 | ```bash |
| 9627 | systemctl is-active do-agent |
| 9628 | systemctl is-enabled do-agent |
| 9629 | dpkg-query -W do-agent |
| 9630 | systemctl --no-pager --full status do-agent |
| 9631 | ``` |
| 9632 | |
| 9633 | Metrics usually appear in the Droplet's Insights tab after a few minutes. This |
| 9634 | is provider-specific VM monitoring; it does not replace DBBASIC's own object |
| 9635 | logs, state, versions, or future application/runtime metrics. |
| 9636 | |
| 9637 | ## Layout |
| 9638 | |
| 9639 | Use separate paths for server code, object source, and runtime data: |
| 9640 | |
| 9641 | ```text |
| 9642 | /opt/dbbasic-object-server |
| 9643 | /var/lib/dbbasic-object-server/objects |
| 9644 | /var/lib/dbbasic-object-server/data |
| 9645 | ``` |
| 9646 | |
| 9647 | - `/opt/dbbasic-object-server` is the git checkout. |
| 9648 | - `/var/lib/dbbasic-object-server/objects` contains live object source files. |
| 9649 | - `/var/lib/dbbasic-object-server/data` contains state, logs, and versions. |
| 9650 | |
| 9651 | `objects` and `data` are mode 0700, owned by `dbbasic`: user objects run as a |
| 9652 | second user, `dbbasic-sandbox`, which must not be able to traverse, `stat` or |
| 9653 | `chmod` anything in them (see ""Kernel Requirements for User Code""). |
| 9654 | |
| 9655 | Keeping objects and data outside the checkout lets the server be upgraded |
| 9656 | without mixing application data into git history. |
| 9657 | |
| 9658 | ## Install |
| 9659 | |
| 9660 | On a fresh Debian or Ubuntu VM: |
| 9661 | |
| 9662 | ```bash |
| 9663 | sudo apt update |
| 9664 | sudo apt install -y python3 python3-venv python3-pip git |
| 9665 | sudo useradd --system --home /var/lib/dbbasic-object-server --shell /usr/sbin/nologin dbbasic |
| 9666 | sudo mkdir -p /opt/dbbasic-object-server |
| 9667 | sudo mkdir -p /var/lib/dbbasic-object-server/objects |
| 9668 | sudo mkdir -p /var/lib/dbbasic-object-server/data |
| 9669 | sudo chown -R dbbasic:dbbasic /opt/dbbasic-object-server /var/lib/dbbasic-object-server |
| 9670 | sudo chmod 755 /opt/dbbasic-object-server |
| 9671 | sudo chmod 750 /var/lib/dbbasic-object-server |
| 9672 | sudo chmod 750 /var/lib/dbbasic-object-server/objects |
| 9673 | sudo chmod 750 /var/lib/dbbasic-object-server/data |
| 9674 | ``` |
| 9675 | |
| 9676 | Clone and install the server: |
| 9677 | |
| 9678 | ```bash |
| 9679 | sudo -u dbbasic git clone <repository-url> /opt/dbbasic-object-server |
| 9680 | cd /opt/dbbasic-object-server |
| 9681 | sudo -u dbbasic python3 -m venv .venv |
| 9682 | sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]' |
| 9683 | ``` |
| 9684 | |
| 9685 | ## Environment |
| 9686 | |
| 9687 | Create `/etc/dbbasic-object-server.env`: |
| 9688 | |
| 9689 | ```text |
| 9690 | DBBASIC_OBJECTS_DIR=/var/lib/dbbasic-object-server/objects |
| 9691 | DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data |
| 9692 | DBBASIC_BACKUPS_DIR=/var/lib/dbbasic-object-server/data/backups |
| 9693 | DBBASIC_PACKAGES_DIR=/opt/dbbasic-object-server/packages |
| 9694 | DBBASIC_ENABLE_SOURCE_WRITES=false |
| 9695 | # Non-admin users writing their own u_<id>_ objects. Keep false until user |
| 9696 | # objects run sandboxed -- see ""User objects and external identity"" below. |
| 9697 | DBBASIC_ENABLE_USER_SOURCE_WRITES=false |
| 9698 | # An external token verifier (e.g. a DRF app's /api/auth/verify/). Unset = off. |
| 9699 | # Must be a trusted internal service: every caller's token is sent to it. |
| 9700 | # https:// is required unless the host is loopback (127.0.0.0/8, ::1, localhost). |
| 9701 | # DBBASIC_IDENTITY_VERIFY_URL=http://127.0.0.1:8000/api/auth/verify/ |
| 9702 | # This server's name; the verifier must echo it as ""audience"" (required). |
| 9703 | # DBBASIC_IDENTITY_AUDIENCE=box-a.example.com |
| 9704 | # Shared secret sent as X-DBBASIC-Verify-Secret (required for a non-loopback URL). |
| 9705 | # DBBASIC_IDENTITY_VERIFY_SECRET=<random, 16+ visible characters> |
| 9706 | # Roles the verifier may confer (default: none; admin names never). |
| 9707 | # DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES=viewer,editor |
| 9708 | # Seconds a verified token is trusted before re-asking (default 30, at most 60). The app |
| 9709 | # can also POST /admin/identity/sources/forget (admin token) on revocation. |
| 9710 | # DBBASIC_IDENTITY_CACHE_TTL_SECONDS=30 |
| 9711 | DBBASIC_ENABLE_FILE_WRITES=false |
| 9712 | DBBASIC_ENABLE_PACKAGE_INSTALLS=false |
| 9713 | DBBASIC_ENABLE_PACKAGE_RESTORE=false |
| 9714 | # AI chat, voice, and reader -- each is its own flag; enabling AI chat does |
| 9715 | # NOT enable TTS/STT/reader. Each also needs a per-user provider key stored |
| 9716 | # via PUT /identity/users/{id}/service-keys before it does anything -- see |
| 9717 | # docs/shell-and-ai.md and docs/secrets-and-credentials.md. |
| 9718 | DBBASIC_ENABLE_AI_CHAT=false |
| 9719 | DBBASIC_AI_TIMEOUT_SECONDS=60 |
| 9720 | DBBASIC_AI_DEFAULT_MODEL=anthropic:claude-haiku-5-5 |
| 9721 | # Effort for conversation tool subsets and for builder mode |
| 9722 | # (low|medium|high|xhigh|max); sent only to Claude 4.6+ models. |
| 9723 | DBBASIC_AI_EFFORT=low |
| 9724 | DBBASIC_AI_BUILDER_EFFORT=high |
| 9725 | DBBASIC_ENABLE_TTS=false |
| 9726 | DBBASIC_TTS_CLOUD_TIMEOUT_SECONDS=30 |
| 9727 | # STT costs real money on every utterance (not just occasional replies |
| 9728 | # like TTS) -- leave this off even where TTS is on unless you mean it. |
| 9729 | DBBASIC_ENABLE_STT=false |
| 9730 | DBBASIC_STT_TIMEOUT_SECONDS=30 |
| 9731 | DBBASIC_ENABLE_READER=false |
| 9732 | DBBASIC_ADMIN_TOKEN=replace-with-a-generated-token |
| 9733 | DBBASIC_MAX_REQUEST_BYTES=1048576 |
| 9734 | DBBASIC_MAX_OBJECT_FILE_BYTES=1048576 |
| 9735 | DBBASIC_MAX_CONCURRENT_REQUESTS=64 |
| 9736 | DBBASIC_MAX_CONCURRENT_EXECUTIONS=8 |
| 9737 | # One customer's user objects may run this many at once (0 = no per-user cap). |
| 9738 | # Over it, that customer alone gets 429; others are unaffected. |
| 9739 | DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER=3 |
| 9740 | # Per-customer storage quotas for u_<id>_ objects (0 = unlimited each): |
| 9741 | # objects owned, bytes of one object's state, bytes of all _files storage. |
| 9742 | DBBASIC_USER_MAX_OBJECTS=100 |
| 9743 | DBBASIC_USER_MAX_STATE_BYTES=5242880 |
| 9744 | DBBASIC_USER_MAX_FILES_BYTES=104857600 |
| 9745 | DBBASIC_OBJECT_TIMEOUT_SECONDS=5 |
| 9746 | DBBASIC_WORKER_POOL_SIZE=2 |
| 9747 | DBBASIC_TRUSTED_IN_PROCESS_OBJECTS=site_home |
| 9748 | DBBASIC_RATE_LIMIT_REQUESTS=1000 |
| 9749 | DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60 |
| 9750 | DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true |
| 9751 | DBBASIC_ENABLE_PERMISSION_AUDIT=false |
| 9752 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false |
| 9753 | DBBASIC_PERMISSION_TRUST_HEADERS=false |
| 9754 | # true = a stored allow rule whose narrowing key was dropped (a misspelt or |
| 9755 | # null row_filter, collection, ...) grants nothing instead of applying more |
| 9756 | # widely than written. Deny rules are untouched. Off by default; the default |
| 9757 | # may turn on in a later release (`docs/permissions-model.md`). |
| 9758 | DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS=false |
| 9759 | DBBASIC_ENABLE_SESSION_LOGIN=false |
| 9760 | DBBASIC_SESSION_LOGIN_TOKEN= |
| 9761 | DBBASIC_ENABLE_PASSWORD_LOGIN=false |
| 9762 | DBBASIC_COOKIE_SECURE=true |
| 9763 | DBBASIC_LOGIN_LOCKOUT_ATTEMPTS=5 |
| 9764 | DBBASIC_LOGIN_LOCKOUT_WINDOW_SECONDS=900 |
| 9765 | DBBASIC_ENABLE_RECORD_EVENTS=true |
| 9766 | DBBASIC_EVENT_KEEP_COUNT=1000 |
| 9767 | DBBASIC_EVENT_KEEP_SECONDS=604800 |
| 9768 | DBBASIC_LOG_MAX_BYTES=10485760 |
| 9769 | DBBASIC_LOG_COMPRESS_ROTATED=true |
| 9770 | DBBASIC_LOG_KEEP_ROTATED=32 |
| 9771 | # Other feature gates worth knowing exist -- off by default, turn on what |
| 9772 | # you actually use rather than everything at once. |
| 9773 | DBBASIC_ENABLE_USER_FILES=false |
| 9774 | DBBASIC_ENABLE_REALTIME=false |
| 9775 | DBBASIC_ENABLE_SITE_ROUTES=false |
| 9776 | DBBASIC_ENABLE_FEED=false |
| 9777 | DBBASIC_ENABLE_FILTERING=false |
| 9778 | DBBASIC_ENABLE_CONCURRENCY=false |
| 9779 | DBBASIC_ENABLE_SESSION_ADMIN_GATES=false |
| 9780 | # off | shadow | on. Makes a permission-filtered list cost what the user can |
| 9781 | # see instead of the whole collection (docs/permissions-model.md#row-filter-index). |
| 9782 | # Run `shadow` first: it serves the old result and logs any disagreement. |
| 9783 | DBBASIC_ROW_FILTER_INDEX=off |
| 9784 | # Copy new mail from members' own IMAP mailboxes into their inbox |
| 9785 | # (app-mail-sync; see docs/http-api-contract.md#mail-sync-imap-inbound). |
| 9786 | # The second line lets it reach mail servers on private addresses. |
| 9787 | DBBASIC_ENABLE_MAIL_SYNC=false |
| 9788 | DBBASIC_MAIL_SYNC_ALLOW_PRIVATE_HOSTS=false |
| 9789 | ``` |
| 9790 | |
| 9791 | Generate a local token on the VM: |
| 9792 | |
| 9793 | ```bash |
| 9794 | python3 -c ""import secrets; print(secrets.token_urlsafe(32))"" |
| 9795 | ``` |
| 9796 | |
| 9797 | Use that generated value for `DBBASIC_ADMIN_TOKEN`. Do not reuse test tokens, |
| 9798 | README placeholders, or tokens from another server. It is required for local or |
| 9799 | admin object listing and introspection requests such as source, state, logs, |
| 9800 | metadata, and versions. |
| 9801 | |
| 9802 | ## Bootstrap Browser Login |
| 9803 | |
| 9804 | To enable browser login on a fresh VM, create the first admin user from the |
| 9805 | shell and turn on password login: |
| 9806 | |
| 9807 | ```bash |
| 9808 | cd /opt/dbbasic-object-server |
| 9809 | sudo -u dbbasic DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data \ |
| 9810 | .venv/bin/python object_identity_cli.py create-superuser \ |
| 9811 | --user-id operator --email you@example.com |
| 9812 | ``` |
| 9813 | |
| 9814 | The password is prompted twice without echo and stored only as a scrypt hash |
| 9815 | under `data/identity/credentials.tsv` (owner-only permissions, inside the |
| 9816 | runtime data directory that never enters source control). Then set |
| 9817 | `DBBASIC_ENABLE_PASSWORD_LOGIN=true` in the environment file, restart the |
| 9818 | service, and allow `/login` and `/logout` through the reverse proxy. Keep |
| 9819 | `DBBASIC_COOKIE_SECURE=true` behind HTTPS; set it to `false` only for |
| 9820 | plain-HTTP local development. Additional users can be managed with the same |
| 9821 | CLI (`create-user`, `set-password`, `list-users`) or through the admin HTTP |
| 9822 | surface from Scroll. |
| 9823 | |
| 9824 | For the first VM boot, leave source writes disabled. After health checks, |
| 9825 | backups, and proxy access are working, a staging server can enable source |
| 9826 | writes: |
| 9827 | |
| 9828 | ```text |
| 9829 | DBBASIC_ENABLE_SOURCE_WRITES=true |
| 9830 | ``` |
| 9831 | |
| 9832 | ### User objects and external identity |
| 9833 | |
| 9834 | To let another app's users call this server with their own |
| 9835 | tokens, set `DBBASIC_IDENTITY_VERIFY_URL` to that app's verify endpoint on |
| 9836 | an internal address (`https://`, or `http://` to a loopback host only), |
| 9837 | `DBBASIC_IDENTITY_AUDIENCE` to this server's name, and -- for a host that |
| 9838 | is not loopback -- `DBBASIC_IDENTITY_VERIFY_SECRET`. Those users can then run their own `u_<id>_` objects |
| 9839 | and list theirs plus the system objects marked `LISTED = True`; they are |
| 9840 | never admin. Their code may call only system objects marked |
| 9841 | `USER_CALLABLE = True`, and each user is held to the concurrency and storage |
| 9842 | limits above (runtime-contract.md ""Fairness and quotas""). See |
| 9843 | [`permissions-model.md`](/docs/permissions-model#identity-sources). |
| 9844 | |
| 9845 | Letting them *write* code is a separate switch, |
| 9846 | `DBBASIC_ENABLE_USER_SOURCE_WRITES=true`. The server refuses user writes |
| 9847 | (403) unless user objects can run sandboxed on this host (the sandbox |
| 9848 | launcher running, Landlock ABI >= 4, not root; `python object_sandbox.py |
| 9849 | --status`), because without that wall a |
| 9850 | user write would be arbitrary Python running with the server's privileges. |
| 9851 | `DBBASIC_ENABLE_SOURCE_WRITES` does not imply it and it does not imply |
| 9852 | `DBBASIC_ENABLE_SOURCE_WRITES`. |
| 9853 | |
| 9854 | Leave file writes disabled on public staging until quotas, permissions, and |
| 9855 | content policy are ready for the use case. A controlled operator VM can enable |
| 9856 | them separately: |
| 9857 | |
| 9858 | ```text |
| 9859 | DBBASIC_ENABLE_FILE_WRITES=true |
| 9860 | ``` |
| 9861 | |
| 9862 | Permission audit and enforcement should also stay closed on first boot. Turn on |
| 9863 | audit mode first to watch route decisions without blocking users: |
| 9864 | |
| 9865 | ```text |
| 9866 | DBBASIC_ENABLE_PERMISSION_AUDIT=true |
| 9867 | ``` |
| 9868 | |
| 9869 | Request blocking only after the persisted policy and auth gateway are confirmed: |
| 9870 | |
| 9871 | ```text |
| 9872 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true |
| 9873 | ``` |
| 9874 | |
| 9875 | Once set, enforcement is always effective: every request is decided by the |
| 9876 | policy, and `permissions.mode` in `/permissions/status` reads `enforced`. The |
| 9877 | readiness checks in `/permissions/status` are advisory. A problem while |
| 9878 | enforced never opens the box; it shows in what the affected callers get: |
| 9879 | a corrupt or unreadable policy answers `503 permission_policy_unavailable` to |
| 9880 | everyone but the admin token (which can repair it with |
| 9881 | `PUT /permissions/policy`), an unreadable identity store answers |
| 9882 | `503 identity_store_unavailable` to signed-in callers, and with no sign-in |
| 9883 | path only the admin token and public grants get in. The server logs a |
| 9884 | `WARNING` for each problem at startup, `GET /admin/status` leads with it |
| 9885 | under `alerts`, and a problem that appears later is logged as an `ERROR` |
| 9886 | and recorded in `GET /admin/ops?kind=permission_readiness`. A policy with no |
| 9887 | grants is enforced as deny-all for everyone but admins, which is how a fresh |
| 9888 | box starts until it has a policy (see |
| 9889 | [permissions-model.md](/docs/permissions-model#route-enforcement) for the |
| 9890 | fresh-box order). |
| 9891 | |
| 9892 | The one thing enforcement refuses to start without is |
| 9893 | `DBBASIC_ADMIN_TOKEN`, the way in for every other problem. For one release |
| 9894 | `DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT=true` starts without it, |
| 9895 | still enforced (it used to start the server unenforced, and no longer does). |
| 9896 | `DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT` no longer does anything; |
| 9897 | remove it. To run without enforcement on purpose, leave |
| 9898 | `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false` and use |
| 9899 | `DBBASIC_ENABLE_PERMISSION_AUDIT=true` to watch decisions. |
| 9900 | |
| 9901 | A hosted, multi-user box should also set |
| 9902 | `DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true`: the server then refuses to |
| 9903 | start, with a one-line `Refusing to start: ...` error, unless |
| 9904 | `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true` (audit alone refuses too), so a |
| 9905 | lost or mistyped enforcement flag cannot bring the box up open. Unset, it |
| 9906 | changes nothing. |
| 9907 | |
| 9908 | `DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS=true` stops the engine applying a |
| 9909 | stored allow rule that `/admin/status` reports as allowing more than written |
| 9910 | (a misspelt or null `row_filter`, `collection` and the like): the rule grants |
| 9911 | nothing until it is fixed. Before turning it on, read the alert and |
| 9912 | `GET /permissions/status`: every rule named there as an allow that ""applies |
| 9913 | more widely than written"" will stop granting, which can lock its users out of |
| 9914 | that collection until you fix the key. Deny rules are not affected. Unset or |
| 9915 | `false`, it changes nothing (`docs/permissions-model.md`). |
| 9916 | |
| 9917 | `DBBASIC_PERMISSION_TRUST_HEADERS=true` is only appropriate when a trusted proxy |
| 9918 | or auth gateway strips client-supplied identity headers and writes fresh |
| 9919 | `X-DBBASIC-*` headers itself. |
| 9920 | |
| 9921 | Do not commit real tokens, VM hostnames, private URLs, or deployment-specific |
| 9922 | paths to this repository. |
| 9923 | |
| 9924 | After creating the file, keep it readable by root and the service group only: |
| 9925 | |
| 9926 | ```bash |
| 9927 | sudo chown root:dbbasic /etc/dbbasic-object-server.env |
| 9928 | sudo chmod 640 /etc/dbbasic-object-server.env |
| 9929 | ``` |
| 9930 | |
| 9931 | ## Filesystem Check |
| 9932 | |
| 9933 | The public package includes a small single-VM layout checker. Run it after |
| 9934 | installing the server and after changing ownership or deployment paths: |
| 9935 | |
| 9936 | ```bash |
| 9937 | cd /opt/dbbasic-object-server |
| 9938 | set -a |
| 9939 | . /etc/dbbasic-object-server.env |
| 9940 | set +a |
| 9941 | .venv/bin/python -m deployment_checks |
| 9942 | ``` |
| 9943 | |
| 9944 | The checker validates the normal Unix boundary: |
| 9945 | |
| 9946 | - server code under `/opt/dbbasic-object-server` |
| 9947 | - live object source under `/var/lib/dbbasic-object-server/objects` |
| 9948 | - runtime data under `/var/lib/dbbasic-object-server/data` |
| 9949 | - deployment secrets under `/etc/dbbasic-object-server.env` |
| 9950 | - systemd unit under `/etc/systemd/system/dbbasic-object-server.service` |
| 9951 | |
| 9952 | Errors should be fixed before exposing routes publicly. Warnings usually mean a |
| 9953 | runtime path is visible to other local users. On a single-purpose staging VM |
| 9954 | that may not break anything, but the safer default is `750` for object and data |
| 9955 | directories. |
| 9956 | |
| 9957 | ## Traffic Limits |
| 9958 | |
| 9959 | Keep the public server narrow while it is staging. |
| 9960 | |
| 9961 | `DBBASIC_MAX_REQUEST_BYTES` limits inbound HTTP request bodies before JSON |
| 9962 | parsing or object execution. The default is 1 MiB: |
| 9963 | |
| 9964 | ```text |
| 9965 | DBBASIC_MAX_REQUEST_BYTES=1048576 |
| 9966 | DBBASIC_MAX_CONCURRENT_REQUESTS=64 |
| 9967 | DBBASIC_MAX_CONCURRENT_EXECUTIONS=8 |
| 9968 | ``` |
| 9969 | |
| 9970 | Configure the same or smaller request body limit in the reverse proxy so Caddy |
| 9971 | or nginx can reject oversized traffic before Python handles it. The app-level |
| 9972 | limit stays in place because proxy configuration can drift. |
| 9973 | |
| 9974 | The concurrency limits are per process. Under overload, the server returns |
| 9975 | `503` rather than queueing unlimited work on a small VM. Future production |
| 9976 | hardening still needs CPU/memory isolation. |
| 9977 | `DBBASIC_OBJECT_TIMEOUT_SECONDS` runs object methods in a worker process and |
| 9978 | returns `504` if the wall-clock timeout is exceeded. On its own that means a |
| 9979 | new Python interpreter for every object call, including every page object and |
| 9980 | site route. `DBBASIC_WORKER_POOL_SIZE` (default `0`, off) keeps that many warm |
| 9981 | worker processes instead. Isolation, the `504` timeout and live source edits |
| 9982 | are unchanged; the interpreter start-up cost is not paid per request. Start |
| 9983 | with `2` on a small VM; each worker holds roughly 32 MB of RSS after serving a |
| 9984 | page. Size it near the number of objects you expect to run at once, and keep it |
| 9985 | at or below `DBBASIC_MAX_CONCURRENT_EXECUTIONS`. Measured numbers are in |
| 9986 | [`traffic-limits.md`](/docs/traffic-limits#warm-worker-pool). |
| 9987 | `DBBASIC_TRUSTED_IN_PROCESS_OBJECTS` is a comma-separated allowlist for |
| 9988 | reviewed server-owned objects that should keep the fast in-process path, such as |
| 9989 | the public homepage. Do not add user-created objects to this list. |
| 9990 | The rate limit values above return `429` with `Retry-After` when one IP or |
| 9991 | valid admin token exceeds the configured window. |
| 9992 | `DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS` is appropriate only because uvicorn is |
| 9993 | bound to `127.0.0.1` behind Caddy. |
| 9994 | |
| 9995 | See [`traffic-limits.md`](/docs/traffic-limits) for the operating model. |
| 9996 | |
| 9997 | ## Log Maintenance |
| 9998 | |
| 9999 | Object logs are part of the runtime feedback loop, so staging servers should not |
| 10000 | let them grow forever. |
| 10001 | |
| 10002 | The active log for an object stays plain TSV: |
| 10003 | |
| 10004 | ```text |
| 10005 | /var/lib/dbbasic-object-server/data/logs/{object_id}/log.tsv |
| 10006 | ``` |
| 10007 | |
| 10008 | When it reaches `DBBASIC_LOG_MAX_BYTES`, the server rotates it. New rotated logs |
| 10009 | are gzip-compressed by default: |
| 10010 | |
| 10011 | ```text |
| 10012 | /var/lib/dbbasic-object-server/data/logs/{object_id}/log-YYYYMMDD-HHMMSS-ffffff.tsv.gz |
| 10013 | ``` |
| 10014 | |
| 10015 | Inspect compressed logs without expanding a second copy: |
| 10016 | |
| 10017 | ```bash |
| 10018 | gzip -cd /var/lib/dbbasic-object-server/data/logs/site_home/log-*.tsv.gz |
| 10019 | ``` |
| 10020 | |
| 10021 | Garbage collection is controlled by `DBBASIC_LOG_KEEP_ROTATED`. The default |
| 10022 | keeps the newest 32 rotated files per object and deletes older rotated logs |
| 10023 | after a successful rotation. Set it to `0` to keep all rotated logs. |
| 10024 | |
| 10025 | This is at-rest compression. For in-motion compression, start with reverse-proxy |
| 10026 | HTTP compression for large log responses. Later station replication should |
| 10027 | compress batches, not individual tiny events. |
| 10028 | |
| 10029 | Event rows are a delivery queue, not the durable audit log. The server and |
| 10030 | daemon prune old `data/state/events/state.tsv` event rows with: |
| 10031 | |
| 10032 | ```bash |
| 10033 | DBBASIC_EVENT_KEEP_COUNT=1000 |
| 10034 | DBBASIC_EVENT_KEEP_SECONDS=604800 |
| 10035 | ``` |
| 10036 | |
| 10037 | Set either value to `0` to disable that retention rule. Subscriptions stay in |
| 10038 | place, and any event referenced by a subscription `last_event_id` is protected so |
| 10039 | the daemon keeps its delivery cursor. Failed delivery attempts are protected too, |
| 10040 | so callback failures stay visible and retryable until delivery succeeds or the |
| 10041 | subscription is repaired. |
| 10042 | |
| 10043 | ## Packages |
| 10044 | |
| 10045 | Packages are read from `DBBASIC_PACKAGES_DIR`. The public server currently |
| 10046 | supports package listing, dry-run planning, and package installs only when |
| 10047 | `DBBASIC_ENABLE_PACKAGE_INSTALLS=true`. Dry-run and install requests append |
| 10048 | compact audit rows under |
| 10049 | `/var/lib/dbbasic-object-server/data/package_changes/{package_id}/changes.jsonl`. |
| 10050 | Package installs create a runtime restore point before writing source, schema, |
| 10051 | or seed files. Restore points default to |
| 10052 | `/var/lib/dbbasic-object-server/data/backups/`; set `DBBASIC_BACKUPS_DIR` if |
| 10053 | they should live on another mounted volume. |
| 10054 | |
| 10055 | Package restore is separate and requires `DBBASIC_ENABLE_PACKAGE_RESTORE=true`. |
| 10056 | It restores a recorded install restore point with overwrite and snapshot |
| 10057 | pruning, so package-created runtime files are removed if they were not in the |
| 10058 | archive. |
| 10059 | |
| 10060 | Keep `DBBASIC_ENABLE_PACKAGE_INSTALLS=false` and |
| 10061 | `DBBASIC_ENABLE_PACKAGE_RESTORE=false` on public staging unless `/packages` is |
| 10062 | reachable only from a private admin surface. The first install path writes |
| 10063 | objects and schemas, creates seed TSV files only when no data exists, and |
| 10064 | rejects permissions/migrations until merge/run semantics are explicit. |
| 10065 | |
| 10066 | ## Reactions and Scheduled Passes |
| 10067 | |
| 10068 | Installing a package does not by itself make its reactions run. Three |
| 10069 | separate things have to be true, and a stock install has only some of them: |
| 10070 | |
| 10071 | - **Event handlers** (`HANDLES` objects: an invoice flipping to paid, a |
| 10072 | journal composing, a sale moving stock) run only when |
| 10073 | `DBBASIC_ENABLE_EVENT_HANDLERS=true` (writes made over HTTP) and/or |
| 10074 | `DBBASIC_ENABLE_CHANGE_DISPATCH=true` (the daemon replays the change log, |
| 10075 | which also reaches writes actions, runners and webhooks make at storage |
| 10076 | level -- a Stripe payment, a checkout, a shipment). Both default off. |
| 10077 | Turning them on is a deliberate act: read the open handler findings |
| 10078 | (tax basis, order totals) before you do. **Change dispatch starts from |
| 10079 | the moment its first pass runs**: writes made before then (payments that |
| 10080 | landed while the flag was off) are NOT dispatched, and the first pass |
| 10081 | says so -- `GET /daemon/status` carries `change_dispatch_baseline` and a |
| 10082 | `change_dispatch_skipped_history` warning with the count. To replay them, |
| 10083 | delete `.change_dispatch_cursor` in the data dir and start the daemon once |
| 10084 | with `DBBASIC_CHANGE_DISPATCH_FROM=beginning` (or an ISO timestamp). Read |
| 10085 | what your handlers do first: state-based reactions (invoice status, books, |
| 10086 | stock) are idempotent, but a replay queues an order email per order. |
| 10087 | - **Scheduled passes** (invoice aging, recurring journals, the biller, the |
| 10088 | usage rollup, tracking polls, and the methods objects schedule for |
| 10089 | themselves with `_schedule`) run only in the daemon, `object_daemon.py`. |
| 10090 | `install.sh` installs and starts it as `dbbasic-object-daemon.service` |
| 10091 | (see ""systemd"" below); a hand-built VM needs that unit added. |
| 10092 | - **Cron schedules** -- every schedule the shipped packages declare -- |
| 10093 | need `croniter`, which is an optional extra (`scheduler`). `install.sh` |
| 10094 | installs it (`.[server,scheduler]`), and so does the one-click install, |
| 10095 | which runs `install.sh`. A hand-built VM installs it into the server's |
| 10096 | virtualenv with `pip install -e '.[server,scheduler]'`; a box installed |
| 10097 | before `install.sh` did so adds it the same way. |
| 10098 | |
| 10099 | None of this is silent any more. The server's startup log prints one |
| 10100 | `[dbbasic] Reactions NOT RUNNING (...)` line per gap, naming the handler |
| 10101 | objects or schedules affected and the setting that fixes it; the daemon's |
| 10102 | boot banner prints a `Reactions:` block; and |
| 10103 | `GET /daemon/status` reports `daemon.reactions` with `status`, the flags, |
| 10104 | whether a daemon heartbeat (`data/.daemon_heartbeat`, touched every 30s |
| 10105 | by a running daemon) is fresh, and a `problems` list |
| 10106 | (`handlers_inert`, `storage_writes_unreacted`, `cron_needs_croniter`, |
| 10107 | `daemon_not_running`). A cron task that cannot be scheduled also carries |
| 10108 | the reason in its own `error` field (`GET /daemon/scheduler/tasks`) and is |
| 10109 | logged as an ERROR once per daemon start. |
| 10110 | |
| 10111 | ## Minimal Object |
| 10112 | |
| 10113 | Create one object so the VM can prove execution, state, and logs: |
| 10114 | |
| 10115 | ```bash |
| 10116 | sudo -u dbbasic mkdir -p /var/lib/dbbasic-object-server/objects/site |
| 10117 | sudo -u dbbasic tee /var/lib/dbbasic-object-server/objects/site/home.py >/dev/null <<'PY' |
| 10118 | def GET(request): |
| 10119 | count = _state_manager.get(""count"", 0) + 1 |
| 10120 | _state_manager.set(""count"", count) |
| 10121 | return { |
| 10122 | ""status"": ""ok"", |
| 10123 | ""message"": ""DBBASIC Object Server is running"", |
| 10124 | ""count"": count, |
| 10125 | } |
| 10126 | PY |
| 10127 | ``` |
| 10128 | |
| 10129 | This object resolves as `site_home`. |
| 10130 | |
| 10131 | For a public staging page, the same object can return HTML instead of JSON: |
| 10132 | |
| 10133 | ```python |
| 10134 | def GET(request): |
| 10135 | count = int(_state_manager.get(""count"", 0)) + 1 |
| 10136 | _state_manager.set(""count"", count) |
| 10137 | _logger.info(""site_home served"", count=count, response_type=""html"") |
| 10138 | |
| 10139 | return { |
| 10140 | ""content_type"": ""text/html; charset=utf-8"", |
| 10141 | ""body"": f""<!doctype html><h1>DBBASIC Object Server</h1><p>Served {count} times.</p>"", |
| 10142 | } |
| 10143 | ``` |
| 10144 | |
| 10145 | That keeps the staging page honest: it is a live object with state and logs, not |
| 10146 | a static file. |
| 10147 | |
| 10148 | ## Run Manually |
| 10149 | |
| 10150 | Before creating a service, run the server by hand: |
| 10151 | |
| 10152 | ```bash |
| 10153 | cd /opt/dbbasic-object-server |
| 10154 | set -a |
| 10155 | . /etc/dbbasic-object-server.env |
| 10156 | set +a |
| 10157 | .venv/bin/uvicorn object_server:app --host 127.0.0.1 --port 8001 --no-access-log |
| 10158 | ``` |
| 10159 | |
| 10160 | In another shell: |
| 10161 | |
| 10162 | ```bash |
| 10163 | curl http://127.0.0.1:8001/health |
| 10164 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/health?capacity=true' |
| 10165 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" http://127.0.0.1:8001/objects |
| 10166 | curl http://127.0.0.1:8001/objects/site_home |
| 10167 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/objects/site_home?state=true' |
| 10168 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/objects/site_home?logs=true' |
| 10169 | ``` |
| 10170 | |
| 10171 | ## systemd |
| 10172 | |
| 10173 | Create `/etc/systemd/system/dbbasic-object-server.service`: |
| 10174 | |
| 10175 | ```ini |
| 10176 | [Unit] |
| 10177 | Description=DBBASIC Object Server |
| 10178 | After=network-online.target |
| 10179 | Wants=network-online.target |
| 10180 | |
| 10181 | [Service] |
| 10182 | User=dbbasic |
| 10183 | Group=dbbasic |
| 10184 | WorkingDirectory=/opt/dbbasic-object-server |
| 10185 | EnvironmentFile=/etc/dbbasic-object-server.env |
| 10186 | ExecStart=/opt/dbbasic-object-server/.venv/bin/uvicorn object_server:app --host 127.0.0.1 --port 8001 --no-access-log |
| 10187 | Restart=on-failure |
| 10188 | RestartSec=2 |
| 10189 | NoNewPrivileges=true |
| 10190 | PrivateTmp=true |
| 10191 | ProtectSystem=full |
| 10192 | ReadWritePaths=/var/lib/dbbasic-object-server |
| 10193 | |
| 10194 | [Install] |
| 10195 | WantedBy=multi-user.target |
| 10196 | ``` |
| 10197 | |
| 10198 | Start it: |
| 10199 | |
| 10200 | ```bash |
| 10201 | sudo systemctl daemon-reload |
| 10202 | sudo systemctl enable --now dbbasic-object-server |
| 10203 | sudo systemctl status dbbasic-object-server |
| 10204 | curl http://127.0.0.1:8001/health |
| 10205 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/health?capacity=true' |
| 10206 | ``` |
| 10207 | |
| 10208 | Watch logs: |
| 10209 | |
| 10210 | ```bash |
| 10211 | sudo journalctl -u dbbasic-object-server -f |
| 10212 | ``` |
| 10213 | |
| 10214 | ### The daemon unit |
| 10215 | |
| 10216 | The background daemon (`object_daemon.py`: scheduled tasks, including the |
| 10217 | methods objects schedule for themselves with `_schedule`, the queue, |
| 10218 | change dispatch, retention and cleanup passes) is a second unit with the |
| 10219 | same user, code, env file and data directory, and no port. `install.sh` |
| 10220 | writes it; on a hand-built VM create |
| 10221 | `/etc/systemd/system/dbbasic-object-daemon.service`: |
| 10222 | |
| 10223 | ```ini |
| 10224 | [Unit] |
| 10225 | Description=DBBASIC Object Server daemon (scheduler, queue, background passes) |
| 10226 | After=network-online.target dbbasic-object-server.service |
| 10227 | Wants=network-online.target |
| 10228 | |
| 10229 | [Service] |
| 10230 | User=dbbasic |
| 10231 | Group=dbbasic |
| 10232 | WorkingDirectory=/opt/dbbasic-object-server |
| 10233 | EnvironmentFile=/etc/dbbasic-object-server.env |
| 10234 | ExecStart=/opt/dbbasic-object-server/.venv/bin/python object_daemon.py |
| 10235 | Restart=on-failure |
| 10236 | RestartSec=5 |
| 10237 | NoNewPrivileges=true |
| 10238 | PrivateTmp=true |
| 10239 | ProtectSystem=full |
| 10240 | ReadWritePaths=/var/lib/dbbasic-object-server |
| 10241 | |
| 10242 | [Install] |
| 10243 | WantedBy=multi-user.target |
| 10244 | ``` |
| 10245 | |
| 10246 | ```bash |
| 10247 | sudo systemctl daemon-reload |
| 10248 | sudo systemctl enable --now dbbasic-object-daemon |
| 10249 | sudo journalctl -u dbbasic-object-daemon -f |
| 10250 | ``` |
| 10251 | |
| 10252 | Run exactly one daemon per data directory: two would both run every due |
| 10253 | task. Restart it alongside the server after an upgrade or an env change |
| 10254 | (`sudo systemctl restart dbbasic-object-server dbbasic-object-daemon`). |
| 10255 | |
| 10256 | `--no-access-log` keeps successful request lines out of journald. DBBASIC keeps |
| 10257 | the useful application trail in object logs and `/health?metrics=true`, which |
| 10258 | are the surfaces Scroll should read. If access analytics are needed later, |
| 10259 | build them as an explicit app/object instead of relying on raw process logs. |
| 10260 | |
| 10261 | Cap journald so process logs cannot consume the VM: |
| 10262 | |
| 10263 | ```bash |
| 10264 | sudo mkdir -p /etc/systemd/journald.conf.d |
| 10265 | sudo tee /etc/systemd/journald.conf.d/99-dbbasic.conf >/dev/null <<'EOF' |
| 10266 | [Journal] |
| 10267 | SystemMaxUse=128M |
| 10268 | SystemKeepFree=1G |
| 10269 | MaxRetentionSec=7day |
| 10270 | Compress=yes |
| 10271 | EOF |
| 10272 | sudo systemctl restart systemd-journald |
| 10273 | sudo journalctl --vacuum-size=128M |
| 10274 | sudo journalctl --disk-usage |
| 10275 | ``` |
| 10276 | |
| 10277 | ## Upgrade |
| 10278 | |
| 10279 | **Two different things live at `/opt` and two different things get served |
| 10280 | at `/var/lib` — know which one you changed before declaring a deploy done.** |
| 10281 | |
| 10282 | Core server modules (`object_server.py`, `object_ai.py`, and every other |
| 10283 | `.py` at the repo root) are imported directly from |
| 10284 | `/opt/dbbasic-object-server` — the steps below are complete for these: |
| 10285 | |
| 10286 | ```bash |
| 10287 | cd /opt/dbbasic-object-server |
| 10288 | sudo -u dbbasic git pull --ff-only |
| 10289 | sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]' |
| 10290 | sudo systemctl restart dbbasic-object-server dbbasic-object-daemon |
| 10291 | ``` |
| 10292 | |
| 10293 | **Anything under `packages/<name>/` (objects, schemas, seed data) is |
| 10294 | different.** The running server reads these from a separately *installed* |
| 10295 | copy at `/var/lib/dbbasic-object-server/objects/` and |
| 10296 | `/var/lib/dbbasic-object-server/data/schemas/` — `git pull` alone never |
| 10297 | syncs into it, no matter how many times you restart. A `git pull`-only |
| 10298 | ""deploy"" of a `packages/` change is a silent no-op: the commit lands, the |
| 10299 | tests pass, the service restarts clean, and the live server keeps running |
| 10300 | the old code with no error anywhere. After the `git pull` above, also run: |
| 10301 | |
| 10302 | ```bash |
| 10303 | curl -s -X POST https://dbbasic.example.com/packages/app-shell/install \ |
| 10304 | -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" -H 'Content-Type: application/json' \ |
| 10305 | -d '{""allow_replace"": true}' |
| 10306 | ``` |
| 10307 | |
| 10308 | To reinstall many packages (e.g. every one after an upgrade), take one |
| 10309 | backup and have each install reuse it instead of writing a full archive per |
| 10310 | package (about 237 MB each on a 3.3 GB data directory): |
| 10311 | |
| 10312 | ```bash |
| 10313 | BACKUP=$(curl -s -X POST https://dbbasic.example.com/admin/backups \ |
| 10314 | -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" | python3 -c 'import json,sys; print(json.load(sys.stdin)[""backup""][""id""])') |
| 10315 | for pkg in $(ls packages); do |
| 10316 | curl -s -X POST ""https://dbbasic.example.com/packages/$pkg/install"" \ |
| 10317 | -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" -H 'Content-Type: application/json' \ |
| 10318 | -d ""{\""allow_replace\"": true, \""restore_point\"": \""$BACKUP\""}"" |
| 10319 | done |
| 10320 | ``` |
| 10321 | |
| 10322 | The loop's order does not matter. A package whose queues or doors are written |
| 10323 | into another package's collection (app-nav's `attention_sources`) installs |
| 10324 | cleanly even when that package is still the old release's, because those rows |
| 10325 | are held back until `app-nav` is installed and refreshes its schema; `app-nav` |
| 10326 | sorts late in this loop, so read `install.warnings` of the earlier installs as |
| 10327 | ""waiting for app-nav"", not as failures, and expect `registered_for_others` in |
| 10328 | the app-nav response. The release gate's `upgrade` stage (`CONTRIBUTING.md`) |
| 10329 | runs exactly this loop from the previous tag. |
| 10330 | |
| 10331 | (swap `app-shell` for whichever package changed; `DBBASIC_ENABLE_PACKAGE_INSTALLS` |
| 10332 | must be `true`). Check the response's `install.objects[].status` — `""updated""` |
| 10333 | means a real change landed, `""unchanged""` means nothing to sync. Read |
| 10334 | `install.permission_retractions` too: it lists every permission rule the |
| 10335 | install removed because the package withdrew it, and every rule it left in |
| 10336 | place for you to decide about (`GET /permissions/unshipped` shows those for |
| 10337 | the whole box; see ""Package Rules And Upgrades"" in |
| 10338 | [`permissions-model.md`](/docs/permissions-model)). A package's tightened |
| 10339 | permission rules do not reach a running box until it is reinstalled. A schema-only |
| 10340 | change can also go straight to `PUT /admin/schemas/{collection}` with the |
| 10341 | updated schema JSON, same admin-token gate. Either way, **restart the |
| 10342 | service afterward** — object modules are cached in the running process, so |
| 10343 | even a correctly-installed file has no effect until the next restart clears |
| 10344 | that cache: |
| 10345 | |
| 10346 | ```bash |
| 10347 | sudo systemctl restart dbbasic-object-server dbbasic-object-daemon |
| 10348 | ``` |
| 10349 | |
| 10350 | To confirm a `packages/` deploy actually landed rather than trusting the |
| 10351 | install response alone, diff the live file against the source directly: |
| 10352 | |
| 10353 | ```bash |
| 10354 | diff /var/lib/dbbasic-object-server/objects/site/<name>.py \ |
| 10355 | /opt/dbbasic-object-server/packages/<pkg>/objects/site/<name>.py |
| 10356 | ``` |
| 10357 | |
| 10358 | A non-empty diff means the install step (or the restart) didn't happen yet. |
| 10359 | |
| 10360 | Then verify the local service, filesystem layout, public proxy, and deployed |
| 10361 | commit: |
| 10362 | |
| 10363 | ```bash |
| 10364 | cd /opt/dbbasic-object-server |
| 10365 | set -a |
| 10366 | . /etc/dbbasic-object-server.env |
| 10367 | set +a |
| 10368 | .venv/bin/python -m deployment_checks |
| 10369 | curl http://127.0.0.1:8001/health |
| 10370 | curl https://dbbasic.example.com/ |
| 10371 | sudo systemctl is-active dbbasic-object-server caddy |
| 10372 | sudo -u dbbasic git rev-parse --short HEAD |
| 10373 | ``` |
| 10374 | |
| 10375 | If the upgrade only changes live objects that were edited **directly** |
| 10376 | under `/var/lib/dbbasic-object-server/objects` (not via a `packages/` git |
| 10377 | change), the server should not need a git deploy at all. That is the |
| 10378 | object loop: edit one object, run it, inspect state/logs, and keep the |
| 10379 | version trail. This is a third, separate path from both cases above — it |
| 10380 | never touches `/opt` or git at all. |
| 10381 | |
| 10382 | ## HTTPS Proxy |
| 10383 | |
| 10384 | For a public or staging hostname, put Caddy or nginx in front of uvicorn and keep |
| 10385 | uvicorn bound to `127.0.0.1`. |
| 10386 | |
| 10387 | Install Caddy if the VM does not already have a reverse proxy: |
| 10388 | |
| 10389 | ```bash |
| 10390 | sudo apt install -y caddy |
| 10391 | ``` |
| 10392 | |
| 10393 | Example Caddyfile using documentation domains: |
| 10394 | |
| 10395 | ```caddyfile |
| 10396 | dbbasic.example.com { |
| 10397 | reverse_proxy 127.0.0.1:8001 |
| 10398 | } |
| 10399 | ``` |
| 10400 | |
| 10401 | Replace `dbbasic.example.com` only on the VM. Do not commit real deployment |
| 10402 | hostnames into this repository. |
| 10403 | |
| 10404 | If Caddy was already installed, inspect what it is serving before taking over |
| 10405 | the hostname: |
| 10406 | |
| 10407 | ```bash |
| 10408 | sudo systemctl status caddy --no-pager |
| 10409 | sudo sed -n '1,220p' /etc/caddy/Caddyfile |
| 10410 | sudo find /usr/share/caddy -maxdepth 3 -type f -printf '%p\t%s bytes\n' |
| 10411 | ``` |
| 10412 | |
| 10413 | Back up the old config before changing it: |
| 10414 | |
| 10415 | ```bash |
| 10416 | sudo cp -a /etc/caddy/Caddyfile /etc/caddy/Caddyfile.before-dbbasic |
| 10417 | ``` |
| 10418 | |
| 10419 | For the earliest public staging endpoint, expose only the hello object, system |
| 10420 | dashboard object, admin status and admin inspection routes, health check, and |
| 10421 | current-session self-service route until auth, permissions, and source |
| 10422 | visibility are ready. Keep the broad `/objects` listing blocked: |
| 10423 | |
| 10424 | ```caddyfile |
| 10425 | dbbasic.example.com { |
| 10426 | handle / { |
| 10427 | rewrite * /objects/site_home |
| 10428 | reverse_proxy 127.0.0.1:8001 |
| 10429 | } |
| 10430 | |
| 10431 | handle /health { |
| 10432 | reverse_proxy 127.0.0.1:8001 |
| 10433 | } |
| 10434 | |
| 10435 | handle /login { |
| 10436 | reverse_proxy 127.0.0.1:8001 |
| 10437 | } |
| 10438 | |
| 10439 | handle /logout { |
| 10440 | reverse_proxy 127.0.0.1:8001 |
| 10441 | } |
| 10442 | |
| 10443 | # only when signup / password reset are turned on |
| 10444 | handle /signup { |
| 10445 | reverse_proxy 127.0.0.1:8001 |
| 10446 | } |
| 10447 | |
| 10448 | handle /verify { |
| 10449 | reverse_proxy 127.0.0.1:8001 |
| 10450 | } |
| 10451 | |
| 10452 | handle /reset* { |
| 10453 | reverse_proxy 127.0.0.1:8001 |
| 10454 | } |
| 10455 | |
| 10456 | handle /admin/status { |
| 10457 | reverse_proxy 127.0.0.1:8001 |
| 10458 | } |
| 10459 | |
| 10460 | handle /admin/changes* { |
| 10461 | reverse_proxy 127.0.0.1:8001 |
| 10462 | } |
| 10463 | |
| 10464 | handle /admin/objects* { |
| 10465 | reverse_proxy 127.0.0.1:8001 |
| 10466 | } |
| 10467 | |
| 10468 | handle /admin/files* { |
| 10469 | reverse_proxy 127.0.0.1:8001 |
| 10470 | } |
| 10471 | |
| 10472 | handle /admin/collections* { |
| 10473 | reverse_proxy 127.0.0.1:8001 |
| 10474 | } |
| 10475 | |
| 10476 | handle /admin/schemas* { |
| 10477 | reverse_proxy 127.0.0.1:8001 |
| 10478 | } |
| 10479 | |
| 10480 | handle /admin/identity* { |
| 10481 | reverse_proxy 127.0.0.1:8001 |
| 10482 | } |
| 10483 | |
| 10484 | handle /permissions/status* { |
| 10485 | reverse_proxy 127.0.0.1:8001 |
| 10486 | } |
| 10487 | |
| 10488 | handle /permissions/policy* { |
| 10489 | reverse_proxy 127.0.0.1:8001 |
| 10490 | } |
| 10491 | |
| 10492 | handle /daemon/status { |
| 10493 | reverse_proxy 127.0.0.1:8001 |
| 10494 | } |
| 10495 | |
| 10496 | handle /daemon/scheduler/tasks* { |
| 10497 | reverse_proxy 127.0.0.1:8001 |
| 10498 | } |
| 10499 | |
| 10500 | handle /daemon/queue/messages* { |
| 10501 | reverse_proxy 127.0.0.1:8001 |
| 10502 | } |
| 10503 | |
| 10504 | handle /events* { |
| 10505 | reverse_proxy 127.0.0.1:8001 |
| 10506 | } |
| 10507 | |
| 10508 | handle /packages* { |
| 10509 | reverse_proxy 127.0.0.1:8001 |
| 10510 | } |
| 10511 | |
| 10512 | handle /api/mcp { |
| 10513 | reverse_proxy 127.0.0.1:8001 |
| 10514 | } |
| 10515 | |
| 10516 | handle_path /static/* { |
| 10517 | root * /var/lib/dbbasic-static |
| 10518 | file_server |
| 10519 | header Cache-Control ""public, max-age=3600"" |
| 10520 | } |
| 10521 | |
| 10522 | handle /permissions/audit* { |
| 10523 | reverse_proxy 127.0.0.1:8001 |
| 10524 | } |
| 10525 | |
| 10526 | handle /dashboard { |
| 10527 | rewrite * /objects/system_dashboard |
| 10528 | reverse_proxy 127.0.0.1:8001 |
| 10529 | } |
| 10530 | |
| 10531 | handle /admin/write-probe { |
| 10532 | rewrite * /objects/system_write_probe |
| 10533 | reverse_proxy 127.0.0.1:8001 |
| 10534 | } |
| 10535 | |
| 10536 | handle /collections/dbbasic_probe/records* { |
| 10537 | reverse_proxy 127.0.0.1:8001 |
| 10538 | } |
| 10539 | |
| 10540 | handle /collections/dbbasic_probe/changes { |
| 10541 | reverse_proxy 127.0.0.1:8001 |
| 10542 | } |
| 10543 | |
| 10544 | handle /schemas/dbbasic_probe { |
| 10545 | reverse_proxy 127.0.0.1:8001 |
| 10546 | } |
| 10547 | |
| 10548 | handle /identity/session { |
| 10549 | reverse_proxy 127.0.0.1:8001 |
| 10550 | } |
| 10551 | |
| 10552 | # This exposes GET/DELETE current-session checks. POST password login works |
| 10553 | # when DBBASIC_ENABLE_PASSWORD_LOGIN=true; the gateway session-mint POST |
| 10554 | # remains disabled unless DBBASIC_ENABLE_SESSION_LOGIN=true and |
| 10555 | # DBBASIC_SESSION_LOGIN_TOKEN are set. |
| 10556 | |
| 10557 | handle /objects/site_home* { |
| 10558 | reverse_proxy 127.0.0.1:8001 |
| 10559 | } |
| 10560 | |
| 10561 | handle { |
| 10562 | respond ""Not found"" 404 |
| 10563 | } |
| 10564 | } |
| 10565 | ``` |
| 10566 | |
| 10567 | Validate and reload: |
| 10568 | |
| 10569 | ```bash |
| 10570 | sudo caddy fmt --overwrite /etc/caddy/Caddyfile |
| 10571 | sudo caddy validate --config /etc/caddy/Caddyfile |
| 10572 | sudo systemctl reload caddy |
| 10573 | ``` |
| 10574 | |
| 10575 | Then test: |
| 10576 | |
| 10577 | ```bash |
| 10578 | curl https://dbbasic.example.com/ |
| 10579 | curl https://dbbasic.example.com/health |
| 10580 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/status |
| 10581 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/collections |
| 10582 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/schemas |
| 10583 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/identity/users |
| 10584 | curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/daemon/status |
| 10585 | curl https://dbbasic.example.com/objects/site_home |
| 10586 | curl https://dbbasic.example.com/admin/write-probe |
| 10587 | curl https://dbbasic.example.com/objects |
| 10588 | ``` |
| 10589 | |
| 10590 | The first six should return responses from the object server. The root and |
| 10591 | `site_home` responses may be JSON or HTML depending on the object. The full |
| 10592 | `/objects` route should stay blocked by Caddy in this early staging mode. |
| 10593 | |
| 10594 | The `admin-write-probe` package may also expose the narrow |
| 10595 | `/collections/dbbasic_probe/records*`, `/collections/dbbasic_probe/changes`, |
| 10596 | and `/schemas/dbbasic_probe` routes. Those routes are still protected by the |
| 10597 | server-side admin-token gate. They exist to prove collection create/update/ |
| 10598 | delete behavior, record changelog reads, and schema reads through the public |
| 10599 | reverse proxy without exposing every collection or schema route. Do not expose |
| 10600 | broad `/collections*`, `/schemas*`, `/objects*`, or source write routes on a |
| 10601 | public staging server. Use `/admin/collections*` and `/admin/schemas*` for |
| 10602 | operator inspection instead. Use `/admin/identity*` for read-only account, user, |
| 10603 | and session inspection instead of exposing broad identity management routes. |
| 10604 | |
| 10605 | ## Public Code Execution Controls |
| 10606 | |
| 10607 | In the early staging deployment, do not expose the full object server API |
| 10608 | directly to the internet. |
| 10609 | |
| 10610 | Use all of these controls together: |
| 10611 | |
| 10612 | - keep uvicorn bound to `127.0.0.1` |
| 10613 | - expose only specific routes through Cadd |
Only the first 512 KB is shown. Download the zip for the whole file.