Metadata lifecycle — load, publish and HMR
How metadata flows through Repository, Change Log, Cache and Registry — the event stream behind Studio hot reload, REST writes and cloud editing.
This page documents the metadata data path introduced by ADR-0008 and refined by ADR-0005. It is the canonical event stream that powers Studio Hot Module Replacement (HMR), REST writes, and future cloud editing.
TL;DR — Every write goes through a single MetadataRepository.put() call. The repository appends to a change log, emits a watch event with a monotonic seq, and broadcasts over SSE to the console UI. In dev, the console's MetadataHmrReloader subscribes to that stream and triggers a debounced full page reload.
Architecture (one diagram)
┌─────────────────────────────────────────────┐
│ Console UI (incl. Studio) │
│ (MetadataHmrReloader) │
└────────────────────┬────────────────────────┘
│ SSE /api/v1/dev/metadata-events
▼
┌─────────────────────────────────────────────┐
│ MetadataManager (bridge) │
│ forwards Repository events → SSE channel │
└────────────────────┬────────────────────────┘
│ ChangeEvent{kind, metadataType, name, seq?}
▼
┌─────────────────────────────────────────────┐
│ Overlay precedence (protocol.ts) │
│ ┌─────────────────────────────────────┐ │
│ │ Top: SysMetadataRepository (org) │ │ ← writable overlay
│ │ Bottom: FS / InMemory (artifact) │ │ ← read-only baseline
│ └─────────────────────────────────────┘ │
└────────────────────┬────────────────────────┘
│ append(change log) + emit watch event
▼
sys_metadata table
(or filesystem artifact)Reads walk top-to-bottom: the first non-null layer wins. Writes always route to the topmost writable layer (the overlay). Deletes from the layered API only remove the overlay row — the artifact baseline survives.
Today this precedence is implemented inside the protocol layer, not by
LayeredRepository. ObjectStackProtocolImplementation lazily builds one
SysMetadataRepository for the environment (getOverlayRepo()) and merges it
against the in-memory code registry — getMetaItemLayered() returns code / overlay /
effective separately. LayeredRepository ships in @objectstack/metadata-core
and implements exactly the semantics above, but it is not yet composed into
any production path: every new LayeredRepository(...) call site is a test
(metadata-core's own suite plus one objectql integration test).
The four primitives
| Primitive | Package | Purpose |
|---|---|---|
| Repository | @objectstack/metadata-core | CRUD + watch interface over a single metadata source. InMemoryRepository and LayeredRepository ship from @objectstack/metadata-core; FileSystemRepository from @objectstack/metadata-fs; SysMetadataRepository from @objectstack/metadata-protocol (relocated out of @objectstack/objectql by ADR-0076 — import it from @objectstack/metadata-protocol; @objectstack/objectql no longer re-exports it). |
| Change Log | @objectstack/metadata-core | Append-only log of every mutation, tagged with a monotonic seq. Watchers can replay from any since. |
| Cache | @objectstack/metadata-core | MetadataCache — a bounded LRU in front of a repository, keyed by refKey(ref) and capped by maxEntries / maxBytes. Lazily filled on read miss (no bulk preload), invalidated by repo.watch() events, and negative-caches misses. |
| Registry | (per consumer) | Not a single package — each consumer owns a typed projection over the cache (e.g. SchemaRegistry in @objectstack/objectql), per ADR-0008 §2.9. |
MetaRef = (type, name, org). As of ADR-0008 §0 amendment (2026-04-13), project and branch are removed from the runtime tuple. Project survives only as an artifact-packaging concept on the objectstack.json envelope; branching is left to Git.
Write path: Studio → SSE → repository
When a user edits a view in Studio:
- Studio calls
PUT /api/v1/meta/view/case_grid(REST). protocol.ts:saveMetaItem()runs the two-tier gate (see overlay whitelist): an item that already exists as a packaged artifact requiresMetadataTypeRegistryEntry.allowEnvironmentOverlay; a brand-new item requiresallowRuntimeCreateorallowEnvironmentOverlay.- If allowed, the call lands on
MetadataRepository.put(ref, body, { parentVersion, actor }). - The repository:
- Verifies
parentVersionmatches the current head (ConflictErroron mismatch). - Writes the new row + appends a change-log entry with the next
seq. - Emits a
MetadataEvent { op, ref, hash, parentHash, actor, seq, ts, source }, whereopis one ofcreate | update | delete | rename | publish | revert.
- Verifies
- The
MetadataManagerbridge forwards the event over the SSE channel/api/v1/dev/metadata-events. The wire payload is not the internalMetadataEvent— it is aChangeEvent { kind: 'metadata-change', type, metadataType, name, path?, timestamp, seq? }(emitted asevent: metadata-change).seqis the canonical repository sequence and is absent for FS-watcher (chokidar) dev events. - In dev, the console's
MetadataHmrReloaderreceives themetadata-changeevent and schedules a debouncedlocation.reload()(defaultdebounceMs: 400, plus a 150 ms toast delay).
The seq is the single source of truth for ordering on the server. Note that the shipped console client does not read seq — it reloads the whole page rather than invalidating per-item caches. There is no granular-refetch hook or seq status badge in the current UI.
Package-first authoring (ADR-0070)
Every runtime-authored item lives inside a writable package — there are no
orphans. Code-defined and installed packages are read-only at runtime, so the
first step of any Studio/API authoring action is to target a writable package (a
"base"): a create aimed at a read-only package is rejected, and the author is asked
to pick or create a writable base first. A save naming a package id this deployment
has not installed is refused the same way, draft or active and for every type
(422 WRITABLE_PACKAGE_REQUIRED, nothing written), and
POST /packages/:id/publish-drafts on such an id answers 404, publishing nothing.
Rows stored under such an id before that rule are not extended either: a save
naming no package, whose address those rows give, and the per-item
POST /meta/:type/:name/publish of such a draft are refused with the same 422.
They can still be removed — DELETE /meta/:type/:name?package=:id for the active
row, POST /packages/:id/discard-drafts for drafts — or brought back by creating a
package with that id. An in-place edit of an item the read-only
package ships is refused too; for a flow, an action or a permission set the refusal
names that type's sanctioned path instead (see ADR-0126). New objects, fields, views, and
flows are namespaced into that package — which is exactly what os package publish
later ships. See ADR-0070.
Note: "package" here is the runtime authoring base (a
package_id-bearing container of metadata), distinct from the npm@objectstack/*packages listed in the repo README.
Customizing an installed package: the paired .custom override (ADR-0146)
A customer's change to an installed base package — HotCRM, id hotcrm — is an item of
the base's paired writable package hotcrm.custom, which depends on the base; the
base's own items stay read-only. The unit is the App: an App and every module or plugin
that declares it (HotCRM's app.objectstack.hotcrm and its modules) share one pair,
<app id>.custom (app.objectstack.hotcrm.custom, namespace <app namespace>_custom, depending on
the App at ^<major>), and the ensure door asked for any of them answers that one pair. A package that
declares no App is its own unit, and a kernel package (scope system or cloud) has no pair in this
version. A per-package pair an earlier version created for a module stays installed and keeps serving
what it holds; while it holds the App's pair namespace, the ensure door answers 409 naming it rather
than create the App's pair beside it. An item of the pair that bears a base item's name — for an
email_template, one item per (name, locale), the name and a locale the base ships — and
declares in its body overrides: { package: 'hotcrm', basedOn: '3.2.0' } (the base's
manifest.id and manifest.version; basedOn is recorded and never a gate, and the base's upgrade
plan reads it only as advice; schema:
Override Declaration) replaces the base's
document whole for every read that serves the base's name
(ADR-0146 D8):
- The reads agree.
GET /meta/:type/:namewith no?package, the same read with?package=hotcrm, the layered read (code= the base's document,overlay= the override,effective= the override), the list scoped to the base and the environment-wide list all serve the override, stamped_packageId: 'hotcrm'. The declaration counts only from the pair — the stored row's ownpackage_idmust behotcrm.custom— and for every type ofOVERRIDABLE_METADATA_TYPES(@objectstack/spec/kernel): aview,dashboard,report,email_template,translation,flow,action,page,app,dataset,doc,bookormapping. A declaration from any other package is ignored. The import door and the connector pull read a namedmappingthrough the by-name read, so they run the pair's mapping. - An
actionoverride changes what runs, never who may run it (ADR-0146 D9). It is served wherever the action is drawn or run (the object read'sactions, the run doors) and replaces the base's behaviour (type,target,body,params,label,visible, …) whole, for the people who could already run the base's action. It keeps the base'sobjectName: every door matches the base's action asOBJECT:NAME, so an override that moves it to another object is refused403 NOT_OVERRIDABLEwith ruledeclared_package_ships_no_such_item. An override that drops a capability from the base'srequiredPermissions, setsai.exposed: trueon an action the base keeps off the agent surface, or drops the base'sai.requiresConfirmation: trueis refused403 NOT_OVERRIDABLEwith ruledeclared_action_widens_access; adding a capability is allowed. - Removing the override brings the base's back.
DELETE /meta/:type/:name?package=hotcrm.custom("Restore package original") deletes the pair's row, for every type above, and every read then serves the base's document again. ADELETEnaminghotcrmremoves nothing of the pair's. - A new locale is not an override. An
email_templatethe pair saves at a locale the base does not ship is the pair's own member, served underhotcrm.custom, and carries nooverrides; declaring one there is refused (403 NOT_OVERRIDABLEat the save, publish and install doors, a row fromos validate, the sentence naming the locale), because the base ships no such member to replace. - The pair's added locale is served on the base's address; a dependent's is not. The
member
hotcrm.customadds is listed byGET /meta/email_templatewith no?packageand with?package=hotcrm, is in the execution list the email service reads, and so is what a send in that locale renders — stamped_packageId: 'hotcrm.custom', as the by-name read already served it. The layered read naminghotcrmor no package agrees:code: null,overlayandeffective= the pair's row. A locale another package that depends onhotcrmadds under the base template's name is that package's own item, served only under?package=naming it and in the list scoped to it: the by-name and layered reads naminghotcrmor no package answer404, and the base's lists leave it out. - The environment-wide list serves one item per name that exactly one code package
ships. A dependent package's same-named item is not listed beside it and stays under
its own
?package=address. A package-unbound row — the overlay row of the table below — still wins over the base's document until ADR-0146 D11 migrates it into the pair. - Orphans are reported, not dropped. A row of the base's name — for an
email_template, at a locale the base ships — stored in the pair without the declaration, or in a package that depends on the base, is reported by the layered read inoverlaywitheffective= the base's document. - Export carries the declaration.
GET /packages/hotcrm.custom/exportcarries the overriding item with itsoverridesblock;GET /packages/hotcrm/exportcarries the base unchanged.GET /packages/export(os package export) answers the whole deployment in one read: every installed package its own code does not register, the pair as its own entry after its base, each entry exactly the per-package export.
Overlay whitelist (shared-DB tenancy invariant)
Most metadata types must not be overlaid by an environment — overlaying a packaged item would break the physical schema or the behaviour its package ships. The whitelist lives in one place: MetadataTypeRegistryEntry.allowEnvironmentOverlay in packages/spec/src/kernel/metadata-plugin.zod.ts (spelled allowOrgOverride before protocol 18; GET /api/v1/meta/types serves it per entry as allowEnvironmentOverlay).
ADR-0131 D6 — the per-organization overlay axis is retired. The
/metadoors (REST and the runtime dispatcher) carry no organization into a metadata write or read: a Studio orPUT /api/v1/meta/...write of the five ✅ types below lands environment-wide (since ADR-0131 D7 thesys_metadatafamily declares no organization column) and is served to every organization, and an organization admin holding only the retiredmanage_org_presentationcapability is refused (403). The protocol itself refuses every organization-scoped write, and every read — item, list, layers, cached, history, diff, audit, drafts and the commit timeline — is environment → code, whatever organization a caller names. An overlay row an earlier release stored under an organization — under thesingleposture, every Studio save of these types, filed under the Default Organization — is served by no read, and on a SQL database (SQLite, PostgreSQL, MySQL) still holding one a v18os serverefuses to start until the v18 migration ceremony (ADR-0131 C7:os migrate organization-ownership --out PLAN, then--apply --plan-file PLAN) has carried such a row to the environment layer and dropped the column; nothing deletes or rewrites it before then. The anonymous form doors read the environment alone too: the ceremony carries every organization-layer public-form withdrawal onto the environment, fail-closed. The table still records which types take an overlay of a shipped item.
ADR-0146 D11 — the tier no longer opens a write door onto a packaged item. A write naming no package — a save, a publish, a reset (
DELETE) or a rollback — onto a ✅-type item that one installed read-only package ships is refused403 NOT_OVERRIDABLE, and the sentence names the base's pair: save it into?package=<base>.custom, declaringoverrides(above); for an item a kernel package (scopesystemorcloud) ships, the same write is refused with a sentence that names no pair, because kernel objects are not customizable in this version and a kernel package has no pair. A package-less row stored before the close is still served untilos migrate packageless-overlaysmoves it into the pair as a declared override; the ✅ row is now the set that ceremony moves and the read path honours for an unmoved row. A package-less write of a name no package ships is environment metadata, and stays open. So does the package-less write of a view container (list,listViews,form,formViews): only a single view declares an override, so the ceremony lists the container and leaves it, and its views move into the pair one by one, each as a single view.
| Type | allowEnvironmentOverlay | Rationale |
|---|---|---|
view, dashboard, report, email_template, translation | ✅ | Pure rendering / render-time content. Customizing it in an environment is safe. |
flow | ❌ | Flows carry execution side-effects (events, jobs, audit), and the flow entry declares supportsOverlay: false — the loader cannot merge a per-org flow overlay, so the write permission granted a write nothing could read back: an org-scoped flow overlay wrote successfully and lost its binding on the next cold start. Rolled back (#6283) so the silent phantom is a loud 403 not_overridable at the moment of the write. allowRuntimeCreate stays true — a tenant may still author a brand-new flow through the runtime API (ADR-0070 package-first authoring); what is closed is overlaying a packaged flow. |
agent | ❌ | Agents are platform-owned and closed to third parties (ADR-0063 §2) — no environment fork of a packaged agent. |
permission, position | ❌ | Authorization correctness — an overlay of a packaged permission set is silent privilege drift (ADR-0005's security row). Rolled back from an unratified true by the 2026-08-08 maintainer ruling (#6483); position takes the amendment's false default for new types. allowRuntimeCreate stays true: runtime-created sets (including package-bound rows materialized through the metadata door) keep working, while an admin-door edit of a code-declared set refuses with 403 not_overridable, naming the sanctioned path: clone the set under a new name and edit the clone (ADR-0126). The package's own author still changes the declaration in the package and re-publishes (ADR-0086 two-doors). |
object | ❌ | Defines the table schema. Overriding a packaged object would break existing data — but allowRuntimeCreate: true, so tenants can author brand-new objects, and this is also how a new field is added (write the object with the field in fields). On an object an installed package ships, a field is added as an object extension in the base's paired .custom package, named <name>__c (Object extensions). |
field | ❌ | Also allowRuntimeCreate: false since protocol 17 (#7893). A field is not a standalone artifact — fields are authored inside their object (ObjectSchema.fields), so a field write minted a separate sys_metadata row keyed ('field','<object>.<name>') that nothing ever composed into the parent: PUT /meta/field/showcase_task.zz_probe answered 200 state=active, the row read back _diagnostics.valid: true, and GET /meta/object/showcase_task never listed the field. The door is closed rather than bridged: add a field by writing its object (PUT /meta/object/:name, or **/*.object.ts and redeploy), which both persists and composes. Existing rows are untouched — they were inert before the change too — and remain deletable. |
datasource | ❌ | Connection strings; multi-tenant isolation is enforced at a higher layer. (allowRuntimeCreate: true — the datasource wizard persists origin: 'runtime' rows.) |
job | ❌ | Also allowRuntimeCreate: false since protocol 17 (#4509). JobSchema.handler names a function in the compiled bundle's function table, which a runtime writer has no way to reach — so a job created in Studio or through PUT /meta parsed, saved, reported success and was never scheduled. The door is closed rather than bridged: job stays first-class through *.job.ts / defineStack({ jobs, functions }), where every schedule shape, retryPolicy and timeout does reach the scheduler. Existing rows are untouched — they were never scheduled — and migrateStoredMetadata reports them skipped. |
sharing_rule | ❌ | Also allowRuntimeCreate: false since protocol 18 (ADR-0131 D6, regime C). A sharing rule has two sources: a package declares it (the stack's sharingRules, switched off through the activation ledger), or an organization authors its own through POST /api/v1/sharing/rules, behind the same-name guard and the organization wall. A runtime sys_metadata item was a third source that bypassed both, so PUT /meta/sharing_rule/:name now answers 403 NOT_CREATABLE (NOT_OVERRIDABLE over a declared rule) and names the two sanctioned paths: author an organization rule, or clone the declared one and switch it off. Items stored before the change are still served until deleted. |
The types in the ✅ row are the complete allowEnvironmentOverlay: true set: every other type in DEFAULT_METADATA_TYPE_REGISTRY is false. The ❌ rows above are the false types whose second tier (allowRuntimeCreate) is worth calling out; any type not listed is allowEnvironmentOverlay: false.
There is no workflow metadata type (per ADR-0020, record state machines are a state_machine validation). Nor is there a standalone validation type any more — it was retired in protocol 17 under ADR-0088 because ValidationRuleSchema carries no object-binding key, so a rule authored through that door could never say what it protected; author rules in the object's own validations[] instead. The runtime gate is implemented in OVERLAY_ALLOWED_TYPES (derived from the registry) and enforced by SysMetadataRepository.put().
The gate is two-tier — allowEnvironmentOverlay: false is not the same as "no runtime writes":
- Overwriting an item that ships from a code package is refused →
403 not_overridable. The change is a declared override saved into the base's paired.custompackage (above); for a ✅ type, a package-less row stored before ADR-0146 D11 is still served until it is moved. - Creating a brand-new item that has no artifact backing requires
allowRuntimeCreate(orallowEnvironmentOverlay). Denied →403 not_creatable.
See ADR-0005 for the full design and amendments.
Packaged flows, actions and permission sets (ADR-0126)
flow, action and permission are behavioral types, in Regime C of ADR-0126. A packaged item of one of these types is locked against in-place edits (and, for a flow or an action, against removal). The refusal names the type's sanctioned path, not a redeploy or OS_METADATA_WRITABLE, and each type names only the routes it has:
| Type | Sanctioned path the refusal names |
|---|---|
flow | Declare an override from the base's paired <base>.custom, or rename it (a write from any other package is told to rename: only the pair declares an override), or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}). The declared override is armed in the base flow's place, keeps its one activation switch, and a run suspended on the base finishes on the version it started on (ADR-0146 D9). A copy under a new name is "New similar", the clone door POST /api/v1/automation/:name/clone (body {name, label}), which the removal refusal still names. A flow that holds a credential (an inbound hook's secret, an http node's signingSecret) is not cloned in one step: the clone door refuses it with 409, because a copy would share the secret, and the copy is authored as a new flow with its own. The copy is written switched off, into the source package's paired customization package <base>.custom (created on first use; a kernel package, of scope system or cloud, has no pair in this version, so a copy of a flow it ships answers the ensure door's 409 until the body names package), or into the writable package the body's optional package names; a flow no read-only package ships has no pair, so its clone names package. The answer's packageId says where the copy landed (ADR-0146 D3, D4). |
action | Switch it off (POST /api/v1/actions/_activation/:object/:action, body {enabled: false}; :object is global for an object-less action). No clone is offered. |
permission | Clone it under a new name: the "New similar" action on the permission set, or the clone door POST /api/v1/security/permission-sets/:name/clone (body {name, label, package?}) with a new name. The clone door copies the whole definition from the security catalog; a copy of a packaged set lands in the package's paired <X>.custom, and a copy of a set a kernel package ships lands environment-wide (ADR-0146 D3/D6). |
A permission set and a position also have a switch, outside the refusal: POST /api/v1/security/_activation/:type/:name (:type = permission or position), body {enabled: false}, switches one off for the deployment. The refusal does not name it: a packaged position's refusal keeps the managed seal's edit remedy. The audience anchors everyone and guest are not switchable.
The switches are operator-only where one install serves several organizations. The refusal names the same path whichever layer answers it: 403 NOT_OVERRIDABLE for a write that names no base, and 403 ITEM_LOCKED for one that names the read-only package. Which writes are refused, and with which code, is unchanged.
An environment row stored over a managed item of a type sealed against overlays (a flow, action, hook, object or datasource, for example — any type whose registry entry admits no overlay) before the seal — written through the OS_METADATA_WRITABLE hatch — is not served (ADR-0131 D6): every read, and boot, takes the package's definition, and the row stays at rest, untouched. Boot names each such row, per type ([metadata_sealed_overlay_unserved]), with the two remedies: re-express the change as a new item under a new name, or delete the stored row. A row under the name of a datasource the host defines in code is named once, by the datasource restore's boot warning, with that warning's remedy. A stored fork of a code-declared permission set is the one exception: the deployment does not boot while it holds one (ADR-0048), and os migrate security-catalog-overlays lists and, with --apply, deletes it.
Conflict handling
Every put() requires a parentVersion (or null for fresh creates). If the head has moved since the caller read it, the repository throws ConflictError(ref, expectedParent, actualHead) with code METADATA_CONFLICT. protocol.ts catches it at every write entry point (save, publish, rollback, overlay-delete) and re-throws an API error with code metadata_conflict, HTTP 409 Conflict, and the expectedParent / actualHead pair attached. Clients are expected to re-read the item and retry; the console does not yet surface a dedicated conflict-resolution UI.
The hash is sha256: + 64-hex of a canonical JSON serialization of the body, with undefined values dropped. The canonical form sorts object keys, except in the maps the spec declares ordered. Today that is one map: an object's fields, which keeps its declared order, so a pure reorder of fields is a new version. put() still short-circuits on a write whose body is unchanged. A row written before this release keeps its stored hash as its version token until its content next changes.
HMR end-to-end (latency & ordering)
- Latency. The server half (REST
PUT→ DB write → SSE flush) is fast on localhost, but the client half dominates:MetadataHmrReloaderdebounces for 400 ms, waits another 150 ms so its toast can paint, and then does a full page reload. Budget roughly half a second plus a cold React mount, not a sub-100 ms in-place re-render. - Ordering. The
seqis monotonic per repository. The repository-levelwatch()API supports replay from asincecursor, but the dev HMR SSE endpoint does not replay on reconnect — it registers a fresh listener, emits areadyevent, and then streams only live events. A tab that disconnects and reconnects will miss any events that occurred while it was offline; it should refetch the affected metadata on reconnect. (The stream also emits: pingheartbeat comments every 15 s.) - Multi-tab. Every open tab registers its own listener on the same in-process broadcast hub, so all tabs receive the same events in the same order. No tab tracks
seqclient-side — the shipped reloader ignores it entirely.
Cross-references
- ADR-0005: Metadata customization overlay — overlay semantics, whitelist, conflict rules.
- ADR-0008 §0 amendment (2026-04): project/branch removal — why
MetaRef.projectandMetaRef.branchare dead. - ADR-0008: Metadata Repository & Change Log — the four-primitive architecture.
- IMetadataService Contract — the runtime API plugins call.
- Architecture Overview — the product shape these primitives serve.
Status (as of 2026-04)
| Component | State |
|---|---|
InMemoryRepository, LayeredRepository | ✅ Shipped (@objectstack/metadata-core) |
FileSystemRepository | ✅ Shipped (@objectstack/metadata-fs) |
Change log + seq (per environment, monotonic) | ✅ Shipped |
SSE bridge (/api/v1/dev/metadata-events, event: metadata-change) | ✅ Shipped |
| Granular client-side HMR hook + seq status badge | ❌ Not implemented — no such hook or badge exists in the console today |
Console dev-mode HMR reloader (MetadataHmrReloader) | ✅ Shipped (console app, mounted app-wide, dev-only) |
SysMetadataRepository (overlay over sys_metadata) | ✅ Shipped (@objectstack/metadata-protocol) |
LayeredRepository(SysMeta + artifact) composition | ⏳ Not wired — the class ships, but nothing composes it outside tests |
protocol.ts:saveMetaItem routed through SysMetadataRepository.put | ✅ Shipped (via the environment's getOverlayRepo() repository) |
sys_metadata_history table (durable, org-keyed change log) | ✅ Shipped (object definition in @objectstack/metadata-core; written by SysMetadataRepository) |
Cache + Registry refactor against MetadataRepository | ⏳ Post-M0 |
Cross-replica sync happens above the repository, not inside it.
SysMetadataRepository.watch()is deliberately scoped to the local instance — it has noLISTEN/NOTIFYor pub/sub of its own, and never will. Cross-node propagation is instead a cluster concern:@objectstack/runtimeregistersClusterServicePluginandMetadataClusterBridgePluginby default (opt out withcluster: false), and atkernel:readythe bridge callsMetadataManager.attachClusterPubSub(), fanning every local watch event out over themetadata.changedchannel (loopback-suppressed byoriginNode) so peer nodes invalidate their caches. Note this replays the invalidation event, not the overlay row — peers re-read from the shared database. The default cluster driver ismemory, which is in-process, so real cross-replica fan-out still requires configuring a distributed driver; and if nocluster(ormetadata) service is registered the bridge logs and skips, leaving each replica seeing only its own writes.⚠️ "Peers re-read from the shared database" has one bound worth naming. The
sys_metadataoverlay rowsprotocol.tsreads — the list read insidegetMetaItems, and the served by-name read insidegetMetaItem— are cached across requests. A localsys_metadatawrite retires them when its statement completes (an engine middleware sees it), so read-your-writes is exact on the node that made the write; a write to any other object does not retire them. Inside an engine transaction the statement completes before the commit, so a read landing between the two can keep the pre-commit rows until the nextsys_metadatawrite or the TTL. A peer's write does not either:metadata.changedinvalidates the MetadataManager caches this note is about, but it does not retire the overlay-read cache. What retires that on a peer is either of two receipt paths that bump the local write epoch for a non-writereason, which retires the cache wholesale: themetadata.mutatedchannel's own —protocol.ts'sapplyRemoteMetadataMutationcallsbumpWriteEpoch(engine, 'remote')right after its registry converges and before local listeners run (#13609, 2026-09-03) — or theauthz.invalidatedchannel's bridge, which bumps the same epoch for the authorization cache and retires this one too, as a side effect of sharing it. Failing both, the floor isOS_METADATA_OVERLAY_CACHE_TTL_MS(default 30s,0disables the cache outright). So only on a deployment with no cluster bridge attached at all — the in-processmemorydriver, with no distributed driver behind it — does a peer's overlay re-read still lag a remote publish by up to that TTL. See Environment variables.The served by-name read also caches its compiled answer for an
app,object,view,pageordashboard(ADR-0156), the part that does not depend on the caller; the per-caller gate, field mask, translation andETagstill run on every request. It adds no lag of its own on top of the bound above: the same write epoch retires it, as do the schema registry's and the metadata service's own change counters. A peer's write that reaches no epoch is seen at its own bound,OS_METADATA_COMPILE_CACHE_TTL_MS(default 30s,0disables it), where it reads everysys_metadatarow's bookkeeping columns (version,checksum,updated_at, identity and state) and the metadata files it read, and recompiles if any of them moved. Each such check also drops the cached rows, so the recompile reads the store as it is then. No compiled answer is kept past ten bounds, which also bounds a write that bypasses the engine and changes a body without moving any of those columns.
FAQ — When does code-defined metadata enter the database?
Short answer: never. This is a deliberate design choice; the table below is the authoritative reference and supersedes any other description you may find.
| Where the metadata came from | Lands in sys_metadata? | Lands in history? |
|---|---|---|
defineView(...) / defineFlow(...) / any source file → compiled into dist/objectstack.json | ❌ Never. Loaded into the in-memory registry on boot; refreshed via HMR in dev. | ❌ The artifact's own version history is Git. The metadata layer does not duplicate it. |
Editing a .json under <root>/<type>/<name>.json (FS overlay, e.g. <root>/view/case_grid.json) | ❌ FS layer is independent of DB. | ✅ Appended to the change log at <root>/.objectstack/.log/main.jsonl by FileSystemRepository. |
Studio inline edit, or PUT /api/v1/meta/... (REST) on an allowEnvironmentOverlay: true type | ✅ Written by SysMetadataRepository.put() as an overlay row, environment-wide since ADR-0131 D6 (the table declares no organization column since D7). | ✅ Appended to sys_metadata_history in the same transaction as the sys_metadata write. No-op puts (identical hash) skip the history row entirely. |
Deploying a new build (new dist/objectstack.json) | ❌ The artifact is loaded into memory, not synced into sys_metadata. | ❌ Use Git tags / your deployment platform's release log; that's where artifact "version history" lives. |
Why artifact never enters the database
- Single source of truth. Code → artifact → memory. If artifact also wrote to
sys_metadata, every deploy would need a reconciliation step ("the row says v3.0.0 but the code says v3.0.1") that is impossible to get right under concurrent edits. - Overlay stays small and auditable. The overlay = "what this environment deliberately changed at runtime" (ADR-0131 D6: one environment layer, no per-organization one). A clean table that's safe to dump, diff, or reset to factory.
- Immutable infrastructure. Rolling back a deploy = switching image tags. No DB migration, no reverse
put, no history replay required. - Storage economics. If artifacts were materialised into
sys_metadata, every environment would carry tens of thousands of baseline rows. Overlay-only keeps its row count proportional to its actual customisation.
What if I want auditable history of deployed artifact changes?
That's a deployment log, not a metadata change log. Track the envelope hash of each deployed objectstack.json against the org/environment in a deployment-history table. The internal items inside the artifact need no per-item history because their canonical history is the Git repo that produced them.