Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/docs/validation-and-logic.md
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
validation-and-logic.md · 40.2 KB · 720 lines

Validation and Business Logic

Two things a schema-driven system has to get right without per-app code: rejecting bad writes, and running the business rules a record's lifecycle implies. DBBASIC does both from the schema, enforced on the server — the form is a convenience, not the gate.

Validation — declared once, enforced on every write

The write path (create and update) validates each field against the schema, server-side, regardless of which surface issued the write (web form, API, MCP agent, AI). A form's client-side checks are a nicety on top; they are not what protects the data.

What is enforced today:

CheckDeclared asEnforced
Type parsestype (integer, number, date, datetime, boolean, enum)✅
Required presentrequired: true✅
Enum membershipenum: [...]✅ (value must be in the list)
Length boundsvalidation.min_length / max_length✅
Numeric rangevalidation.min / max✅ (every writer; payments.amount_cents and refunds.amount_cents declare min: 1)
Strict numeric boundvalidation.exclusive_min / exclusive_max✅ (every writer; "greater than zero" — see below)
Required once a state holdsvalidation.required_when✅ (every writer; "a matched line names its target" — see below)
Patternvalidation.pattern (regex: Python re syntax, matched against the whole value; a package whose pattern does not compile is refused at install, see dron.md)✅
Referential integrityrelation: {collection}✅ (id must exist in the target)
State transitionfield transitions map / flow✅ (status can only move where allowed)
Read-only / computedread_only / type: computed✅ (client value rejected)
Uniquenessroot-level unique: [{fields, scope}]✅ (inside the write lock, for every writer — see below)
Frozen once settledroot-level locked_when: [{when, except}] or [{when, fields}]✅ (update and delete, inside the write lock, for every writer — see below)
Storable in TSV(substrate)✅ (size, no NUL/control chars)

Referential integrity and enforced state transitions are the notable ones — most no-code tools skip both. A relation is a validated pointer: you cannot point a project_id at a project that doesn't exist. A status field with a transitions map is a state machine: an order can go open → cancelled only if the schema says so.

Strict bounds and conditional required fields

{"name": "quantity", "type": "number", "required": true,
 "validation": {"exclusive_min": 0}},

{"name": "matched_to", "type": "text",
 "validation": {"required_when": {"match_status": ["matched"]}}}

exclusive_min / exclusive_max say strictly greater / less than a number. min and max are inclusive, so min: 0 admits a zero and "usage is positive" or "a stock move moves something" could not be said without code. Use min: 1 for a whole-number count (payments.amount_cents); use exclusive_min: 0 where fractions are real (quantity, which may be 1.5 or 0.0000001). The comparison is exact (decimal, not float), the field must be numeric, and a blank value is left to required, as it is for min. The refusal reads Record field 'quantity' must be greater than 0. They combine with min / max; a range that allows nothing (exclusive_min: 5 with max: 5) is refused at schema load.

required_when says the field must be non-blank (not empty, not only spaces) while the record matches every condition, in the shape locked_when.when uses: {field: value} or {field: [values]}, where a field holds one of its values (compared exactly, as stored; booleans as true / false). It is judged on the record as it will be stored: on an update, the stored row with the submitted changes applied. So the write that sets match_status to matched must also set matched_to (or find it already set), a write that blanks matched_to while the line is matched is refused, and moving the line out of matched frees the field. The refusal reads Record field 'matched_to' is required when match_status is matched.

Both are checked by object_records with the other field rules, on create and update, for every writer: HTTP, MCP, handlers, the daemon, imports. A refusal is the ordinary validation 400 (InvalidRecordPayloadError) and nothing is written. A row that already breaks a rule when a declaration is added stays on file, but is refused on its next write whatever that write changes — the same as min.

Refused at schema load (ValueError, never "no rule"): a bound that is not a finite number, an exclusive bound on a non-numeric field, bounds that leave no value, a required_when that is empty, names a field the schema does not declare (a typo would never apply), names the field itself, has a value that is not a string or a non-empty list of strings, or sits on a computed or read-only field.

What they do not do. They cannot say "forbidden when" (a loss move must have no destination) or compare two fields (taken <= capacity), and required_when asks for non-blank, not for a particular value. Those stay in a hook or a locked check. The whole list of what a declaration cannot say, and the tool for each, is What can't be declared.

Known gaps

  • **Numeric range is declared field by field, and most money fields do not

declare it yet.** validation.min/max is enforced, but a price can still go negative wherever no schema says otherwise. The collections where it mattered first (payments, refunds) declare min: 1, and the quantities of usage events, stock moves and shipment lines declare exclusive_min: 0; the others still rely on their hook, which only the public write surface reaches.

  • Declarative cross-field rules — no formula language yet for

"end_date > start_date" (visible_when handles conditional visibility, not validation). The general mechanism exists, though: a pre-write hook (below) expresses any cross-field or cross-collection rule in real code. A Salesforce-style declarative rule (formula + message) remains the ergonomic follow-on for the common cases.

  • Inline client feedback — the form pre-checks required; length/pattern

errors currently surface after a server round-trip, and messages are technical ("longer than max_length"). Friendlier, inline feedback is a UX polish item, not a safety gap.

Uniqueness — declared in the schema, enforced inside the write lock

{
  "name": "usage_events",
  "unique": [
    {"fields": ["event_id"], "scope": ["owner_id"]},
    {"fields": ["code"], "ignore_case": true, "message": "That code is already in use."}
  ],
  "fields": [ ... ]
}

Each entry says: no two records may hold the same fields values — within the same scope values, when a scope is given.

keymeaning
fieldsRequired. The key: one or more field names. With several, records collide only when all match.
scopeOptional. Field names the key is unique within ("per owner", "per bank account").
ignore_caseOptional, default false. Compare the fields values without regard to case.
messageOptional. The error text for a violation, in place of the generated sentence.

How two records are compared:

  • Values are compared trimmed. "evt-1" and "evt-1 " are one key.
  • A blank fields value means the record has no key and is exempt. Most

wallets have no gift-card code and a bank line from a CSV has no bank transaction id; uniqueness is a property of the keys that exist. Make the field required if every record must have one.

  • A blank scope value is an ordinary value. Two ownerless records with

the same key do collide. (Admin-token writes are not owner-stamped; if a blank scope were exempt, they could duplicate freely.)

  • ignore_case folds the fields values, not the scope.

Why this is a schema key and not a hook. A duplicate check in a pre-write hook reads the collection, finds nothing and allows the write — but hooks run before the write lock, so two overlapping requests both find nothing and both land. A handler or scheduled job that asks "have I done this already?" before writing has the same gap, and never reaches a hook at all. This is how one usage event was billed twice, one wallet top-up credited twice and one setting configured twice. unique is checked by object_records under the same lock that performs the append, so the second writer sees the first one's row. It applies to every writer: HTTP, MCP, handlers, the daemon, imports, seeds. There is no bypass flag.

What a violation looks like. Nothing is written and no change-log entry is made.

  • From object_records.create_collection_record / update_collection_record:

object_records.UniqueConstraintError (a ValueError), with .collection, .fields, .scope and .existing_id — the record that holds the key. A storage-level writer that must be idempotent catches it and treats it as "already done":

  try:
      object_records.create_collection_record("wallet_entries", entry, base_dir=base, actor=ACTOR)
  except object_records.UniqueConstraintError:
      return {"status": "already_posted"}   # the marker was used; post nothing
  • Over HTTP: 409 with "code": "unique_violation" and the constraint's

fields and scope. The id of the record that holds the key is not returned — the caller may not be allowed to read it.

Updates. An update is checked only for a key it changes. A record may keep its own key and change anything else.

Data that was already there. Declaring a constraint over a collection that already holds duplicates does not remove them and does not fail. The existing records stay and stay editable; no further holder of that key is admitted, and deleting one duplicate does not free a key another still holds. object_records.find_unique_violations(collection, base_dir=...) lists them ([{"fields", "scope", "values", "ids"}]) — run it before declaring a constraint, and merge or delete what it reports.

What is refused at schema load (a ValueError, so an unenforceable constraint never loads as "no constraint"): an entry that is not an object (a bare list of names is ambiguous — one compound key, or several?), unknown keys, id, a computed field, a store: extra field, a field named twice. A field does not have to be declared in fields to be constrained.

Cost. Collections without unique pay one cached schema lookup per write. A constrained collection keeps an in-memory index of who holds each key; it is built once (one pass over the cached rows) and then updated by each write, so a write costs a dictionary lookup, not a scan. Measured at 100,000 rows in append mode, three runs of 200 creates: 1.2–1.4 ms per create without a constraint, 1.25–1.5 ms with one; the one write that builds the index took about 170 ms longer, most of it reading the file because the collection was cold. The index is rebuilt after anything else changes the file — another process's write, a compaction, a restore — so several processes taking turns writing one collection each pay a rebuild per turn. A collection too large for the records cache still holds its keys in memory.

What it does not do. It compares stored values for equality. It cannot express "one received payment per order" (a conditional key) or "amounts must not exceed a ceiling" (a sum). unique is not exposed by /api/schema.

A ceiling is not a unique key. "Payments must not exceed the invoice", "refunds must not exceed the payment" are sums over rows that several writers add to, with inputs in other collections. payments.v3 and refunds.v3 approximated it with a per-parent sequence number declared unique (each hooked writer stamped the next number from the read it summed), which serialized writers that came through the hook and nobody else: a webhook's payment carried no number, an admin's edit kept its old one, and an invoice line cut in the meantime was not seen. Declare a ceiling as a locked check instead; it holds for every writer and for inputs in other collections. The v3 columns invoice_seq / payment_seq remain as data, unconstrained and no longer stamped.

Locked when settled — declared in the schema, enforced inside the write lock

{
  "name": "time_logs",
  "locked_when": [
    {"when": {"status": ["approved", "billed"]},
     "except": ["status", "invoice_id", "notes"],
     "message": "Approved time is settled. Correct it with a new entry."}
  ],
  "fields": [ ... ]
}

Each rule says: while the stored record has when, an update may change only the except fields, and the record cannot be deleted. Or, written the other way round with fields, an update may change anything but the listed fields (below).

keymeaning
whenRequired, 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).
exceptOptional, 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.
fieldsOptional, 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).
allow_deleteOptional, default false. true freezes the fields but still lets the record be deleted.
messageOptional. The error text for a refusal, in place of the generated sentence.

Which form to use: except is the safe default for a record that is money or evidence (a new field is frozen until someone decides otherwise). fields is for a record that is mostly still alive once settled, where only a few fields are the settled fact:

{"when": {"status": ["won", "lost"]},
 "fields": ["title", "description", "amount_cents"],
 "message": "A settled deal's title, description and amount are frozen."}

The two forms are judged the same way in everything below, inside the same lock, for every writer; only the question "is this field frozen?" differs. allow_delete is independent of the form and defaults to false: a settled record cannot be deleted whichever fields are frozen. A refusal is 409 record_locked with fields naming the frozen fields the write tried to change ([] for a delete), and a message becomes its error.

How a write is judged:

  • By the stored record, not by what the write would produce. The write

that moves a draft to approved may change anything — the stored row is a draft. A write to an approved row may change only the except fields, even if it also moves the row out of approved: unlocking and editing take two writes.

  • A change is a submitted field whose value would differ. Sending a frozen

field back unchanged is fine (a form posts everything it shows).

  • Computed and read-only fields are never frozen. A client cannot submit

either; what changes them is the server — a rollup recomputed on a posted journal, a trusted writer's stamp.

  • Every matching rule applies, and each can only restrict.
  • Nobody is exempt: not the owner, not an admin, not the admin token, not

a storage-level writer, and there is no bypass argument. A trusted writer that must touch a settled record (the invoice generator moving approved to billed and stamping invoice_id) does it through the except fields.

  • Creates are not affected: a record may be created already in the state.

The state field decides whether the lock can be left. Put the field that when tests in except and the transitions map decides which moves out of the state are legal; leave it out and the state is terminal.

Why this is a schema key and not a hook. Three hooks each carried their own _ALLOWED_AFTER_… set (time logs, expenses, scans), which is the point logic-decisions.md #5 said to promote the pattern. They also shared three gaps a hook cannot close: the hook did not run on delete, so the frozen record could be removed; the hook reads the record before the write lock, so an edit that overlaps the approval is checked against the draft and written onto the approved row; and storage-level writers never reach a hook. locked_when is checked by object_records against the row read under the lock.

What a refusal looks like. Nothing is written and no change-log entry is made.

  • From object_records.update_collection_record / delete_collection_record:

object_records.RecordLockedError (a ValueError), with .collection, .record_id, .action ("update" or "delete"), .fields (the frozen fields the update tried to change; [] for a delete) and .when.

  • Over HTTP: 409 with "code": "record_locked" and fields.

What it does not do. It reads one record. It cannot freeze a journal's lines because the journal is posted — that rule is about another collection, and stays in the line's hook (hook_fin_journal_lines, where it is advisory against a concurrent post, and where it has to ask about the journal a line is leaving as well as the one it joins: a hook that read only the new journal_id let a line be moved out of a posted journal). Retention pruning (prune_collection_records) rewrites the file rather than deleting row by row, so it cannot apply the rule per record; it refuses a collection that declares locked_when outright (its one caller ages out page_views, which declares none). locked_when is not exposed by /api/schema, so the generated form does not yet grey out frozen fields; it learns from the 409.

Locked checks — a decision across collections, made inside the write lock

{
  "name": "payments",
  "locked_checks": [
    {"name": "overpayment",
     "object": "hook_payments",
     "function": "LOCKED_CHECK",
     "reads": ["invoices", "invoice_lines", "refunds", "app_settings"],
     "lock": "ledger",
     "on": {"create": true, "update": ["amount_cents", "invoice_id", "status"], "delete": true}}
  ],
  "fields": [ ... ]
}

Each entry says: before any write that on selects lands in this collection, call function of the installed object object, holding the named lock, and do not write unless it allows. unique and locked_when are rules about one collection; a locked check is for the rule that needs rows from other collections — a sum against a ceiling ("payments on an invoice do not exceed what the invoice is worth"), a headroom ("refunds do not exceed the payment"), a parent that must still be in a state.

keymeaning
objectRequired. The installed object that ships the check (usually the collection's hook object).
functionOptional, 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.
nameOptional, default the object id. Named in errors (check) and in the 409. Unique within the schema.
readsCollections 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.
lockOptional, 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).
onOptional, 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.

Unknown keys, a misspelled collection in reads, an on that selects nothing: refused at schema load (a ValueError), so a check that cannot be enforced never loads as "no check". Not exposed by /api/schema.

Why a declaration and a function, not a declarative sum. The owner prefers configuration, and "ceilings": [{"sum": ..., "group_by": ..., "max_from": ...}] was the first candidate. It cannot state the ceilings that ship: the overpayment ceiling is the smaller of the invoice's stamped total and what its lines say (subtotal by object_lines, plus the larger of line and document tax), and the refund headroom is the payment's amount net of the other refunds, refused outright for a bounced payment. A declarative form would need an expression language to say that, or it would change what the ceiling is computed from. So the locking is declared — which collections, which lock, which writes — and the verdict is a named, read-only function the package ships beside its hook, sharing the hook's code so the early answer and the locked answer cannot drift.

When it runs. object_records.create/update/delete_collection_record call it for every writer — HTTP and MCP, actions, handlers, webhooks, the daemon, imports (object_import), materialize, merged seeds — after schema validation, transitions, locked_when and unique, and before anything is written. There is no bypass argument. Its request:

keycreateupdatedelete
recordthe row to be storedthe stored row with the changes appliedthe row being removed
existingNonethe stored row, read under the lockthe same row
collection, action, check, reads, base_dir

There is no subject: a locked check states a fact about the data, not a permission. Who may do what stays in the hook.

What it answers. None (or {}) allows. {"error": "...", "status": 409} refuses (any 4xx; the default is 409); {"error": ..., "status": 503} says it could not decide. Anything else is a broken check.

outcomeCheckRefusedError .status / .codeover HTTP
the check refused409 (or its 4xx) / check_refused409 {"code": "check_refused", "check": name, "error": its sentence}
it said 503, raised, is not installed, or its lock was not free within DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS (default 30)503 / check_unavailable503 — retry
it answered outside the contract, or tried to write or to run another object500 / check_failed500

Nothing is written and no change-log entry is made in any of these. CheckRefusedError is a ValueError (like UniqueConstraintError), with .collection, .check, .status, .code. A storage-level writer that records money which has already moved must decide what a refusal means for it — the Stripe webhook answers 409 with needs_attention (not acknowledged, so Stripe redelivers once a person makes room); checkout's gift-card payment reverses the wallet debit it just made.

What a check may do. Read, through object_records, and decide. It runs holding locks other writers wait on, so:

  • it may not write (create/update/delete_collection_record, retention)

or run another object (object_execution.execute_object) — both raise LockedCheckWriteError, answered 500, nothing written;

  • it must fail closed on a read it cannot make: return 503, or let the

exception escape (also 503) — never treat "unreadable" as "nothing there";

  • it should be quick: its cost is paid inside the lock by every writer of

every collection the lock covers. A check that hangs makes the others time out with 503 after DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS rather than wait forever; the platform does not interrupt the check itself.

The lock, and why it cannot deadlock. A check lock is an flock on <data>/.locks/<lock>.lock, so it holds across threads and processes like the collection file locks. The rules:

  1. A write plans its locks before taking any: every lock whose check is

declared on, or reads, the collection it writes — plus those of the collections its rollups refresh, because that refresh writes them while this write's file lock is held.

  1. It takes those check locks in sorted order, then its collection file

lock. A lock this thread already holds is not taken again (a rollup refresh nested in a write finds its locks held).

  1. A thread never waits for a check lock while holding a file lock. If a

nested write needs one it does not hold (only possible if the schemas changed between the outer write's plan and the inner write), it gets CheckLockOrderError instead; a rollup refresh is best-effort and skips.

So a thread waiting for a check lock holds only check locks that sort before it and no file lock, and a thread waiting for a file lock already holds every check lock it will ever take in that write. Waits among check locks follow one total order (no cycle); no thread holding a file lock waits on a check lock (no cycle through both kinds); waits among file locks are the existing child → rollup-parent order, unchanged. Multiple named locks are supported and tested (a write to a collection two checks read takes both).

What the lock buys and costs: every write to a covered collection waits for any other covered write in flight — for payments that is every write to payments, refunds, invoices, invoice lines and settings, one at a time, for the length of one check and one append. It is one lock per name, not one per invoice; the ledger's writes are few and short, and a per-key lock would need the key of every input (a line's invoice, a refund's payment's invoice, both sides of a re-point) to be planned before the write, which a name does not.

Nobody routes around it.

  • Every storage write goes through the three functions above.
  • Retention (prune_collection_records) refuses a collection a check is

declared on or reads, as it refuses one with locked_when.

  • A package's seed into a collection that already has records is merged row

by row through create_collection_record (checked, as before); a fresh seed is normally a byte copy, but into a collection that declares a locked check it is written row by row as well, and refused rows are listed in the install result (code: check_refused).

  • compact_collection rewrites a file without changing what it holds and

takes no check lock. A backup restore replaces files wholesale, as it does for unique and locked_when: it is an operator's act on a stopped or quiet server, not a writer.

  • A server running code from before this key ignores it (unknown root keys

are dropped at schema load), as it would ignore unique.

Cost. Collections no check covers pay one look at the schema index (already made for rollups; shared). A covered write pays one flock round trip (open, lock, unlock, close) and waits for other covered writes; a write the check is selected for also pays the check's reads, inside the lock. Measured on one machine, append mode, storage-level creates, median of 200 (50 at 100,000 rows); "rows" is the number of payments, with a tenth as many invoices and refunds and a fifth as many invoice lines:

write1,000 rows: without / with the declaration100,000 rows: without / with
a collection nothing covers (vs 246b3e5, before the mechanism)0.68 / 0.68 ms2.50 / 2.50 ms
invoice_lines create (takes the ledger lock, not checked)1.27 / 1.32 ms41.8 / 39.3 ms
payments create (takes the lock, runs overpayment)2.37 / 3.06 ms133.8 / 143.4 ms

The check costs about 0.7 ms at 1,000 payments and 10 ms at 100,000 (it reads one invoice's payments, refunds and lines through read_collection_records_where; the field index it uses is rebuilt after each write to the collection). Most of a payment write at 100,000 rows is not the check: it is the invoices rollup refresh, which reads every payment, and was there before.

Shipped: payments.overpayment (hook_payments.LOCKED_CHECK) and refunds.refundable (hook_refunds.LOCKED_CHECK), both on the ledger lock; fin_journals.closed_period and fin_journal_lines.closed_period (hook_fin_journals / hook_fin_journal_lines.LOCKED_CHECK) on the fin_periods lock, reading fin_closed_periods -- nothing is written, edited, moved or deleted in a closed period by any writer. That rule had lived in the two hooks, and every journal composer writes below them, so a payment recorded after its month was closed posted into the closed month. What a composer does instead is object_finance. compose_posted_journal's policy: the first open day after the period, with occurred_on and period_review=pending saying so (tests/test_closed_period_composers.py). Tests: tests/test_locked_checks.py (the mechanism, on a toy package: every writer, every failure mode, the lock order, six processes writing every covered collection in random order), tests/test_money_gates_locked_ceilings.py and tests/test_money_gates_ceiling_races.py (the money). Also expenses.category_stamps (hook_expenses, reading expense_categories: an expense's stamped requirements and deductible share must be what its category says when it is created, recategorised, submitted or approved), mileage_logs.mileage_rules (hook_mileage_logs, reading mileage_rates and vehicles and the other trips on the vehicle: no backwards or overlapping odometer readings, no approval at a rate other than the year's) and fringe_benefits.fringe_period; see expense-substantiation.md.

Pre-write hooks — code inside the write path

For rules the schema can't express, a collection declares a hook object:

{ "name": "fin_journals", "hooks": { "before_write": "hook_fin_journals" } }

The object's BEFORE_WRITE(request) runs synchronously inside the generic HTTP write path — after permission checks, before persist — for every public create, update and delete on that collection. request carries {collection, action, record, existing, changes, subject}. It returns None to allow, {"error": "...", "status": 4xx} to reject with its own message, or {"record": {...}} to transform (the transformed record still passes full schema validation, and can never touch id, owner_id, or read-only/computed fields).

What the request holds depends on action:

actionexistingrecordchangesmay answer
"create"Nonethe row to be writtenthe same rowallow, reject, transform
"update"the stored row before this writethat row with the caller's changes appliedonly what the caller sentallow, reject, transform
"delete"the row about to be removedthe same row{}allow, reject

subject is {"user_id": ..., "roles": [...]} in all three.

Branch on action first. A hook is called for all three and every rule in it has to say which it is about. The delete path ran no hook until a review found that "approved time is frozen" stopped an edit and not a DELETE; when deletes started arriving, two shipped hooks that decided "is this being approved?" from the record's status mistook the removal of an approved row for an approval, and answered with the self-approval refusal. A hook that has no rule about deletes starts with if request["action"] not in ("create", "update"): return None.

A delete cannot be transformed — there is nothing to persist — so a hook that answers one with {"record": ...} is treated as broken (500, nothing deleted), like any other answer outside the contract.

existing is read before the write lock is taken, so everything a hook checks is advisory against a concurrent writer: two requests can both pass the same hook and both write. A hook is the right place for a rule about one request; it cannot make a rule hold under a race. "This value appears once" is declared as unique (above) and enforced inside the lock; "this sum stays under what another collection says" is a locked_checks entry (above), whose function the hook can share so its early answer and the locked one agree; "this record has not changed since I read it" is If-Match / expected_rev.

The contract is deliberately strict:

  • Fail closed — a declared hook that is missing, raises, or returns a

non-contract shape rejects the write. A gate that silently passes on error is not a gate.

  • Every surface that writes on a caller's behalf — the collection routes,

MCP's record tools (which call them), and the file routes (/api/files, WebDAV), which create and delete files records through their own helpers and ask the files hook the same way.

  • A gate's own reads fail closed too. A hook that reads other records to

decide must not treat "I could not read" as "nothing there". Five shipped gates did, and with the ledger unreadable the duplicate gate passed the duplicate. object_records.read_collection_records raises on a failed read; what a gate may fold to "no rows" is only a collection that is not installed, which is a fact rather than an unknown:

  try:
      rows = object_records.read_collection_records("refunds", base_dir=base)
  except object_collections.CollectionNotFoundError:
      rows = []                      # app-payments' refunds not installed: none exist
  except Exception:
      return {"error": "Refund history is unreadable; refusing to record "
                       "against an unknown history.", "status": 503}

A hook that simply lets the exception escape is also closed (500 hook_failed, no write); returning its own 503 just says why. The shared readers gates call take strict=True for the same behaviour — object_banking.existing_line_keys, is_duplicate_line, find_import_by_file_hash, previous_import, run_gates, and object_finance.closed_period_for — and are lenient by default only until each caller is moved over. Moved so far: both bank statement importers (every gate read strict; an import that fails part-way is resumed by re-importing the file), action_reverse_journal's closed-period check, and the hooks that gate on these reads (hook_bank_lines, hook_fin_journals, hook_fin_journal_lines).

The server relays a hook's status when it is a 4xx or 503 (_apply_before_write_hook); anything else a refusing hook returns reaches the client as 400. So "I could not read" arrives as something to retry, not as a bad request, and a hook still cannot call a refused write a success or a server fault of its own.

  • After permissions — a denied subject never reaches the hook.
  • Opt-in per collection — collections without hooks pay one cached dict

lookup; the original latency concern that deferred this feature (event-hooks-decisions.md) stays bounded.

  • Public surface only — trusted server-side writers (the daemon,

migrations, seed-merge) call the storage layer directly and bypass hooks.

This is what keeps the generative form working when custom logic arrives: the form still POSTs to /collections/{c}/records; the rule lives server-side. First adopter: fin_journals refuses to post a journal whose lines don't balance — a cross-collection rule (it sums fin_journal_lines) no schema key could express.

Business logic — the automation substrate

Business rules run without per-app code through a set of declarative primitives, driven by a background daemon and the change log:

flowchart LR
    W["record write"] --> CL["change log"]
    CL --> DAEMON["daemon: poll triggers"]
    DAEMON --> NOTIFY["notify_rules → notification / email"]
    DAEMON --> TARGET["trigger object → target object"]
    W --> TRANS["transition guards (flow: when clauses)"]
    SCHED["schedule"] --> DAEMON
    DAEMON --> COMPUTE["computed / materialize fields"]
    DAEMON --> CONN["connectors → external systems + reconcile"]
  • Transitions with guards — a flow/transitions map is a conditional

state machine; a when clause gates whether a move is allowed. The board's drag and every status write run through it.

  • notify_rules — declarative "a record changed → send a notification /

email." Data, not code.

  • Trigger → target objects — the daemon polls trigger objects and executes

target objects: the event-handler path (see runtime-contract.md and event-hooks-decisions.md).

  • Computed / materialized fields — derived values (type: computed,

materialize_definitions).

  • Connectors — external side effects expressed as desired-state records

with a reconcile pass.

  • Scheduled passes — the daemon runs periodic work (compaction,

auto-transitions).

This is the same family as Salesforce flows/validation-rules, Hasura event triggers, and Directus Flows — declarative automation over a data store, here on plain-text records.

Formula & rollup fields — shipped

The spreadsheet feature, on collections. A type: computed field declares either a formula over sibling fields or a rollup over a child collection:

{"name": "full_name", "type": "computed",
 "formula": "first_name + \" \" + last_name"}

{"name": "debit_total_cents", "type": "computed",
 "rollup": {"collection": "fin_journal_lines", "fk_field": "journal_id",
            "op": "sum", "field": "debit_cents"}}

Values are materialized on write at the storage layer — stored in the TSV, recomputed whenever inputs change (formulas on writes of the record itself; rollups when source-collection records are created, updated, or deleted — single-hop, loop-guarded). Because the value is stored, every surface works with zero changes: lists, tables, detail, search, field=value filters, sort, CSV, backups — and realtime falls out free: edit a journal line and the journal's totals update live in every open browser. rollup.op is sum | count | min | max | avg, with an optional equality where. The formula language is a tiny safe expression grammar (fields, strings, numbers, + - * /, parens, round(x[, places]) and floor(x) — never Python eval). Numbers are exact: whole numbers are integers of any size, fractions are Decimal, never float. A formula over whole numbers only fills an integer field, so a division in it is rounded half-up once at the end (1234 * 825 / 10000 is 102); one with a fractional operand keeps its fraction. Rollups sum the same way. A broken formula stores an empty value and never fails the write — derived values are non-authoritative, the opposite posture of hooks. Definition changes are backfilled explicitly with object_records.recompute_computed_fields(collection) (install step, admin action, or cron — never a runtime loop).

Finding a written collection's rollup parents happens after the row has landed, so it is best-effort like the refresh: a schema file in <data>/schemas/ that does not load (invalid JSON, a name outside the schema-name rules) is skipped, exactly as the check-lock plan skips it, and the write is answered as written. Writes to that file's own collection are refused before anything is written, since its schema is what they validate against. A rollup the broken file declares is not refreshed while it is broken — nobody can read the declaration — so its parent rows are stale until the file is fixed and then either a child of that parent is written again (the refresh recomputes from every child) or recompute_computed_fields(<parent>) is run. The broken file itself is what to look for: GET /schemas/<name> answers its error.

Declarative validation rules (cross-field formula + message) remain the natural next sugar over the hook.

Related

of rule goes (the placement flowchart) with worked examples; and logic-decisions.md, the doctrines behind placements.

schedules, and event contracts.

are shaped the way they are.

immutable substrate for audit-shaped data (journals, stock moves).