Skip to content

ZigBase 0.14.0

Latest

Choose a tag to compare

@github-actions github-actions released this 20 Nov 02:48
· 2 commits to main since this release
Immutable release. Only release title and notes can be modified.
af07d71

[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 with mise exec zig@0.17.1 --), set .minimum_zig_version = "0.17.1" in your build.zig.zon, re-fetch ZigBase with zig 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 spelled debug, safe, fast and small (-Doptimize=safe, and the same for -Dbench-optimize). ZigBase's own dependencies move with it: zap is now pinned to the valthon/zap fork, 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 official translate-c package. 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); and path_secret.param must 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.txt becomes robotsTxt, /api/2fa/verify becomes _2faVerify); set .name only 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 a base or view collection instead of being silently dropped: POST/PATCH /api/collections answer 400 validation_reserved_name, and zigbase schema apply refuses the document. Before, schema apply exited 0 with the field quietly missing, and a following import discarded that column's values while reporting success (#382). Rename the field. auth collections are unchanged: their injected system fields are still ignored on input, so a client can write back a collection document it just read.
  • Comptime .indexes is 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 Conflict instead of being automatically dropped and rebuilt. Inspect and explicitly migrate legacy or application-owned objects before retrying.
  • On a tenant-owned base collection (tenant_field set), a field marked unique (other than the tenant field itself) is now unique per tenant, enforced as a composite UNIQUE (<tenant_field>, <field>) instead of across the whole table (#498). A table-wide unique answered 409 whenever 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 .collections and 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 import upserts 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: global or tenant), 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. Upload POST returns 409 if the collection changes during the transfer; upload PATCH also returns 409 if 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): immediate 503 overload responses with Retry-After, and superuser-only, process-local saturation diagnostics at /api/admission/stats. Builds without it retain no counters or request checks, and the GET /api/health liveness probe stays available while shedding. max_requests and the reported limit are optional (?u32); omit max_requests for no HTTP cap, and stats report limit: null. The TypeScript, Dart, Python (sync and async) and Kotlin SDKs retry recognized overload responses within their existing retry budget and honor numeric Retry-After; generic or malformed 503s 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 (including app.submit) and serial durable poll batches. .admission.max_work caps 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 return error.QueueFull, and saturated durable workers leave jobs pending without spending attempts or rate tokens. Diagnostics and the offline resources report show both budgets. Pre-enqueue serialization, handler allocations and total RSS are not capped.
  • Configure lazy memory-job and app.submit workers 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-only resources --json command 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 tune command 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 (positive u32, default 10,000). Realtime stats and resources --json report 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 .distributed cron 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_at identifies an occurrence stably across retries and recovery, and generation identifies 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.queueCapacity snapshots. 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 Urgency header: zigbase.PushMessage has an optional urgency field (zigbase.PushUrgency: .very_low, .low, .normal, .high), honoured by ctx.push().send and ctx.push().enqueue. Unset, the header is omitted (#484).
  • zigbase.DisabledMailerPlugin lets an app declare that it sends no mail: messages are dropped without logging recipients, bodies or tokens, and doctor --production reports the choice instead of a missing-mailer error.
  • Opt-in zigbase.Idempotency for 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-db refuses 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 an Idempotency-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 an idempotencyKey option.
  • Opt-in record invalidation backfill for reconnecting clients. -Drealtime-backfill=true keeps a bounded, process-local SQLite store; -Ddurable-realtime=true journals 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/backfill returns 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 and 409 resetRequired when a gap cannot be filled. limit counts only items the caller may see and hasNext is 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 force resetRequired on another's checkpoint, and response time grows with the entries scanned. Raw SQL, Data facade 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=true with .files.resumable.durable = true persists 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 the invalid_image and thumbnail_busy error 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=true adds read-only files inventory reporting 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 optional inventory capability 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.renameCollection renames 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 with MigrationBusy before 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 and doctor share the same coordinated ledger bootstrap. On SQLite, older or external writers and automatic provisioning still require a single leader.
  • migrate preview --json lists the compiled consumer migration declarations offline, with explicit unknown pending state, SQL, effects and runtime reversibility.
  • zigbase openapi writes 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, and x-zigbase-collection/x-zigbase-collection-type markers. --out replaces the file atomically.
  • zigbase routes --json lists 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 --json is a versioned offline catalog of agent-facing CLI operations, their output formats, side effects and required inputs (integer bounds as lossless decimal strings). diagnostics wraps doctor checks and failures in one versioned JSON document; ordinary doctor NDJSON is unchanged. capabilities, diagnostics, routes, migrate preview and tune are dev-tools verbs, omitted from -Ddev-tools=false builds.
  • serve wait --timeout-ms N --json waits, up to a deadline, for a healthy tracked session (including unresponsive health probes), reports ready: true on 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_headers sets CSP (including multi-kilobyte generated policies) and per-path cache headers for embedded and directory static serving.
  • zigbase import --preserve-timestamps is an operator-only, create-only mode that keeps validated source created and updated values. Import manifest v2 adds an entry-local preserveTimestamps policy, so the two-pass importer can restore relation cycles between timestamped and timestamp-less collections.
  • zigbase import --external-auths migrates OAuth/OmniAuth provider linkage with the account, so a social-login user is not locked out after a migration. Each auth row may carry externalAuths: [{"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-linked providerId rather than re-pointing an identity. Provider access and refresh tokens never migrate. externalAuths is 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-pocketbase Agent 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-laravel and zigbase-migrate-go Agent 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-api Agent 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.py converter and its tools/rails/export_source.rb metadata 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 _id is stripped, and tables, columns or attachments the target cannot accept are raised at inventory time for an explicit rename or omit decision, and impossible dates, orphan relations, duplicate or malformed auth emails and non-UTF-8 text stop the extraction rather than the import. report.json records 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-fullstack Agent 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 --production ship gate, backup/restore rehearsal, upgrades and rollback, and the custom-image Docker contract (a non-root /data mountpoint owned by uid/gid 65532, serve in the foreground, HTTP readiness and production doctor verified against the assembled image and named volume).
  • Python SDK: opt-in request_key cancellation 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 BADF panic in a queue worker, unexplained dropped connections, and connection resets and truncated pages during browser navigation. Fixed in the pinned zap fork; no application change is required.
  • Realtime access rules now see the subscriber's auth collection in @request.auth.collection and 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, onAuth and the refresh/logout hooks) now carry the user's resolved account scope too, so ctx.can() there sees the same @request.account.* values as a REST request. @request.auth.collection and multi-auth-collection rules are now documented.
  • A REST record delete now announces the rows its relation foreign keys change: realtime publishes a delete event for every record removed by cascadeDelete (transitively), authorized per subscriber against that record's pre-delete state, and an update event for every record whose single relation was set to null; -Ddurable-realtime journals 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 and resetRequired. Record hooks do not run for these rows, and deletes through the Data facade, 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 answered 500 until 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>_fts shadow table). A change whose index cannot be built fails as a whole, and a -Dfts5=false SQLite build answers 400 to 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=true builds: ?vector= list queries no longer fail with 500 (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 answer 400 naming 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 the main schema 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 in search_path is 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_field on an existing collection in .collections is 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 unique flag changes; it used to change only the stored definition. Auth collections keep their previous update behavior.
  • zigbase schema apply --dry-run runs 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 without ZIGBASE_FIELD_KEY passed the dry run and failed the real one. Every problem is now reported at once, on stderr, with its error code (#383).
  • zigbase schema apply is 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 emitted applied list is empty on failure (#383). Freeing a non-injected auth collection 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 before hooks (create, update, delete) keep the status and message of an explicit ctx.fail for every 4xx or 5xx status the HTTP transport supports, and the field details of ctx.invalid; a supported status without a dedicated code (such as 422) uses bad_request. Other failures, including unnamed statuses such as 432, keep the generic 400, and rejected writes still roll back. Hook 5xx responses invoke onError and the reporter backstop with phase before_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_request consistently in typed routes, route ctx.fail and 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 generic 500; 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 with null.
  • 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 500 and left the record in place (#519).
  • superuser create works 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_commit is off (set on the cluster, database or role) is raised to local for 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.md documents the durability requirement, that fsync = off and full_page_writes = off are 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 .rate windows use the database server's clock instead of each host's, so an instance whose clock ran ahead no longer resets other instances' claims before visibility_timeout_s and 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 .distributed leases early; generation fencing still applies and delivery stays at-least-once (#492).
  • On PostgreSQL, mail suppression and bulk sends work: POST /api/mail/webhooks/:provider and POST /api/mail/unsubscribe no longer fail with 500, sends with .mail.check_suppression no longer error, and ctx.mail().sendBulk, batchStatus, cancelBatch and the mail_batch_item queue job run.
  • A correctly signed SES webhook whose complaint or bounce field 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/events and GET /api/analytics/rollups/:name no longer answer 500, and a rollup that has not run yet returns an empty items list, as on SQLite. Event and rollup ordering and the since/from/to filters compare text bytewise, as on SQLite, whatever the database locale: the PostgreSQL-only migration 0030_analytics_text_collation gives the text columns of _events and existing _rollup_* tables (found through search_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 MailCommandFailed when 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 .distributed poll) 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 (.distributed cron follows the database clock and can repeat a minute after that clock steps back) (#493). Under ZIGBASE_FAKE_NOW only 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_size applies 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/health no 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 .webmanifest as application/manifest+json and .ics as text/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, verified or token_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.submit ownership 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/finish proofs, 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 .rate ceilings are shared through database-backed, integer-second windows (migration 0025_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 permanent storage/.zigbase-maintenance.lock must not be removed or replaced; inventory excludes it, and offline files reconcile requires its exclusive lease.
  • The file-serving database reader is released before beforeServe hooks and storage work, including original downloads, so a hook can acquire a reader even with a one-reader pool.
  • doctor --production reports exact @public creation 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/replay recorder (zb_replay) writes captures and findings atomically with private 0600 permissions, 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.testing guidance explains Zig's misleading failed 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 use zigbase.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, SoftwareApplication JSON-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, so owner ~ @request.auth.id compiled to LIKE '%%' 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.id with no owner in the body were affected the same way. An absent @request.auth.*, @request.account.id or @request.account.role value now behaves like SQL NULL: every comparison with it is false, whatever the operator, and inside an in (…) list it matches nothing. The presence tests @request.auth.id != "" and @request.auth.id = "" keep their meaning (#505).
  • serve now binds the host it is given. --http-host/ZIGBASE_HTTP_HOST was parsed, logged, recorded in serve.json and checked by doctor, but never passed to the listener, so every server listened on all interfaces, including instances meant to stay on the documented 127.0.0.1 default behind a reverse proxy. Loopback is now the real default and 0.0.0.0 (or ::) the deliberate opt-in; the official container image already sets ZIGBASE_HTTP_HOST=0.0.0.0 and 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_found as 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 after before_create/before_update hooks, so a hook that links across accounts must write through ctx.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, crossTenant contexts and ctx.records() writes are not narrowed, and the target's viewRule is not applied, so a non-tenant target such as users stays referenceable by id (#497). A new doctor check, 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 as skipped if its scan fails.
  • Realtime delete events are authorized against the deleted record's stored values. Row-constrained subscribers (tenant members, ability holders, owners under rules such as owner = @request.auth.id) on collections with a relation field received no delete frames at all, and the server logged realtime: dropped delivery. Other subscribers were checked against a snapshot with empty created/updated, fixed-point numbers in decimal form and unencoded JSON scalars, so a rule such as price < 100 or created < "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), a beforeDelete hook cannot change what decides, and the delete fails and rolls back if the stored values cannot be read. A viewRule that 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 Ctx queries 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-db import (including existing tables under --force) and startup refuse it and leave it unmodified (REST 400 naming the collection, field and index), and startup restores a missing identity index. On SQLite the identity column must keep the default BINARY collation; a column a migration declared COLLATE NOCASE (or another collation) is refused, because login and uniqueness would compare differently, so declare a .nocase unique 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 FTS5 bm25, 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 record id on 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-api and rails-fullstack; and recorded score-4 runs for App Genesis and rails-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 archive tree.
  • 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/admin works on a fresh checkout (tests/_bin.py builds fixture servers from their named build steps, and the plugins frontend builds with npm run build:frontend); the resolver's tests moved to tests/tools/ so CI collects them; admin fixtures wait for HTTP health and keep startup logs.
  • Dev-mode builds honor ZIGBASE_FAKE_HASH=1 for cheap Argon2id hashing in test harnesses, with a matching dummy cost on login misses; production builds compile it out.
  • collections.create/update/delete/updateRules join a caller's open transaction with a SAVEPOINT via a new db.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.