Repository navigation
·
2 commits
to main
since this release
Immutable
release. Only release title and notes can be modified.
[0.14.0] - 2026-11-19
Breaking
- ZigBase now requires Zig 0.17.1 (0.13.0 required Zig 0.16.0). Building with any other version fails at compile time with a required-versus-actual message. To upgrade an app: install Zig 0.17.1 (
mise install, or prefix commands withmise exec zig@0.17.1 --), set.minimum_zig_version = "0.17.1"in yourbuild.zig.zon, re-fetch ZigBase withzig fetch --save, and port your own code to the Zig 0.17.1 standard library (the docs and examples show the new spellings). Optimization modes are now spelleddebug,safe,fastandsmall(-Doptimize=safe, and the same for-Dbench-optimize). ZigBase's own dependencies move with it:zapis now pinned to thevalthon/zapfork, which ports upstream v0.10.6 to Zig 0.17.1 and carries the descriptor-safety fix described under Fixes, and C declarations come from a pinned officialtranslate-cpackage. Both resolve through the ZigBase dependency, so your build file needs no new dependency or C-translation step; a package that vendors its dependencies must refresh them. - Custom routes are checked at compile time against one literal route grammar, shared by dispatch and OpenAPI. Paths must be canonical absolute ASCII paths without trailing or repeated slashes, dot segments or percent escapes; capture names must be distinct identifiers; methods must be concrete (not
.UNKNOWN); andpath_secret.parammust name an actual capture. Every enabled engine, admin, feature-state, WebSocket and SSE route is reserved, so a custom or feature route can no longer shadow one: move a colliding route. Explicit route.names must be Zig identifiers, and no explicit or derived name may collide with another route or a built-in operation. Derived names sanitize URI punctuation and leading digits (/robots.txtbecomesrobotsTxt,/api/2fa/verifybecomes_2faVerify); set.nameonly to resolve a genuine collision or an otherwise empty derived name. - A field whose name the engine reserves (
id,created,updated,email,username,passwordHash,tokenKey,verified,token_epoch, case-insensitively) is now refused on abaseorviewcollection instead of being silently dropped:POST/PATCH /api/collectionsanswer400 validation_reserved_name, andzigbase schema applyrefuses the document. Before,schema applyexited 0 with the field quietly missing, and a followingimportdiscarded that column's values while reporting success (#382). Rename the field.authcollections are unchanged: their injected system fields are still ignored on input, so a client can write back a collection document it just read. - Comptime
.indexesis authoritative on startup, including its empty default: metadata-declared indexes absent from code are removed and each DDL operation is logged. Failed builds or conflicting external names refuse startup with the collection and index identified. Equivalent ordinary migration-created indexes are adopted; unsupported external definitions require an explicit migration. - PostgreSQL generated search columns without the engine ownership comment now refuse startup with
Conflictinstead of being automatically dropped and rebuilt. Inspect and explicitly migrate legacy or application-owned objects before retrying. - On a tenant-owned base collection (
tenant_fieldset), a field markedunique(other than the tenant field itself) is now unique per tenant, enforced as a compositeUNIQUE (<tenant_field>, <field>)instead of across the whole table (#498). A table-wide unique answered409whenever any tenant held a value, so one request per guess told a member of one tenant what another tenant had stored, and any tenant could claim a value for every other tenant. To keep a value unique across all tenants, declare a unique index on it (.indexes = .{ .{ .name = "...", .fields = .{"slug"}, .unique = true } }). Existing deployments converge at startup, for.collectionsand API-created collections alike: PostgreSQL swaps the constraints in place, and SQLite rebuilds each affected table once, keeping its rows and migration-created indexes and triggers (a table the rebuild cannot reproduce is refused at startup; see the SQLite rebuild entry under Fixes).zigbase importupserts on such a field match tenant and key together, so they never select another tenant's row, and each such row must carry a non-empty tenant value. OpenAPI marks each unique field's scope (x-zigbase-unique-scope:globalortenant), and the admin schema editor shows it beside the unique checkbox. Auth collections are not converged: their identity fields keep global partial unique indexes over non-empty values, declared unique fields stay global, and the default["email"]identity does not gain username uniqueness. - Collection files now live under an engine-owned physical namespace that stays reserved after the collection is renamed or deleted. Creating a collection under a reserved prefix, including case variants on every backend (to protect case-insensitive local filesystems), fails with a conflict instead of adopting leftover files; reservations are not reclaimed automatically. Custom storage callbacks receive the physical namespace, which is not necessarily the current collection name; public URLs and hooks keep using logical names. On upgrade, existing collections keep their exact prefixes, and ambiguous legacy case aliases are refused for explicit operator repair.
- Record-file uploads write bytes before acquiring the database writer, so storage plugins must not assume the destination record exists during
put. UploadPOSTreturns409if the collection changes during the transfer; uploadPATCHalso returns409if the record changes, and requires update access to the existing row before the transfer as well as to the updated row before commit. - Declared scheduler intervals of zero minutes are rejected at compile time for every job; a reactive handler may still request an immediate next tick explicitly.
Features
- Comptime-configurable two-factor authentication with TOTP, WebAuthn, restricted authentication attempts, recovery codes, and application policy hooks for user and group requirements. Clients handle pending authentication, and the golfsim example shows TOTP enrollment, login and recovery.
- The admin UI groups auth collections under Users and ordinary collections under Data collections; account links keep the selected auth collection (legacy record URLs included), and collection settings link straight to account management. User create/edit forms cover schema-defined profile fields (validation, JSON and rich-text editors, relations, multiple selections and file uploads) alongside credentials, with labelled controls, internationalized email addresses and the server's UTF-8 byte-length password policy. Edits submit only changed fields, so concurrent profile updates are preserved and credentials can be reset on legacy rows missing required profile values.
- Opt-in comptime HTTP admission limits (
.admission.max_requests): immediate503overload responses withRetry-After, and superuser-only, process-local saturation diagnostics at/api/admission/stats. Builds without it retain no counters or request checks, and theGET /api/healthliveness probe stays available while shedding.max_requestsand the reportedlimitare optional (?u32); omitmax_requestsfor no HTTP cap, and stats reportlimit: null. The TypeScript, Dart, Python (sync and async) and Kotlin SDKs retry recognized overload responses within their existing retry budget and honor numericRetry-After; generic or malformed503s are not retried, and raw requests stay single-attempt. - Opt-in coordinated admission (
-Dcoordinated-admission=true) shares one process-local budget across synchronous HTTP requests, queued and running memory jobs (includingapp.submit) and serial durable poll batches..admission.max_workcaps the work count;.admission.max_job_bytes, usable without an HTTP cap, caps retained memory-job payload and name bytes across queued, running and retried tasks. Saturated requests get the overload response, saturated job submissions returnerror.QueueFull, and saturated durable workers leave jobs pending without spending attempts or rate tokens. Diagnostics and the offlineresourcesreport show both budgets. Pre-enqueue serialization, handler allocations and total RSS are not capped. - Configure lazy memory-job and
app.submitworkers with.pools.memory_jobs(1–64), independently of scheduler workers. Resource profiles select 1, 4 or 8 workers; omitting both keeps four. - Opt-in comptime resource profiles (
minimal,balanced,throughput) select transparent pool defaults with explicit overrides. The read-onlyresources --jsoncommand reports the compiled settings (admission, retained-reader capacity, SQLite soft cache targets, scheduler and memory-worker stack sizes, worker counts, resumable-upload staging ceilings) without opening a database or reading deployment secrets, and lists what it excludes rather than estimating total memory. - A dev-tools
tunecommand compares supplied workload measurements against explicit memory and latency budgets, with freshness and context checks and deterministic recommendations. A Linux measurement helper provides a reproducible local health-workload example. - Tune the shared WebSocket/SSE connection cap with comptime
.realtime.max_connections(positiveu32, default 10,000). Realtime stats andresources --jsonreport the configured cap; saturated upgrades are rejected without incrementing the reserved count. - Check opt-in application binary-size and allocation budgets with versioned performance reports; compatible benchmark timings are compared as advisory data, with no deployed runtime overhead.
- Opt-in query and performance workbench (
-Dquery-workbench=true; default builds retain no state or instrumentation). On SQLite it attributes queries to route templates, counts slow and repeated structural shapes, times finalized statements' prepare/step/reset/finalize calls, and offers bearer-superuser-only SELECT-shape plan inspection; on PostgreSQL it covers prepared executions with client-side exchange and lifecycle timing (no plan inspection). It also aggregates per-method/route-template timing (including SQL-free handlers, errors and authorization denials), HTTP outcome classes, database pool mutex waits and declared durable/scheduled job attribution. Every item is labelled with its backend and measurement semantics; SQL and parameter text, row data and job payloads are never captured, and all storage is fixed-capacity. - Opt-in comptime
.distributedcron and interval jobs share persisted schedules across instances of one database: expired leases are recovered, stale dispatcher completions are fenced, idle schedules poll through readers every 15 seconds, and the lease duration can be tuned without changing schedule identity.JobEvent.scheduled_atidentifies an occurrence stably across retries and recovery, andgenerationidentifies each claim attempt. - Bound retained durable queue rows and UTF-8 payload bytes with optional per-queue capacity, atomic SQLite/PostgreSQL admission, and bounded
ctx.queueCapacitysnapshots. Retry and terminal history hold capacity until deletion or GC. - Capture up to 1024 analytics events atomically with
ctx.trackBatch, reusing one writer acquisition and prepared statement. Actor and tenant values remain server-derived; nested batches respect the enclosing transaction. - Web Push messages can set the RFC 8030
Urgencyheader:zigbase.PushMessagehas an optionalurgencyfield (zigbase.PushUrgency:.very_low,.low,.normal,.high), honoured byctx.push().sendandctx.push().enqueue. Unset, the header is omitted (#484). zigbase.DisabledMailerPluginlets an app declare that it sends no mail: messages are dropped without logging recipients, bodies or tokens, anddoctor --productionreports the choice instead of a missing-mailer error.- Opt-in
zigbase.Idempotencyfor database-only custom operations on SQLite and PostgreSQL: receipts scoped by principal, operation and key, payload-conflict detection, current authorization on every replay, the mutation and its result committed atomically, and comptime retention, capacity and output budgets (strict capacity and fail-fast namespace locks on PostgreSQL).migrate-dbrefuses to copy a database whose source or target idempotency ledger is non-empty; drain operations and clean verified-expired receipts first. Golfsim demonstrates an authenticated idempotent cancellation route. - Opt-in (
-Drest-idempotency=true) retry receipts for authenticated JSON record create, update and delete sent with anIdempotency-Key, persisted atomically with the mutation on SQLite and PostgreSQL, with bounded retention and capacity, current authorization on replay, and an explicit refusal for unsupported operations. The TypeScript record and generated typed services accept anidempotencyKeyoption. - Opt-in record invalidation backfill for reconnecting clients.
-Drealtime-backfill=truekeeps a bounded, process-local SQLite store;-Ddurable-realtime=truejournals REST record changes transactionally on SQLite and PostgreSQL (a journal failure rolls back the write), so checkpoints survive restarts and work across instances.GET /api/realtime/backfillreturns id-only items under the caller's current authorization (deletes are checked per item against the deleted record's stored snapshot), with paginated, encrypted and authenticated checkpoints and409 resetRequiredwhen a gap cannot be filled.limitcounts only items the caller may see andhasNextis true only when another such item follows, so pages do not reveal other users' write volume; a durable request scans at most 4096 journal entries. Documented side channels remain: tenants share retention, so one tenant's write volume can forceresetRequiredon another's checkpoint, and response time grows with the entries scanned. Raw SQL,Datafacade writes and hook side-writes are not captured, and this is not historical-payload replay. - Opt-in (
-Dresumable-uploads=true), principal-bound resumable file uploads for existing records, with configurable session, memory, chunk and expiry budgets; authorization and field-size checks before payload reservation; and commit-time authorization through the normal file mutation path. Completed and failed acknowledgements hold their session slots until the original expiry; only receiving sessions can be cancelled. Sessions are process-local in RAM by default;-Ddurable-resumable-uploads=truewith.files.resumable.durable = truepersists them (SQLite with local storage) so receiving sessions and completion receipts survive a process restart under one owner, with fresh authorization and no uncertain hook replay. Both modes buffer fully; neither is streaming, cross-instance, or power-loss durable. The REST reference and protocol guide cover retry windows, quota sizing and shared-capacity fairness. - Opt into durable cleanup of replaced and deleted HTTP record files with
.files.cleanup_queue, using a declared durable queue for transactional enqueue, retries, physical-reference-safe replacement cleanup and guarded record-prefix deletion on local or S3 storage. - Opt-in ImageMagick thumbnail profiles (
-Dimage-thumbnails=true) for built-in local storage: PNG/JPEG/WebP output, contain/cover resizing, the file's own authorization, configurable process and admission limits, and theinvalid_imageandthumbnail_busyerror codes. Builds without it exclude thumbnail routes and subprocess support; no image codec is vendored or linked. - Large S3 objects are uploaded with multipart S3 uploads automatically, with a configurable threshold and part size, bounded retries, completion XML validation and abort cleanup. Request bodies are still fully buffered.
- Opt-in
-Dfile-inventory=trueadds read-onlyfiles inventoryreporting for local and S3 storage: bounded pages, page-level byte usage, and referenced/unreferenced-candidate/unknown classifications, accounting explicitly for concurrent and in-flight uploads. It refuses incompatible collection metadata before inspecting objects (run migrations after upgrading the binary; these commands never migrate), resolves unknown filesystem entry types, follows an operator-configured root symlink but no descendant links, and reports failures without stack traces. Storage plugins can offer it through an optionalinventorycapability without changing the four-method vtable. files reconcile(same flag) previews bounded orphan candidates and supports explicit offline deletion for built-in local storage with SQLite. Apply refuses while cooperating apps are running, locks database writes, and rechecks object identity, age and physical references before each unlink. S3, PostgreSQL and custom storage are refused; older or external writers must be stopped and the storage root dedicated to one database. Unknown metadata is retained; partial deletion failures exit nonzero and cannot roll back filesystem changes.- Explicit offline
Migrator.renameCollectionrenames a collection atomically, preserving collection, field and record ids, relations, indexes, search and persistent auth references. Files keep their physical namespace and upload/cleanup metadata follows the new name without moving stored objects. All processes must be stopped and compiled name references updated; old names get no URL or topic aliases. The rename refuses ambiguous or shadowed relations, destination search collisions, and dangling destination-name relation metadata or SQLite foreign keys, which must be repaired first. Renaming an auth collection rotates its signing keys and revokes sessions and challenges. - Consumer migration apply and rollback batches are coordinated across processes. On PostgreSQL they are coordinated across replicas, including non-transactional callbacks; this requires session-affine connections, and an unlock the session does not own fails with
MigrationLockSessionLost. On SQLite a permanent, nonblocking sidecar file lock makes a competing batch fail withMigrationBusybefore it reads the ledger or runs callbacks; retry once the active batch finishes. Per-migration commits are unchanged, an existing caller transaction is refused without being modified, and a callback that leaves a transaction open stops the batch at that migration. Migration status, rollback anddoctorshare the same coordinated ledger bootstrap. On SQLite, older or external writers and automatic provisioning still require a single leader. migrate preview --jsonlists the compiled consumer migration declarations offline, with explicit unknown pending state, SQL, effects and runtime reversibility.zigbase openapiwrites a deterministic, read-only OpenAPI 3.1.2 JSON document of live collection CRUD, built-in routes and typed or untyped custom routes, with honest access metadata, compile-time gates, redacted path-secret contracts, a fixed contract-format version, andx-zigbase-collection/x-zigbase-collection-typemarkers.--outreplaces the file atomically.zigbase routes --jsonlists the compiled application's registered built-in and custom routes and their redacted auth declarations without opening a database. Conditional routes follow the actual dispatch tables; static assets, individual admin endpoints and runtime authorization are outside its coverage.capabilities --jsonis a versioned offline catalog of agent-facing CLI operations, their output formats, side effects and required inputs (integer bounds as lossless decimal strings).diagnosticswraps doctor checks and failures in one versioned JSON document; ordinarydoctorNDJSON is unchanged.capabilities,diagnostics,routes,migrate previewandtuneare dev-tools verbs, omitted from-Ddev-tools=falsebuilds.serve wait --timeout-ms N --jsonwaits, up to a deadline, for a healthy tracked session (including unresponsive health probes), reportsready: trueon success, and distinguishes internal failures from deadline expiry.- Custom routes can use the exported local-file response helpers, Range/conditional planning and MIME lookup.
static_headerssets CSP (including multi-kilobyte generated policies) and per-path cache headers for embedded and directory static serving. zigbase import --preserve-timestampsis an operator-only, create-only mode that keeps validated sourcecreatedandupdatedvalues. Import manifest v2 adds an entry-localpreserveTimestampspolicy, so the two-pass importer can restore relation cycles between timestamped and timestamp-less collections.zigbase import --external-authsmigrates OAuth/OmniAuth provider linkage with the account, so a social-login user is not locked out after a migration. Each auth row may carryexternalAuths: [{"provider":…,"providerId":…}], written in one transaction with the record. The flag is off by default, requires an auth collection that already declares each named provider, refuses_superusers, is create-only, and fails on an already-linkedproviderIdrather than re-pointing an identity. Provider access and refresh tokens never migrate.externalAuthsis stripped from every client payload, so linkage can only be written through this offline import.- A supported offline PocketBase 0.39.11 migration workflow and the
zigbase-migrate-pocketbaseAgent Skill: durable inventory decisions, deterministic schema/auth/data/file bundles, bcrypt rehash-on-login continuity, preserved source timestamps, a pinned reference fixture and end-to-end parity coverage. - Official
zigbase-migrate-express,zigbase-migrate-laravelandzigbase-migrate-goAgent Skills and guides for discovery-driven re-platforming: source inventory (including Express middleware and persistence), durable endpoint mapping, deterministic import, supported bcrypt migration, parity replay, doctor review and rehearsed cutover and rollback. - The official
zigbase-migrate-rails-apiAgent Skill and guide re-platform a Rails API-only backend: an observed-versus-inferred source inventory, durable schema/endpoint/auth/side-effect decisions, deterministic NDJSON extraction that preserves ids, timestamps, relations, files and supported bcrypt credentials, OpenAPI reconciliation, parity replay covering success, validation-failure, unauthenticated and unauthorized cases, and a rehearsed cutover behind an explicit backend-only scope gate. - The offline
tools/rails/rails2zb.pyconverter and itstools/rails/export_source.rbmetadata extractor (Ruby 2.7 compatible) cover Rails inventory, durable decisions, deterministic extraction and Active Storage file installation; PostgreSQL sources are read through one credential-safe, repeatable-read, read-only snapshot. The converter refuses to emit what the target would discard: reserved column names, names that collide once_idis stripped, and tables, columns or attachments the target cannot accept are raised at inventory time for an explicitrenameoromitdecision, and impossible dates, orphan relations, duplicate or malformed auth emails and non-UTF-8 text stop the extraction rather than the import.report.jsonrecords what was dropped or relaxed, including every public access rule, and artifacts are replaced atomically. - The full-stack Rails migration skill and guide add a deterministic coordinator that reconciles the Rails backend inventory, ZigBase OpenAPI and replay evidence, and Zigapagos presentation handoffs into one versioned route map. Backend implementation, OpenAPI, access rules and replay are a hard gate before presentation conversion; presentation builds must be clean, with routes and HTML references resolving to emitted assets; auth journeys must match the observed Rails credential mechanism; and missing live OAuth credentials are a launch-verification gap rather than a backend blocker. Exit codes distinguish input failures from incomplete proof.
- The official
zigbase-zigapagos-fullstackAgent Skill and pairing guide cover building, testing and deploying a same-origin Zigapagos frontend with a custom ZigBase framework binary, including durable public-signup review and layered backend, transport and browser tests. - A rules-first app-design guide for humans and coding agents: turn user journeys into trust boundaries, choose box or framework mode, model relations without accidental denormalization, inventory every intentional public rule, place trusted behavior in the narrowest server seam, and choose the test boundary that proves each feature.
- A production deployment guide for systemd, Docker Compose, Fly and Railway: reverse-proxy TLS, persistent data and JWT secrets, the
doctor --productionship gate, backup/restore rehearsal, upgrades and rollback, and the custom-image Docker contract (a non-root/datamountpoint owned by uid/gid65532,servein the foreground, HTTP readiness and production doctor verified against the assembled image and named volume). - Python SDK: opt-in
request_keycancellation for async generic requests and individual collection reads, including generated typed clients. A newer request cancels older work and its retry waits; unkeyed requests gain no dependencies or tasks.
Fixes
- Stop the HTTP reactor from closing file descriptors it does not own. A stale poll event could close a descriptor the OS had already reissued, whether an outbound SMTP socket, a SQLite file or a replacement HTTP connection. The symptoms were an intermittent
BADFpanic in a queue worker, unexplained dropped connections, and connection resets and truncated pages during browser navigation. Fixed in the pinnedzapfork; no application change is required. - Realtime access rules now see the subscriber's auth collection in
@request.auth.collectionand the active account's role in@request.account.role. Both were empty for WebSocket and SSE subscribers, so rules such as@request.auth.collection = "users"denied every realtime event. Account scope is refreshed from current memberships for each delivery, so a demotion or membership removal stops protected events on open connections. Auth hooks (beforeAuthSuccess,onAuthand the refresh/logout hooks) now carry the user's resolved account scope too, soctx.can()there sees the same@request.account.*values as a REST request.@request.auth.collectionand multi-auth-collection rules are now documented. - A REST record delete now announces the rows its relation foreign keys change: realtime publishes a
deleteevent for every record removed bycascadeDelete(transitively), authorized per subscriber against that record's pre-delete state, and anupdateevent for every record whose single relation was set tonull;-Ddurable-realtimejournals both in the delete's transaction. Before, these rows changed silently. Announcing never fails the delete: above 1000 affected records, for a foreign key the engine cannot map to a row id (a composite or alternate-key reference from a migration), or for a cascaded row that cannot be decoded or journaled, the delete degrades to backfill invalidation andresetRequired. Record hooks do not run for these rows, and deletes through theDatafacade, raw SQL, migrations and TTL expiry still cascade without announcements (#489). - Realtime event-frame construction releases partially allocated channels and frames when allocation fails.
- Collections created or changed through the collections API or the admin UI get their full-text search index in the same transaction as the schema change. Before, only startup built it, so
?search=on a collection created over HTTP answered500until the next restart, and search-field changes left the index stale. Making a field searchable backfills existing rows; adding, removing or renaming a searchable field rebuilds the index; turning search off or deleting the collection drops it (including SQLite's<name>_ftsshadow table). A change whose index cannot be built fails as a whole, and a-Dfts5=falseSQLite build answers400to a searchable field instead of accepting one it would refuse at the next start (#507). - Additive searchable fields are reconciled after their physical columns exist. Search provisioning verifies catalog ownership before changing SQLite FTS5 or PostgreSQL search objects, so application data survives reserved-name collisions; PostgreSQL search rejects registry/schema shadows and temporary probe collisions, and destructive generated-column changes fail closed when user triggers may depend on them, without blocking unchanged search or missing-index repair. Reconciliation is transactional and still repairs proven engine indexes.
- SQLite
-Dvector=truebuilds:?vector=list queries no longer fail with500(no such function: vec_distance_cosine). Pooled reader connections now register sqlite-vec like the writer, and every SQLite connection is opened through one constructor (#488). - SQLite table rebuilds (startup convergence or a collections API update) no longer discard schema they do not own. A rebuild started from the stored definition, dropping migration-added columns and any migration-created index or trigger that did not survive the copy. It now refuses, before changing anything: a table with a column, constraint or foreign key the engine does not create; a view or trigger on another table that depends on it; a migration-created index, trigger or view that depends on a column being dropped or renamed, or that uses wildcard or positional dependencies when the column layout changes; an index a migration trigger uses through
INDEXED BY; and TEMP tables, views, indexes or triggers that shadow or attach to it. Collections API updates answer400naming the object and asking for an explicit migration. Engine indexes and triggers are recognised by their SQL and regenerated, every other index and trigger is restored as it was, and drops and table statements are qualified with themainschema so same-named TEMP objects are left alone (#498). - Index-only comptime schema changes are reconciled transactionally without rebuilding tables or removing migration-owned indexes. Declared-index lookups on SQLite ignore same-name triggers and stay in
main, leaving temporary same-name indexes alone. On PostgreSQL, declared indexes are looked up, dropped and recreated in the collection table's own schema, so a same-name index earlier insearch_pathis no longer mistaken for the collection's or dropped, and names over 63 bytes are matched by their truncated catalog name. - Startup provisioning applies safe select-option widening to existing databases without rebuilding tables. Select narrowing, single/multi-value changes and other field option or flag changes log an explicit-migration warning instead of being silently ignored. Concurrent startups planning the same definition converge without conflicts or repeated cache invalidation, and reordering select values alone leaves the stored definition unchanged.
- Adding or changing
.tenant_fieldon an existing collection in.collectionsis now persisted at startup. It was ignored, so the collection stayed unscoped while the startup log reported it as tenant-owned. - On PostgreSQL, updating a base collection through the API now adds or removes the unique constraint when a field's
uniqueflag changes; it used to change only the stored definition. Auth collections keep their previous update behavior. zigbase schema apply --dry-runruns the same validation as the real apply, so a rehearsal refuses exactly what a run refuses; before, an identifier-invalid field name (_draft), a reserved name, an unsatisfiable date range or an encrypted field withoutZIGBASE_FIELD_KEYpassed the dry run and failed the real one. Every problem is now reported at once, on stderr, with its error code (#383).zigbase schema applyis atomic across collections: all passes run in one transaction, so a document that fails on its fourth collection no longer leaves the first three applied, and the emittedappliedlist is empty on failure (#383). Freeing a non-injectedauthcollection no longer panics with an out-of-bounds slice when a document pairs an auth collection of fewer than six fields with a malformed one.- Access-rule field and relation references are validated before schema apply (including dry runs) and REST collection mutations, against the complete prospective schema, so forward relations and newly added fields work.
- Record
beforehooks (create, update, delete) keep the status and message of an explicitctx.failfor every 4xx or 5xx status the HTTP transport supports, and the field details ofctx.invalid; a supported status without a dedicated code (such as 422) usesbad_request. Other failures, including unnamed statuses such as 432, keep the generic400, and rejected writes still roll back. Hook 5xx responses invokeonErrorand the reporter backstop with phasebefore_hook, naming the collection, status and message. Hook messages and field details are copied before the hook returns, so no failure leaks into a later handler. - Unmapped 4xx statuses use
bad_requestconsistently in typed routes, routectx.failand auth-method failures. Auth-method failure messages with a named 4xx status that has no dedicated code (such as 422) now reach the client instead of becoming a generic500; 5xx and unnamed-status messages stay operator-only, logged and redacted from the response. - Preserve shared descendants in relation expansion, and release expanded records correctly with ordinary allocators, including after partial allocation failures.
- Oversized stateless and signed cursors are rejected with an actionable client error instead of being returned as an unusable continuation token.
- Empty SQLite prepared statements are rejected safely.
- Float fields normalize consistently across JSON and multipart saves, including finite JSON numbers beyond the integer range, with the same bounds and non-finite-value validation. Large finite numeric min/max schema options survive API parsing and schema JSON round trips; string and non-finite bounds stay invalid.
- Clearing a single select or relation in a multipart record update now clears the field instead of validating an empty option or target id. A single select that declares
""as an option keeps it as a value and is cleared withnull. - Native tenant membership resolution uses PostgreSQL parameter placeholders, including authorization inside mutation transactions.
- On PostgreSQL, deleting an auth-collection record over REST succeeds and removes its OAuth links; it answered
500and left the record in place (#519). superuser createworks on PostgreSQL. Failed insertions, including duplicate emails on either backend, exit nonzero instead of reporting success; existing operator passwords are preserved.- Built-in migrations are serialized across concurrent PostgreSQL startups, including fresh-ledger creation and applied-state rechecks; the transaction-scoped locks release on success, rollback and disconnect. SQLite also checks applied state under its writer lock.
- PostgreSQL: a connection whose effective
synchronous_commitisoff(set on the cluster, database or role) is raised tolocalfor ZigBase's session, with one startup warning, so an acknowledged session revoke, "log out everywhere" or mail enqueue is no longer undone by a PostgreSQL crash or power cut. Stronger settings are left alone.docs/postgres.mddocuments the durability requirement, thatfsync = offandfull_page_writes = offare not overridden, and the transaction-pooler caveat (#490). - PostgreSQL durable queues: enqueue, claim, completion, cancellation, reclaim and cleanup use PostgreSQL parameters and timestamps; workers lock and skip rows another instance has claimed; and an expired handler can no longer overwrite a newer claim's completion or retry state. Claims, reclaim sweeps (the poller's and the hourly
_queue_gc), retry scheduling and.ratewindows use the database server's clock instead of each host's, so an instance whose clock ran ahead no longer resets other instances' claims beforevisibility_timeout_sand runs their jobs twice (#491). Upgrade every coordinated instance together; older binaries still use their host clock. The docs now explain that a forward step of the database clock (the server's on PostgreSQL, the host's on SQLite) can expire durable claims and.distributedleases early; generation fencing still applies and delivery stays at-least-once (#492). - On PostgreSQL, mail suppression and bulk sends work:
POST /api/mail/webhooks/:providerandPOST /api/mail/unsubscribeno longer fail with500, sends with.mail.check_suppressionno longer error, andctx.mail().sendBulk,batchStatus,cancelBatchand themail_batch_itemqueue job run. - A correctly signed SES webhook whose
complaintorbouncefield is not a JSON object no longer crashes the server; it is accepted and suppresses nothing. - On PostgreSQL,
GET/POST /api/senders,POST /api/senders/:id/verify,GET /api/analytics/eventsandGET /api/analytics/rollups/:nameno longer answer500, and a rollup that has not run yet returns an emptyitemslist, as on SQLite. Event and rollup ordering and thesince/from/tofilters compare text bytewise, as on SQLite, whatever the database locale: the PostgreSQL-only migration0030_analytics_text_collationgives the text columns of_eventsand existing_rollup_*tables (found throughsearch_path) the"C"collation, locking those tables and rebuilding their indexes while it runs (1.1 s measured for 400,000 events) (#487). - Command mail delivery consistently returns
MailCommandFailedwhen the child closes its input before the whole message is written, including on an early zero exit; the child is still reaped. A successful write only confirms kernel buffering, so a zero-exit command must enforce its own delivery contract. - Scheduler delays (interval jobs, reactive
.after, retry backoff, durable worker polling and the.distributedpoll) run on the monotonic boot clock. Stepping the wall clock back no longer stops every job, durable queues included, for the length of the step, and stepping it forward no longer fires interval jobs early. Cron stays on the wall clock: after a forward step a job runs once, late, and after a backward step a per-process cron job never repeats a minute it already ran (.distributedcron follows the database clock and can repeat a minute after that clock steps back) (#493). UnderZIGBASE_FAKE_NOWonly cron times are frozen; interval, reactive and retry delays measure real elapsed time, so an interval job fires once its period has passed instead of never. - Schedulers with more than 256 jobs due at once leave the overflow eligible for the next tick instead of stranding it as running.
.pools.stack_sizeapplies to memory-job threads as documented, with the same 1 MiB floor as scheduler threads. Partial or failed thread startup logs the actual and requested counts, and contending workers park during startup instead of spinning.- SQLite applies its startup busy timeout before enabling WAL, so startup waits out short-lived readers of an existing rollback-journal database.
- Exact
GET /api/healthno longer parses or rejects a multipart request body; the liveness probe ignores bodies as documented. - S3 record cleanup follows every listing page, decodes XML-escaped keys, and rejects malformed or out-of-prefix results instead of silently leaving later pages behind.
- Failed uploads clean up the object whose PUT failed as well as earlier writes, covering partial writes and lost replies.
- Serve
.webmanifestasapplication/manifest+jsonand.icsastext/calendar. - The in-process test harness captures streamed file response bodies, following the live server's whole-file offset semantics.
- Passkey registration options are serialized safely when the relying-party display name contains quotes or control characters.
- Prevent intermittent admin sign-outs during rapid collection navigation or writes that overlap a session refresh.
- Admin record drawers load the collection's current definition when opened, including fields changed in another tab or through the API, and account drawers honor required profile fields and password-policy changes made while Users is open.
- Admin record drawers on non-auth collections, such as the built-in mail collections, no longer hide fields named
email,username,verifiedortoken_epoch. - Authentication settings accept an integer password minimum from 0 through 255 and keep a zero minimum when saved and reopened; invalid values sent to the collections API return a field error instead of silently falling back.
- TypeScript and Dart live lists escape filter control characters correctly, refetch field-to-field predicates they cannot evaluate locally, and fall back to a refetch, preserving the original query and server errors, when a server filter is outside the local parser's grammar.
- SDK single-flight token refresh holds across delayed unauthorized responses and overlapping token generations, including Python async cancellation recovery.
- Python SDK file-stream upload bodies survive authentication and overload retries.
- The golfsim webhook example follows
app.submitownership correctly, avoiding a leaked caller copy and a double-free of the queue-owned job name. - Cached build configuration tracks Git provenance, native-version headers and embedded asset inputs, so rebuilt binaries report the current commit and assets.
- Documentation corrections: OAuth state handling, WebAuthn creation options and flat
register/finishproofs, login timeout and browser encoding, trusted-route authorization, declared partial indexes and index reconciliation, and record-hook context; the auth, booking and abilities examples are now executable.
Changed
- Record list cursors bind the collection's identity, name and rename epoch, so no cursor survives a rename, even one that is later reversed. Cursors issued before this upgrade are rejected; discard them and restart pagination.
- Durable queue
.rateceilings are shared through database-backed, integer-second windows (migration0025_queue_rates; stop older workers before applying it). A claim and its rate charge commit atomically, restarting a process no longer resets the current window's budget, and idle polls do not rewrite the window. - Every booted app using built-in local storage holds one shared maintenance-lock descriptor until shutdown, even without file inventory or with
serve --ignore-lock; there is no per-request lock operation. The permanentstorage/.zigbase-maintenance.lockmust not be removed or replaced; inventory excludes it, and offlinefiles reconcilerequires its exclusive lease. - The file-serving database reader is released before
beforeServehooks and storage work, including original downloads, so a hook can acquire a reader even with a one-reader pool. doctor --productionreports exact@publiccreation on non-system auth collections as a warning instead of an inescapable error, so the documented open-signup flow can pass a tolerant production gate. Public writes on ordinary collections and system auth collections remain errors.- The
tools/replayrecorder (zb_replay) writes captures and findings atomically with private0600permissions, keeping the previous complete artifact when validation or serialization fails, and forwards only safe representation headers when a redirect leads to another origin. - The
zigbase.testingguidance explains Zig's misleadingfailed command: … --listen=-output (#261), which still occurs on Zig 0.17.1: a successful test process whose exit-time stderr is shown under a stale command label, not a runner race or crash. Check the exit status and the build summary, and usezigbase.addTest, whose shipped simple runner avoids the label while still failing on assertions, leaks, logged errors and signals. - The migration guide and its navigation label are now "Migrating an existing backend to ZigBase", distinguishing application re-platforming from ZigBase schema migrations and SQLite-to-PostgreSQL moves.
- The public website and all three example frontends moved from Astro/React to pinned Zigapagos (now 0.5.0). The site is refocused on ambitious applications, small-team leverage, Zig framework extensibility and explicit resource control, with equally visible direct-development and coding-agent paths; it publishes the design rationale and a prioritized engineering backlog, and ships a sitemap,
robots.txt,SoftwareApplicationJSON-LD and a heading order that never skips a level. - Golfsim's browser frontend uses its generated ZigBase client and record types, with schema-drift typechecking, SDK multipart handling, escaped file URLs and the existing cookie/CSRF authentication.
Performance
- Authenticated custom routes release their auth/tenant lookup reader before route guards and handlers run, so a handler's own reads no longer hold a second reader for the whole request. Authorization and request-owned identity/tenant data are unchanged.
Security
- Access rules no longer let an anonymous caller, or one whose session has expired, match rows through an
@request.auth.*comparison. The absent value was bound as an empty string, soowner ~ @request.auth.idcompiled toLIKE '%%'and allowed REST list, view, update and delete on every row with an owner;!=,>,=against rows with an empty owner, and the create rule@request.data.owner = @request.auth.idwith noownerin the body were affected the same way. An absent@request.auth.*,@request.account.idor@request.account.rolevalue now behaves like SQLNULL: every comparison with it is false, whatever the operator, and inside anin (…)list it matches nothing. The presence tests@request.auth.id != ""and@request.auth.id = ""keep their meaning (#505). servenow binds the host it is given.--http-host/ZIGBASE_HTTP_HOSTwas parsed, logged, recorded inserve.jsonand checked bydoctor, but never passed to the listener, so every server listened on all interfaces, including instances meant to stay on the documented127.0.0.1default behind a reverse proxy. Loopback is now the real default and0.0.0.0(or::) the deliberate opt-in; the official container image already setsZIGBASE_HTTP_HOST=0.0.0.0and is unaffected. A host this machine has no address for (a typo, another machine's address, an interface not yet up) now fails at boot, naming the address and the setting, instead of falling back to all interfaces.- A relation into a tenant-owned collection only accepts ids from the request's active account. On create and update, another account's id gets the same
400 validation_not_foundas a nonexistent id, for single and multi relations. A non-hidden field's update accepts the ids the row already stores and checks only the ids it adds; hidden fields check stored ids too, and a request without an active account cannot add links to empty-owner targets. The check sees values afterbefore_create/before_updatehooks, so a hook that links across accounts must write throughctx.records(). On PostgreSQL the source row stays locked while relation ids are authorized and validated. Before, the check confirmed that another tenant's record id existed, and a stored link let that tenant's own delete cascade to or clear the linking row. Superusers,crossTenantcontexts andctx.records()writes are not narrowed, and the target'sviewRuleis not applied, so a non-tenant target such asusersstays referenceable by id (#497). A newdoctorcheck,cross-tenant-relations, warns once per relation field about existing links from a tenant-owned row to another account's record (stored earlier, or by a superuser or server-side write), and about stored multi-relation values that are not a JSON id array; it leaves them in place, ignores rows with no tenant value, and reports only itself asskippedif its scan fails. - Realtime
deleteevents are authorized against the deleted record's stored values. Row-constrained subscribers (tenant members, ability holders, owners under rules such asowner = @request.auth.id) on collections with a relation field received no delete frames at all, and the server loggedrealtime: dropped delivery. Other subscribers were checked against a snapshot with emptycreated/updated, fixed-point numbers in decimal form and unencoded JSON scalars, so a rule such asprice < 100orcreated < "2026-01-01 00:00:00"could send a deleted record's id to someone not allowed to view it, or withhold it from someone who was. Multi-value and hidden fields are now evaluated with their stored values (hidden values stay on the server; delete frames remain id-only), abeforeDeletehook cannot change what decides, and the delete fails and rolls back if the stored values cannot be read. AviewRulethat traverses a relation (owner.team = …) is still not evaluated for deletes. This applies to SSE and WebSocket on SQLite and PostgreSQL (#486). - A queued realtime record event whose collection is removed before delivery is dropped and logged. It used to be forwarded as a custom-topic message, record body included, to any subscriber allowed on a topic of that name (#486).
- Client relation filters and sorts through targets with restricted view policies or TTL are rejected, including in realtime subscription filters. Trusted access rules and server-authored
Ctxqueries keep private traversal; server code that forwards untrusted filters can opt into client-query validation. - Realtime subscription filters may not use hidden fields, closing a boolean oracle over fields omitted from client records. An invalid subscription filter gets an immediate error without replacing valid subscriptions; delivery checks remain in place.
- OAuth identity links and passkey enrollment are bound to their canonical auth collection, and passkey registration challenges to the authenticated account.
- Auth identity indexes are verified before they are trusted, on SQLite and PostgreSQL. A same-name object that is not the engine's unique index over non-empty values of the identity field, or a temporary table or index shadowing the collection or index name, no longer stands in for identity uniqueness: collection create/update, auth-options updates, rename,
migrate-dbimport (including existing tables under--force) and startup refuse it and leave it unmodified (REST400naming the collection, field and index), and startup restores a missing identity index. On SQLite the identity column must keep the defaultBINARYcollation; a column a migration declaredCOLLATE NOCASE(or another collation) is refused, because login and uniqueness would compare differently, so declare a.nocaseunique index for case-insensitive identities. SQLite recognises only a narrow predicate spelling, so a logically equivalent hand-written index may be refused (see KNOWN_LIMITATIONS.md). - On SQLite,
?search=no longer ranks with FTS5bm25, whose corpus statistics span every tenant's rows, so the order of one tenant's results could reveal whether another tenant's text contained a word (#495). Results are ranked by a row-local score (zb_rank: per-term hit counts normalized by row length), and ties are broken by recordidon both backends. Expect the relevance order of some SQLite searches to change; the matched rows are unchanged. The formula is in the search guide's Ranking section.
Internal
- Repository agent test tooling: a trusted-checkout wrapper with a static allowlisted pytest inventory, exact module/function execution, shared output limits, process-group deadlines and JSON outcomes; bounded changed-file selection with curated dependency rules; and TypeScript (pinned Node 24, two workers) and Python SDK unit-suite selectors. It makes no full-suite coverage claim.
- Agent evaluation: a provider-neutral runner (strict JSON-argv execution, isolated workspaces, explicit environment passthrough, bounded transcripts, process-group timeout cleanup, interrupt-safe startup); deterministic graders for App Genesis, PocketBase,
rails-apiandrails-fullstack; and recorded score-4 runs for App Genesis andrails-api. Grader fixes for doctor warnings-only exits, credential-value secret checks and scratch-copy determinism checks (#494); fixture workspaces are no longer collected by pytest. - A bounded tenant project/task capacity workload (relation expansion, realtime delivery, transactional background jobs, higher-load and recovery phases) with latency/RSS/CPU and isolation reports and a live CI correctness smoke; reproducible evidence, not production capacity claims.
- Realtime authorization fanout measurements, allocation-lifetime checks, and mid-fanout two-factor and session-revocation regressions; the correctness gate runs with ReleaseSafe and CI checks no timing thresholds.
- CI: feature, contract, code-generation and performance checks run in independent lanes; isolated upload tests run in parallel; the full SQLite unit suite also runs with FTS5 disabled; canonical Zig doc examples compile, config-table parity is checked, and the TypeScript and Python OAuth examples run; PostgreSQL readiness waits for the final listener; S3 integration runs against digest-pinned SeaweedFS; the replay tool is linted; Zig packages are prefetched with jittered retries in every job that builds Zig (CI, fuzz and release), the browser job restores the shared Zig package cache and Linux release builds restore it from main, and a contracts check configures the build from both a branch clone and a
git archivetree. - Test runners: CI exercises the default and shipped simple runners against successful stderr, skips, assertions, leaks, logged errors and post-test signals; a dependency-free Zig+C reproduction and candidate compiler patch for #261 are kept; the zap fork and runner diagnostics are ported to Zig 0.17.1, where #261 still reproduces.
- Test harness:
pytest tests/adminworks on a fresh checkout (tests/_bin.pybuilds fixture servers from their named build steps, and the plugins frontend builds withnpm run build:frontend); the resolver's tests moved totests/tools/so CI collects them; admin fixtures wait for HTTP health and keep startup logs. - Dev-mode builds honor
ZIGBASE_FAKE_HASH=1for cheap Argon2id hashing in test harnesses, with a matching dummy cost on login misses; production builds compile it out. collections.create/update/delete/updateRulesjoin a caller's open transaction with aSAVEPOINTvia a newdb.Db.inTransaction()seam.- Analytics SQL is lowered into bounded stack scratch instead of a hidden global allocator.
- Regression tests for upload writer availability, concurrent-update conflicts, failure cleanup and S3 pagination; ImageMagick 6 and 7 probe contracts tested independently of the host; the negative collection-cache invalidation test no longer depends on allocator address reuse.
- The examples use stable TypeScript 7, Vitest 5 and Node 26 types, track their npm lockfiles, and share the Zigapagos 0.5.0 launcher.