From 00fef25c86ee0a8f7ad56a074d0d0c0776a20f2e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:30:09 +0000 Subject: [PATCH 1/4] perf(metadata-protocol): the served item read caches its caller-independent compiled answer (ADR-0156) `getMetaItem`'s served face (the per-item read of every app bundle member) answers a by-name read of an app, object, view, page or dashboard from a per-engine cache while every source it reads is unchanged. The per-caller gate, mask, translation and ETag, and the live trailers, run every request. - objectql: `SchemaRegistry#revision`, moved by every public write; the public methods are classified read/write once, exhaustive by type, and the writes are wrapped (registry-revision.ts). - metadata: `MetadataManager#revision` and `loaderChangeMark()`; `FilesystemLoader#changeMark()` stats the type directories and files its reads touched. - metadata-protocol: meta-compile-cache.ts, stamped with the overlay generation and the three counters; confirms at its bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, 0 = uncached) with a store reading and the loader marks, and never renews an entry it cannot confirm. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp --- .changeset/34206-shared-compile-cache.md | 19 + .../docs/deployment/environment-variables.mdx | 1 + .../src/meta-compile-cache.test.ts | 485 ++++++++++++++++++ .../src/meta-compile-cache.ts | 371 ++++++++++++++ .../src/protocol-meta-item-reads.ts | 66 ++- .../metadata/src/loaders/filesystem-loader.ts | 36 ++ .../metadata/src/loaders/loader-interface.ts | 13 + .../metadata-manager-change-revision.test.ts | 156 ++++++ packages/metadata/src/metadata-manager.ts | 49 ++ .../src/engine-cascade-delete-objects.test.ts | 63 +++ .../objectql/src/registry-revision.test.ts | 116 +++++ packages/objectql/src/registry-revision.ts | 217 ++++++++ packages/objectql/src/registry.ts | 15 + scripts/engine-double-contract.pinned.json | 5 + 14 files changed, 1598 insertions(+), 14 deletions(-) create mode 100644 .changeset/34206-shared-compile-cache.md create mode 100644 packages/metadata-protocol/src/meta-compile-cache.test.ts create mode 100644 packages/metadata-protocol/src/meta-compile-cache.ts create mode 100644 packages/metadata/src/metadata-manager-change-revision.test.ts create mode 100644 packages/objectql/src/registry-revision.test.ts create mode 100644 packages/objectql/src/registry-revision.ts diff --git a/.changeset/34206-shared-compile-cache.md b/.changeset/34206-shared-compile-cache.md new file mode 100644 index 00000000000..8f75fb80be9 --- /dev/null +++ b/.changeset/34206-shared-compile-cache.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/metadata': patch +'@objectstack/objectql': patch +--- + +perf(metadata-protocol): the served item read caches its caller-independent compiled answer (ADR-0156) + +Clause-②: no +Metadata-protocol: none + +`getMetaItem` (the served face of `GET /api/v1/meta/:type/:name`, and the per-item read an app bundle makes for every app, object, view, page and dashboard it names) no longer recompiles an item whose sources have not changed. Every caller gets the same answer it got before, the response body and ETag included: only the server's work per request moves. + +- **What is cached.** The compiled envelope of a by-name read of `app`, `object`, `view`, `page` and `dashboard` items, per engine. A read for a package, a state, a member or a draft preview is never cached. The per-caller gate, field mask, translation and ETag stay computed on every request, and the live trailers (`registration`, `disabledActions`, `cascadeDeleteObjects`) are read on every hit. +- **What retires it.** Each source counts its own changes at its own mutation point: the `sys_metadata` overlay generation, the schema registry's `objectRevision` and a new `revision` that every public write of `SchemaRegistry` moves (the classification of its public methods is exhaustive by type), and a new `revision` on `MetadataManager`. Any move drops every entry. A source without its counter makes the cache decline. +- **What another process can change.** After a bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms) the cache confirms before it recompiles: a reading of the stored rows (count and latest change) and of each loader's backing store (`FilesystemLoader` stats the type directories and files its reads touched). If nothing moved, the entries stand for another bound. A loader that keeps no change mark makes every entry recompile at its bound, never renewed. +- `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read, the same reads in the same order. + +On a showcase Setup bundle, an immediate repeat made 213 database reads before and 9 after. diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index d3b53bcad9b..b1da9cb6fb1 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -430,6 +430,7 @@ With several replicas declared over the Redis cluster driver (`OS_CLUSTER_REPLIC | `OS_SANDBOX_WALL_CEILING_MS` | number | `30000` | Wall-clock ceiling (ADR-0102) — the backstop that cuts a hook/action body stuck on a host call that never settles (which burns no CPU, so the CPU budget alone would never fire). The effective ceiling is `max(this, cpuBudget)`, so it can never cut a body still inside its CPU budget. Positive integer only; unset keeps 30s. | | `OS_LOCALIZATION_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of a workspace's reference localization (`timezone` / `locale` / `currency`, read from `sys_setting`) — leg C of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Unlike `OS_AUTHZ_GRANTS_CACHE_TTL_MS` (which is off by default) this one ships **on**, because its invalidation is synchronous and in-process rather than TTL-bound: a `localization` settings change, a write to `sys_setting` or `sys_platform_setting` (the tables the answer is read from), and a non-`write` bump of the engine write epoch each retire a cached answer immediately. A write to any other object does not. So the TTL only bounds what none of these seams can see — a write made on another replica with no cluster bridge attached at all: neither the `metadata.mutated` channel's receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch`, #13609) nor the `authz.invalidated` bridge, both of which bump this same epoch when attached. ⚠️ A malformed value reads as `0` (off), the opposite arm from the grants variable and deliberately so: there `0` is also the default, whereas here folding `3OOO` (letter O) into the default would hand you a **longer** window than the one you were setting. Deployment config only — never a settings row, because `sys_setting` is the table this cache caches. | | `OS_METADATA_OVERLAY_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of the `sys_metadata` overlay rows read inside `getMetaItems` (the list read) and `getMetaItem` (the served by-name read the REST API-exposure gate makes on every `/data` request) — leg D of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Ships **on**, for the same reason as `OS_LOCALIZATION_CACHE_TTL_MS`: invalidation is synchronous and in-process, because every `sys_metadata` write goes through the engine, whose middleware retires the entry when the write's statement completes, before the next read. Outside a transaction that is the commit. Inside an engine transaction it is earlier than the commit: a read that lands between the statement and the commit can keep the pre-commit rows until the next `sys_metadata` write or the TTL. A write to any other object does not retire it; a non-`write` bump of the engine write epoch retires it wholesale. What is cached is the overlay ROW SET only — never the merged answer — so the SchemaRegistry, the MetadataService and the artifact table are re-consulted on every call, cached or not, and the read-side registry hydration keeps running on a cache hit. The TTL therefore bounds one thing: a write made on **another replica** with no cluster bridge attached at all — neither the `metadata.mutated` channel's own receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch` right after registry convergence, #13609) nor the `authz.invalidated` bridge, either of which retires this entry the moment it is attached and fires. ⚠️ A malformed value reads as `0` (off) — same arm and same reason as `OS_LOCALIZATION_CACHE_TTL_MS`. Deployment config only, never a settings row. | +| `OS_METADATA_COMPILE_CACHE_TTL_MS` | number | `30000` | Bound, in milliseconds, for the per-environment cache of compiled item answers ([ADR-0156](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0156-compiled-metadata-answer-cache-every-source-counts-its-own-changes.md)): the served item read (`getMetaItem`) of an app, object, view, page or dashboard, which the app bundle (`GET /api/v1/meta/app/:appId/bundle`) and the item reads make. `0` means **off**, a real path: the read is the uncached one, the same reads in the same order. Only the caller-independent answer is cached; the per-caller gate, field mask, translation and `ETag` are computed on every request. A local change is seen at once: the cache keeps the change counter of every source it reads (the `sys_metadata` overlay generation, the schema registry's `revision` and `objectRevision`, the metadata service's `revision`) and drops every entry when one moves; a source without its counter makes it decline. When the bound passes it confirms before it recompiles, with one reading of what this process cannot see (the `sys_metadata` row count and newest `updated_at`, and each metadata loader's own change mark: the file loader stats the directories and files its reads touched); unchanged, the entries stand for another bound; unreadable, nothing is renewed. The bound is therefore how long another replica's write with no cluster bridge, or a file edited under a running process, can stay unseen. ⚠️ A malformed value reads as `0` (off). Deployment config only, never a settings row. | | `OS_INLINE_SEED_BUDGET_MS` | number | `8000` | Time budget for synchronous seed execution at boot before deferring to a worker. | | `OS_TENANT_AUDIT` | flag | `1` | Set to `0` to silence the tenant-isolation audit warnings emitted by the SQL driver. | diff --git a/packages/metadata-protocol/src/meta-compile-cache.test.ts b/packages/metadata-protocol/src/meta-compile-cache.test.ts new file mode 100644 index 00000000000..eb1fa26823a --- /dev/null +++ b/packages/metadata-protocol/src/meta-compile-cache.test.ts @@ -0,0 +1,485 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34206, ADR-0156 D7] The compiled metadata answer cache behind the served +// item read (`getMetaItem`). Each invalidation pin is paired with a control on +// the same harness (a degenerate cache passes either half alone), and each +// revocation-shaped pin asserts the changed metadata is IN the next answer, +// not only that an entry went. +// +// The harness is the overlay cache's (`protocol.item-read-overlay-cache.test.ts`) +// grown by the counters this cache reads: a registry with `revision` and +// `objectRevision`, a metadata service with `revision` and +// `loaderChangeMark()`, and an `objectql` service answering the live trailers. + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +// The served read reaches a dynamic `import('@objectstack/lint')` (metadata diagnostics): pay its load at collection. +import '@objectstack/lint'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +import { META_COMPILE_CACHE_TTL_ENV, metaCompileCacheTtlMs } from './meta-compile-cache.js'; +import { servedRowChangedAtOf } from './served-row-changed-at.js'; + +type Row = Record; + +const matches = (row: Row, where: Row = {}): boolean => Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`store double: unsupported combinator ${k}`); + if (v !== null && typeof v === 'object') { + const set = (v as { $in?: unknown }).$in; + if (!Array.isArray(set)) throw new Error(`store double: unsupported operator in ${JSON.stringify(v)}`); + return set.includes(row[k] ?? null); + } + return v === undefined || (row[k] ?? null) === (v ?? null); +}); + +type Middleware = (ctx: { object: string; operation: string }, next: () => Promise) => Promise; + +const storedObject = (label: string, updatedAt = '2026-11-16T00:00:00.000Z'): Row => ({ + id: 'r_widget', type: 'object', name: 'widget', state: 'active', package_id: null, + updated_at: updatedAt, + metadata: JSON.stringify({ name: 'widget', label, fields: {}, actions: [{ name: 'approve' }, { name: 'reject' }] }), +}); + +const storedView = (label: string): Row => ({ + id: 'r_view', type: 'view', name: 'widget_list', state: 'active', package_id: null, + updated_at: '2026-11-16T00:00:00.000Z', + metadata: JSON.stringify({ name: 'widget_list', label, object: 'widget' }), +}); + +interface HarnessOptions { + /** Omit the registry's `revision` (the cache must decline). */ + registryRevision?: boolean; + /** The metadata service: `true` (counted, with a loader mark), `'no-revision'`, `'no-mark'`, or `false` (none). */ + metadataService?: true | 'no-revision' | 'no-mark' | false; +} + +function harness(rows: Row[], opts: HarnessOptions = {}) { + const reads: Array<{ op: string; where: Row }> = []; + let epoch = 0; + const seam = { + get current() { return epoch; }, + bump(): number { epoch += 1; return epoch; }, + subscribe(): () => void { return () => {}; }, + }; + const registryCalls: string[] = []; + const registry: Record = { + objectRevision: 0, + getItem: () => undefined, + getObject: () => undefined, + listItems: () => [], + getPackage: () => undefined, + getArtifactItem: () => undefined, + isPackageDisabled: () => false, + registerItem: () => { registryCalls.push('registerItem'); }, + registerObject: () => { registryCalls.push('registerObject'); }, + applyNavContributions: (app: unknown) => app, + // ADR-0150 D3: a by-name read of a package-scoped type needs the resolver. + readsByPackage: () => true, + resolveItem: (type: string, name: string) => (registry.getItem as (t: string, n: string) => unknown)(type, name), + }; + if (opts.registryRevision !== false) registry.revision = 0; + const engine: Record = { + registry, + writeEpoch: seam, + find: async (table: string, q: { where?: Row; limit?: number; orderBy?: unknown } = {}) => { + if (table !== 'sys_metadata') return []; + reads.push({ op: 'find', where: structuredClone(q.where ?? {}) }); + let hits = rows.filter((r) => matches(r, q.where)); + if (q.orderBy !== undefined) hits = [...hits].sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at))); + return typeof q.limit === 'number' ? hits.slice(0, q.limit) : hits; + }, + findOne: async (table: string, q: { where?: Row } = {}) => { + assertEngineFindOnePredicate(table, q as never); + if (table !== 'sys_metadata') return null; + reads.push({ op: 'findOne', where: structuredClone(q.where ?? {}) }); + return rows.find((r) => matches(r, q.where)) ?? null; + }, + count: async (table: string, q: { where?: Row } = {}) => { + if (table !== 'sys_metadata') return 0; + reads.push({ op: 'count', where: structuredClone(q.where ?? {}) }); + return rows.filter((r) => matches(r, q.where)).length; + }, + }; + const middlewares: Middleware[] = []; + engine.registerMiddleware = (fn: Middleware) => { middlewares.push(fn); }; + + let loaderMark = 'files-1'; + const metadataReads: string[] = []; + let metadataService: Record | undefined; + const kind = opts.metadataService ?? true; + if (kind !== false) { + metadataService = { + getDiagnosed: async (type: string, name: string) => { + metadataReads.push(`${type}/${name}`); + return { data: undefined, degraded: false, errors: [] }; + }, + }; + if (kind !== 'no-revision') metadataService.revision = 0; + if (kind !== 'no-mark') metadataService.loaderChangeMark = async () => loaderMark; + } + let disabledActions: string[] = []; + let disabledActionsReads = 0; + const objectql = { + getDisabledActions: () => { disabledActionsReads += 1; return disabledActions; }, + getCascadeDeleteObjects: () => ['widget_line'], + }; + const services = new Map([['objectql', objectql]]); + if (metadataService) services.set('metadata', metadataService); + const protocol = new ObjectStackProtocolImplementation(engine as never, () => services) as any; + + /** A `sys_metadata` write as the engine makes one: the epoch, then the middleware chain around the row. */ + const write = async (apply: () => void, object = 'sys_metadata') => { + seam.bump(); + const chain = [...middlewares]; + let i = 0; + const next = async (): Promise => { + if (i < chain.length) return chain[i++]!({ object, operation: 'update' }, next); + apply(); + }; + await next(); + }; + const byNameReads = (name: string) => reads.filter((r) => r.where.name === name).length; + return { + protocol, engine, registry, services, reads, registryCalls, metadataReads, write, byNameReads, + get metadataService() { return metadataService; }, + setLoaderMark: (mark: string) => { loaderMark = mark; }, + setDisabledActions: (names: string[]) => { disabledActions = names; }, + get disabledActionsReads() { return disabledActionsReads; }, + }; +} + +const read = (h: ReturnType, type = 'object', name = 'widget') => + h.protocol.getMetaItem({ type, name }); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + +describe('[#34206, ADR-0156] the compiled item answer is cached while every source is unchanged', () => { + it('⭐ a repeat reads ZERO sources and serves an equal answer', async () => { + const h = harness([storedObject('Widget')]); + const first = await read(h); + const storeReads = h.reads.length; + const serviceReads = h.metadataReads.length; + expect(h.byNameReads('widget')).toBeGreaterThan(0); + const second = await read(h); + expect(h.reads.length).toBe(storeReads); + expect(h.metadataReads.length).toBe(serviceReads); + expect(second).toEqual(first); + expect(second.item.label).toBe('Widget'); + }); + + it('cached ≡ uncached: the hit equals the answer the cache-off read gives, for each cached type', async () => { + const rows = [storedObject('Widget'), storedView('All widgets')]; + for (const [type, name] of [['object', 'widget'], ['view', 'widget_list']] as const) { + const cached = harness(rows); + await read(cached, type, name); + const hit = await read(cached, type, name); + vi.stubEnv(META_COMPILE_CACHE_TTL_ENV, '0'); + const uncached = await read(harness(rows), type, name); + vi.unstubAllEnvs(); + expect(hit).toEqual(uncached); + expect(servedRowChangedAtOf(hit)).toBe(servedRowChangedAtOf(uncached)); + expect(servedRowChangedAtOf(hit)).toBeDefined(); + } + }); + + it('each call gets its own copy: editing an answer reaches neither the entry nor the next caller', async () => { + const h = harness([storedObject('Widget')]); + const first = await read(h); + first.item.label = 'edited'; + const second = await read(h); + second.item.fields.injected = { type: 'text' }; + const third = await read(h); + expect(second.item.label).toBe('Widget'); + expect(third.item.fields.injected).toBeUndefined(); + expect(third).toEqual({ ...first, item: { ...first.item, label: 'Widget' } }); + }); + + it('the live trailers are read on every hit, never cached', async () => { + const h = harness([storedObject('Widget')]); + const first = await read(h); + expect(first.disabledActions).toEqual([]); + expect(first.cascadeDeleteObjects).toEqual(['widget_line']); + const readsBefore = h.disabledActionsReads; + h.setDisabledActions(['approve']); + const second = await read(h); + expect(h.disabledActionsReads).toBe(readsBefore + 1); + expect(second.disabledActions).toEqual(['approve']); + expect(Object.keys(second)).toEqual(Object.keys(first)); + }); + + it('a trailer the live read no longer answers is absent from the hit, not served from the entry', async () => { + const h = harness([storedObject('Widget')]); + const first = await read(h); + expect(first.cascadeDeleteObjects).toEqual(['widget_line']); + // The engine no longer holds the object: its closure answers nothing. + (h.services.get('objectql') as Record).getCascadeDeleteObjects = () => undefined; + const before = h.byNameReads('widget'); + const second = await read(h); + expect(h.byNameReads('widget')).toBe(before); // non-vacuity: a hit + expect('cascadeDeleteObjects' in second).toBe(false); + }); + + it('[D4] a hit leaves the registry exactly as a miss does: the served read registers nothing either way', async () => { + const h = harness([storedObject('Widget')]); + await read(h); + const afterMiss = [...h.registryCalls]; + await read(h); + expect(h.registryCalls).toEqual(afterMiss); + }); + + it('a read the cache does not answer (a package, a draft preview, a state) is read every time', async () => { + const h = harness([storedObject('Widget')]); + for (const request of [ + { type: 'object', name: 'widget', packageId: 'com.acme' }, + { type: 'object', name: 'widget', previewDrafts: true }, + { type: 'object', name: 'widget', state: 'active' }, + ]) { + await h.protocol.getMetaItem(request).catch(() => undefined); + const before = h.reads.length; + await h.protocol.getMetaItem(request).catch(() => undefined); + expect(h.reads.length, JSON.stringify(request)).toBeGreaterThan(before); + } + }); +}); + +describe('[#34206, ADR-0156 D7] every source retires the entry, and a change elsewhere does not', () => { + it('stored rows: a sys_metadata write retires it and the next answer carries the new row', async () => { + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + await h.write(() => { rows[0] = storedObject('Gadget'); }); + const after = await read(h); + expect(after.item.label).toBe('Gadget'); + }); + + it('control: a write to another object keeps the entry', async () => { + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + const before = h.reads.length; + await h.write(() => {}, 'crm_account'); + await read(h); + expect(h.reads.length).toBe(before); + }); + + it('schema registry: a move of `revision` retires it', async () => { + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + const before = h.byNameReads('widget'); + (h.registry.revision as number)++; + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('schema registry: a move of `objectRevision` retires it', async () => { + const h = harness([storedObject('Widget')]); + await read(h); + const before = h.byNameReads('widget'); + (h.registry.objectRevision as number)++; + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('schema registry: a registry item change is in the next answer (an app\'s registered body)', async () => { + const h = harness([]); + let label = 'Sales'; + h.registry.getItem = (type: string, name: string) => + (type === 'app' && name === 'sales' ? { name: 'sales', label, navigation: [] } : undefined); + const first = await read(h, 'app', 'sales'); + expect(first.item.label).toBe('Sales'); + label = 'Revenue'; + // Unchanged counter: the entry stands (the double changed under the registry's own code). + expect((await read(h, 'app', 'sales')).item.label).toBe('Sales'); + (h.registry.revision as number)++; + expect((await read(h, 'app', 'sales')).item.label).toBe('Revenue'); + }); + + it('metadata service: a move of its `revision` retires it, and so does another service in its slot', async () => { + const h = harness([storedObject('Widget')]); + await read(h); + let before = h.byNameReads('widget'); + (h.metadataService!.revision as number)++; + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + before = h.byNameReads('widget'); + h.services.set('metadata', { ...h.metadataService!, getDiagnosed: h.metadataService!.getDiagnosed }); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('control: a repeat with every counter unchanged keeps the entry', async () => { + const h = harness([storedObject('Widget')]); + await read(h); + const before = h.reads.length; + for (let i = 0; i < 3; i++) await read(h); + expect(h.reads.length).toBe(before); + }); +}); + +describe('[#34206, ADR-0156 D2] a source without its counter makes the cache decline', () => { + for (const [label, opts] of [ + ['a registry without `revision`', { registryRevision: false }], + ['a metadata service without `revision`', { metadataService: 'no-revision' }], + ] as const) { + it(label, async () => { + const h = harness([storedObject('Widget')], opts as HarnessOptions); + await read(h); + const before = h.byNameReads('widget'); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + } + + it('an engine without the overlay seam', async () => { + const h = harness([storedObject('Widget')]); + delete h.engine.writeEpoch; + await read(h); + const before = h.byNameReads('widget'); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('no metadata service at all is no source, and the cache answers', async () => { + const h = harness([storedObject('Widget')], { metadataService: false }); + await read(h); + const before = h.reads.length; + await read(h); + expect(h.reads.length).toBe(before); + }); +}); + +describe('[#34206, ADR-0156 D6] `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read', () => { + it('the same reads, in the same order, as an engine the cache declines', async () => { + const rows = [storedObject('Widget')]; + vi.stubEnv(META_COMPILE_CACHE_TTL_ENV, '0'); + const off = harness(rows); + await read(off); + await read(off); + vi.unstubAllEnvs(); + const declined = harness(rows, { registryRevision: false }); + await read(declined); + await read(declined); + expect(off.reads).toEqual(declined.reads); + expect(off.metadataReads).toEqual(declined.metadataReads); + }); + + it('the knob: unset is the default, a malformed or negative value is off', () => { + expect(metaCompileCacheTtlMs({})).toBe(30_000); + expect(metaCompileCacheTtlMs({ [META_COMPILE_CACHE_TTL_ENV]: '5000' })).toBe(5000); + expect(metaCompileCacheTtlMs({ [META_COMPILE_CACHE_TTL_ENV]: 'soon' })).toBe(0); + expect(metaCompileCacheTtlMs({ [META_COMPILE_CACHE_TTL_ENV]: '-1' })).toBe(0); + }); +}); + +describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recompiles', () => { + const atBound = () => { + let now = 1_000_000; + vi.spyOn(Date, 'now').mockImplementation(() => now); + return { pass: () => { now += 30_001; } }; + }; + + it('nothing moved: the entries stand for another bound, with no recompile', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + clock.pass(); + await read(h); // the first bound may drop: the loader mark grows as reads probe + const before = h.byNameReads('widget'); + clock.pass(); + await read(h); + expect(h.byNameReads('widget')).toBe(before); + }); + + it('the store moved under another writer (no engine seam saw it): every entry goes, and the next answer carries the row', async () => { + const clock = atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + clock.pass(); + await read(h); + rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); + // Inside the bound the out-of-process write is not seen (ADR-0156 D1 (b)). + expect((await read(h)).item.label).toBe('Widget'); + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + }); + + it('a loader\'s backing store moved (a file under a running process): every entry goes', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + clock.pass(); + await read(h); + const before = h.byNameReads('widget'); + h.setLoaderMark('files-2'); + clock.pass(); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('an in-process write that lands while the confirmation awaits the store is not hidden by the entry it retires', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + clock.pass(); + await read(h); + // The registry moves while the confirmation's store reading is in flight. + const count = h.engine.count as (...a: unknown[]) => Promise; + h.engine.count = async (...a: unknown[]) => { + h.engine.count = count; + (h.registry.revision as number)++; + return count(...a); + }; + clock.pass(); + const before = h.byNameReads('widget'); + await read(h); + expect(h.engine.count).toBe(count); // non-vacuity: the confirmation ran and saw the move mid-flight + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('a store outage at the confirmation fails the read as the uncached read does, and never serves the unconfirmed entry', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + const count = h.engine.count as (...a: unknown[]) => Promise; + const outage = new Error('connect ECONNREFUSED 127.0.0.1:5432'); + h.engine.count = async () => { throw outage; }; + clock.pass(); + const failure = await read(h).then(() => undefined, (e: unknown) => e as Error & { cause?: unknown }); + expect(failure).toBeInstanceOf(Error); + expect(failure?.cause).toBe(outage); + // The store is back with the reading the entry was last confirmed at: + // the confirmation now succeeds, and the answer is right. + h.engine.count = count; + expect((await read(h)).item.label).toBe('Widget'); + }); + + it('a store not provisioned yet at the confirmation: no reading, so the entry is recompiled, not renewed', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + h.engine.count = async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); }; + clock.pass(); + const before = h.byNameReads('widget'); + expect((await read(h)).item.label).toBe('Widget'); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + }); + + it('⛔ a source the confirmation cannot observe: nothing is renewed, every bound recompiles', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')], { metadataService: 'no-mark' }); + await read(h); + let before = h.byNameReads('widget'); + await read(h); + expect(h.byNameReads('widget')).toBe(before); // inside the bound it is still a cache + for (let i = 0; i < 2; i++) { + clock.pass(); + before = h.byNameReads('widget'); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(before); + } + }); +}); diff --git a/packages/metadata-protocol/src/meta-compile-cache.ts b/packages/metadata-protocol/src/meta-compile-cache.ts new file mode 100644 index 00000000000..11dea216ae8 --- /dev/null +++ b/packages/metadata-protocol/src/meta-compile-cache.ts @@ -0,0 +1,371 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34206, ADR-0156] The compiled metadata answer cache: the served item read + * (`getMetaItem`) of an app, object, view, page or dashboard, kept per engine + * and answered again while every source it was compiled from is unchanged. + * + * ## What is cached, and what is not (ADR-0156 D3) + * + * The value is `getMetaItem`'s envelope for one `(type, name)` read with no + * package, member, state or draft preview: the merge of the stored rows, the + * schema registry and the metadata service, governed, decorated and locked. + * That read takes no caller: it reads the store as the system and the + * registries in memory, so every caller of the environment is answered the + * same envelope. The per-caller gate, the field mask, the translation and the + * `ETag` are the REST door's, applied over this envelope on every request, + * as before. + * + * Three members of the envelope are NOT cached: `registration`, + * `disabledActions` and `cascadeDeleteObjects` ({@link LIVE_ITEM_TRAILER_KEYS}). + * They read the automation engine, the action-activation ledger and the + * cascade closure, which have no counter here; a hit reads them again through + * the one function the miss used ({@link liveItemTrailers}). + * + * ## The sources and their counters (ADR-0156 D1 (a), D2) + * + * | source | counter | + * |:--|:--| + * | `sys_metadata` rows | the overlay cache generation ({@link readOverlayCacheGeneration}): every engine-seam write to the table, and every non-write epoch move (a peer's write through the cluster bridge, a metadata or manual bump) | + * | schema registry: objects | `registry.objectRevision` | + * | schema registry: items, artifacts, packages and enablement, navigation contributions, namespaces, claims | `registry.revision` (objectql `registry-revision.ts`) | + * | metadata service | `revision` on the service registered as `'metadata'`, and the service's identity | + * + * A source without its counter makes the cache DECLINE: the read runs + * uncached, exactly as before. A registry without `revision` or + * `objectRevision`, an engine without the overlay seam, a metadata service + * without `revision`: each declines. ⛔ No counter is guessed, and none is + * borrowed from another source. + * + * ## The time bound and the confirmation (ADR-0156 D1 (b), D5) + * + * `OS_METADATA_COMPILE_CACHE_TTL_MS` (default {@link META_COMPILE_CACHE_DEFAULT_TTL_MS}; + * `0` is off and the read is the uncached one, the same reads in the same + * order). The bound covers what this process cannot see: another node's + * write with no cluster bridge, a write that bypasses the engine. + * + * When the bound passes, the cache confirms before it recompiles: the + * counters above at their stamp, and a reading of everything outside this + * process that the bound exists for ({@link readConfirmationMark}): + * + * - the stored rows: the `sys_metadata` row count and its newest + * `updated_at` ({@link readStoreMark}), which another writer's insert, + * update or delete moves; + * - the metadata service's loaders: `loaderChangeMark()` on the service + * (`@objectstack/metadata`), each loader's own reading of its backing + * store (the file loader stats the directories and files its reads + * touched, so a file a deployment creates, removes or edits under a + * running process moves it). + * + * Nothing moved: the entries are kept for another bound. Anything moved: + * every entry goes. + * + * ⛔ A renewal is a claim about what was looked at (ADR-0156 D5). When the + * confirmation cannot read one of those (the store cannot be read, the + * service keeps no `loaderChangeMark`, a loader keeps no mark), nothing is + * renewed: every entry is dropped at its bound and compiled again, so the + * cache answers repeats within one bound and never across two. + * + * ## Invalidation is coarse, by construction + * + * The stamp is the whole tuple of counters, held per engine. Any counter + * moving retires EVERY entry of that engine at once: metadata changes are + * rare, and a per-entry dependency graph would be the call-site list ADR-0127 + * D2 forbids in another shape. A read in flight across a change is stamped + * with the counters it STARTED under and is not stored when they moved + * before it settled. + * + * ## Values are cloned in both directions + * + * An envelope is cloned when stored and again when served, so a caller that + * edits its answer (the REST door spreads and translates it) cannot reach the + * entry, and a hit is byte-equivalent to a miss. An envelope that cannot be + * cloned is not stored. The served row's change time + * (`servedRowChangedAtOf`, a non-enumerable symbol member) is kept beside the + * clone and put back on every served copy. + * + * ## Hydration (ADR-0156 D4) + * + * The served item read registers nothing in the schema registry; the list + * read (`getMetaItems`) does, and is not cached here. A hit therefore leaves + * the registry exactly as a miss does. + */ + +import { isMissingTableError } from '@objectstack/metadata/errors'; +import { readOverlayCacheGeneration } from './meta-overlay-cache.js'; +import { metadataReadFailureError } from './protocol-client-failures.js'; +import { servedRowChangedAtOf, withServedRowChangedAt } from './served-row-changed-at.js'; + +/** Env var naming the compile cache's time bound, in milliseconds. `0` turns the cache off. */ +export const META_COMPILE_CACHE_TTL_ENV = 'OS_METADATA_COMPILE_CACHE_TTL_MS'; + +/** + * The default bound: 30 s, the overlay row cache's. On a single node with the + * engine seam every local change is seen at once and the bound only paces the + * confirmation; across nodes with no cluster bridge it is how long another + * node's write can stay unseen, as it already is for the row cache. + */ +export const META_COMPILE_CACHE_DEFAULT_TTL_MS = 30_000; + +/** The types whose served item read is cached: the app bundle's member types. */ +export const META_COMPILE_CACHE_TYPES: ReadonlySet = new Set(['app', 'object', 'view', 'page', 'dashboard']); + +/** The time bound, read from {@link META_COMPILE_CACHE_TTL_ENV}. Unset or blank: the default. Not a non-negative number: `0`. */ +export function metaCompileCacheTtlMs( + env: Record = typeof process !== 'undefined' ? process.env : {}, +): number { + const raw = env[META_COMPILE_CACHE_TTL_ENV]; + if (raw === undefined || raw.trim() === '') return META_COMPILE_CACHE_DEFAULT_TTL_MS; + const parsed = Number(raw.trim()); + if (!Number.isFinite(parsed) || parsed < 0) return 0; + return Math.floor(parsed); +} + +/** The request shape this cache answers: a served read naming only a type and a name. */ +export interface MetaCompileCacheRequest { + type: string; + name: string; + packageId?: string; + state?: 'active' | 'draft'; + previewDrafts?: boolean; + member?: string; +} + +/** What the cache reads from the protocol: the engine, the services, and the live trailers. */ +export interface MetaCompileCacheHost { + readonly engine: unknown; + readonly getServicesRegistry?: (() => { get(name: string): unknown } | undefined) | undefined; + /** The live members of a served envelope, as the miss computed them. */ + liveTrailers(type: string, name: string, item: unknown): Record; + /** The keys {@link liveTrailers} may answer; stripped from a stored envelope. */ + readonly liveTrailerKeys: readonly string[]; +} + +/** The counters an entry was compiled under. Compared member by member, never interpreted. */ +interface CompileStamp { + readonly overlay: number; + readonly objectRevision: number; + readonly registryRevision: number; + readonly metadataService: object | undefined; + readonly metadataServiceRevision: number | undefined; +} + +interface CompileEntry { + /** A private clone of the envelope, the live trailers removed. Never handed out un-cloned. */ + readonly envelope: Record; + readonly changedAt: string | undefined; +} + +interface CompileBucket { + readonly stamp: CompileStamp; + /** The confirmation reading ({@link readConfirmationMark}) the entries were last confirmed at; `undefined` until the first. */ + mark: string | undefined; + /** Until when the entries stand without a confirmation. */ + confirmedUntil: number; + readonly entries: Map; +} + +/** One bucket per engine: the engine owns the rows and the registry every entry was compiled from. */ +const buckets = new WeakMap(); + +/** The metadata service the protocol reads, or `undefined` when there is none. */ +function metadataServiceOf(host: MetaCompileCacheHost): object | undefined { + try { + const service = host.getServicesRegistry?.()?.get('metadata'); + return service !== null && typeof service === 'object' ? service : undefined; + } catch { + return undefined; + } +} + +/** + * Every source's counter, now — or `undefined` when a source the read can + * reach exposes none, which makes the cache decline (ADR-0156 D2). + */ +export function readCompileStamp(host: MetaCompileCacheHost): CompileStamp | undefined { + const engine = host.engine; + if (!engine || typeof engine !== 'object') return undefined; + const overlay = readOverlayCacheGeneration(engine); + if (overlay === undefined) return undefined; + const registry = (engine as { registry?: { objectRevision?: unknown; revision?: unknown } }).registry; + if (!registry || typeof registry.objectRevision !== 'number' || typeof registry.revision !== 'number') return undefined; + const metadataService = metadataServiceOf(host); + let metadataServiceRevision: number | undefined; + if (metadataService !== undefined) { + const revision = (metadataService as { revision?: unknown }).revision; + if (typeof revision !== 'number') return undefined; + metadataServiceRevision = revision; + } + return { + overlay, + objectRevision: registry.objectRevision, + registryRevision: registry.revision, + metadataService, + metadataServiceRevision, + }; +} + +function sameStamp(a: CompileStamp, b: CompileStamp): boolean { + return a.overlay === b.overlay + && a.objectRevision === b.objectRevision + && a.registryRevision === b.registryRevision + && a.metadataService === b.metadataService + && a.metadataServiceRevision === b.metadataServiceRevision; +} + +/** + * The confirmation's reading of everything outside this process the bound + * exists for: the stored rows ({@link readStoreMark}) and the metadata + * service's loaders (`loaderChangeMark()`), or `undefined` when either + * cannot be read, which forbids a renewal (ADR-0156 D5). + */ +export async function readConfirmationMark(engine: unknown, metadataService: object | undefined): Promise { + const read = (metadataService as { loaderChangeMark?: unknown } | undefined)?.loaderChangeMark; + if (metadataService !== undefined && typeof read !== 'function') return undefined; + const [store, loaders] = await Promise.all([ + readStoreMark(engine), + metadataService === undefined + ? Promise.resolve('') + : (read as () => Promise).call(metadataService).then( + (mark) => (typeof mark === 'string' ? mark : undefined), + () => undefined, + ), + ]); + if (store === undefined || loaders === undefined) return undefined; + return JSON.stringify([store, loaders]); +} + +/** + * The store reading the confirmation compares (ADR-0156 D5): the number of + * `sys_metadata` rows and the newest `updated_at` among them, read as the + * system. Another writer's insert moves both, its update moves the second, + * its delete moves the first. + * + * `undefined` when there is nothing to read it with (an engine without + * `count` / `find`) or no store yet (`sys_metadata` not provisioned, by error + * type): the bucket's entries then go, and nothing is renewed. Any other + * failure is thrown as the uncached read throws it + * (`rethrowUnlessMetadataStoreUnprovisioned`): an outage is never read as + * "nothing moved", and never served from the entries it could not confirm. + */ +export async function readStoreMark(engine: unknown): Promise { + const ql = engine as { + count?: (object: string, query: unknown) => Promise; + find?: (object: string, query: unknown) => Promise; + }; + if (typeof ql?.count !== 'function' || typeof ql?.find !== 'function') return undefined; + try { + const context = { isSystem: true }; + const [count, newest] = await Promise.all([ + ql.count('sys_metadata', { where: {}, context }), + ql.find('sys_metadata', { + where: {}, + fields: ['updated_at'], + orderBy: [{ field: 'updated_at', order: 'desc' }], + limit: 1, + context, + }), + ]); + if (typeof count !== 'number') return undefined; + const row = Array.isArray(newest) ? newest[0] as { updated_at?: unknown } | undefined : undefined; + const at = row?.updated_at instanceof Date ? row.updated_at.toISOString() : String(row?.updated_at ?? ''); + return JSON.stringify([count, at]); + } catch (error) { + if (isMissingTableError(error, 'sys_metadata')) return undefined; + throw metadataReadFailureError(error); + } +} + +/** Whether this request is one the cache answers. */ +function cacheableRequest(request: MetaCompileCacheRequest): boolean { + return META_COMPILE_CACHE_TYPES.has(request.type) + && typeof request.name === 'string' && request.name !== '' + && request.packageId === undefined + && request.member === undefined + && request.state === undefined + && request.previewDrafts === undefined; +} + +function entryKey(request: MetaCompileCacheRequest): string { + return JSON.stringify([request.type, request.name]); +} + +/** A clone of `value`, or `undefined` when it cannot be cloned. */ +function cloned(value: T): T | undefined { + try { + return structuredClone(value); + } catch { + return undefined; + } +} + +/** The served copy of an entry: a fresh clone, the live trailers read now, the row change time put back. */ +function serve(host: MetaCompileCacheHost, request: MetaCompileCacheRequest, entry: CompileEntry): unknown { + const envelope = structuredClone(entry.envelope); + const served = { ...envelope, ...host.liveTrailers(request.type, request.name, envelope.item) }; + return withServedRowChangedAt(served, entry.changedAt); +} + +/** + * Confirm `bucket` at its bound (ADR-0156 D5) and open the next one: its + * entries stand for another bound only when the reading of everything outside + * this process is the one they were last confirmed at. A moved reading drops + * them all. An unreadable one drops them all too, and leaves no reading to + * compare at the next bound, so nothing compiled under it is ever renewed: + * it is a cache for one bound at a time. + */ +async function confirm(engine: object, bucket: CompileBucket, ttlMs: number, now: number): Promise { + const mark = await readConfirmationMark(engine, bucket.stamp.metadataService); + if (mark === undefined || bucket.mark !== mark) bucket.entries.clear(); + bucket.mark = mark; + bucket.confirmedUntil = now + ttlMs; +} + +/** + * Answer a served item read through the cache, or by `compute` (the uncached + * read) when the cache is off, the request is not one it answers, a source + * exposes no counter, or the entry is missing. See the module header. + */ +export async function readThroughMetaCompileCache( + host: MetaCompileCacheHost, + request: MetaCompileCacheRequest, + compute: () => Promise, +): Promise { + const ttlMs = metaCompileCacheTtlMs(); + if (ttlMs <= 0 || !cacheableRequest(request)) return compute(); + const stamp = readCompileStamp(host); + if (stamp === undefined) return compute(); + const engine = host.engine as object; + + let bucket = buckets.get(engine); + if (bucket === undefined || !sameStamp(bucket.stamp, stamp)) { + bucket = { stamp, mark: undefined, confirmedUntil: 0, entries: new Map() }; + buckets.set(engine, bucket); + } + const now = Date.now(); + if (now >= bucket.confirmedUntil) await confirm(engine, bucket, ttlMs, now); + + const key = entryKey(request); + const hit = bucket.entries.get(key); + // The stamp is read again: the confirmation awaited the store. + const current = readCompileStamp(host); + if (hit !== undefined && current !== undefined && sameStamp(current, stamp) && buckets.get(engine) === bucket) { + return serve(host, request, hit) as T; + } + + const answer = await compute(); + const after = readCompileStamp(host); + if (after === undefined || !sameStamp(after, stamp) || buckets.get(engine) !== bucket) return answer; + const item = (answer as { item?: unknown } | null | undefined)?.item; + if (item === null || typeof item !== 'object') return answer; + const copy = cloned(answer) as Record | undefined; + if (copy === undefined) return answer; + for (const trailer of host.liveTrailerKeys) delete copy[trailer]; + bucket.entries.set(key, { envelope: copy, changedAt: servedRowChangedAtOf(answer) }); + return answer; +} + +/** Test seam: drop every entry this process holds for `engine`. */ +export function clearMetaCompileCache(engine: object): void { + buckets.delete(engine); +} diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index a0d4fe91d97..7454a58608f 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -27,6 +27,7 @@ import { } from '@objectstack/core'; import { isPairOf, itemDiscriminator } from '@objectstack/metadata-core'; import { boundObjectOf, storedItemPackageId } from '@objectstack/metadata/stored-item-package'; +import type { FlowRegistration } from '@objectstack/spec/api'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; // [#24395] The draft row's per-key provenance, read back for the strict draft read. import { storedDraftChanges } from './draft-changes.js'; @@ -55,6 +56,7 @@ import { isPackageLessRow, refuseUnjudgeableByNameRead, } from './protocol-exact-qualifier.js'; +import { readThroughMetaCompileCache } from './meta-compile-cache.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { bundleMemberOf, @@ -559,14 +561,24 @@ export async function judgeDroppedServiceRefusal( } /** The body of `ObjectStackProtocolImplementation#getMetaItem`; the method's docblock there is its contract. */ -export async function getMetaItem(host: Pick, request: { +export async function getMetaItem(host: Pick, request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, /** [#22877] The bundle member to read — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string, }) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. Folded // HERE, at each face's boundary, as {@link getMetaItems} folds. - return host.readMetaItemFace(canonicalizeMetaRequestType(request), 'served'); + const canonical = canonicalizeMetaRequestType(request); + // [#34206, ADR-0156] Through the compiled-answer cache, which answers + // only a read naming a bundle member type and a name, and only while + // every source it reads counts its own changes; otherwise, and at + // `OS_METADATA_COMPILE_CACHE_TTL_MS=0`, this is the uncached read. + return readThroughMetaCompileCache({ + get engine() { return host.engine; }, + getServicesRegistry: () => host.getServicesRegistry?.(), + liveTrailers: (type, name, item) => liveItemTrailers(host, type, name, item), + liveTrailerKeys: LIVE_ITEM_TRAILER_KEYS, + }, canonical, () => host.readMetaItemFace(canonical, 'served')); } /** The body of `ObjectStackProtocolImplementation#getMetaItemForExecution`; the method's docblock there is its contract. */ @@ -579,6 +591,37 @@ export async function getMetaItemForExecution(host: Pick, + type: string, name: string, item: unknown, +): { registration?: FlowRegistration; disabledActions?: string[]; cascadeDeleteObjects?: string[] } { + const readRegistration = host.resolveFlowRegistrationReader(type); + const readDisabledActions = host.resolveDisabledActionsReader(type); + const cascadeDeleteObjects = host.resolveCascadeDeleteObjects(type, name); + return { + ...(readRegistration ? { registration: readRegistration(name) } : {}), + ...(readDisabledActions ? { disabledActions: readDisabledActions(item) } : {}), + ...(cascadeDeleteObjects !== undefined ? { cascadeDeleteObjects } : {}), + }; +} + /** The body of `ObjectStackProtocolImplementation#readMetaItem`; the method's docblock there is its contract. */ /** * [#32607] The item's active rows a face read before {@link readMetaItem} @@ -1424,21 +1467,18 @@ export async function readMetaItem(host: Pick(); private static readonly RESOLUTION_MEMO_CAP = 10_000; @@ -764,6 +770,7 @@ export class FilesystemLoader implements MetadataLoader { /** The disk read behind {@link findFile}: one `fs.access` per resolvable extension, in precedence order. */ private async probeFile(type: string, name: string): Promise { const typeDir = path.join(this.rootDir, type); + this.probedTypeDirs.add(typeDir); const extensions = this.resolvableExtensions(); for (const ext of extensions) { @@ -780,6 +787,35 @@ export class FilesystemLoader implements MetadataLoader { return null; } + /** + * [#34206, ADR-0156 D5] What another process can change under an item + * {@link load} answered: the modification time and size of every type + * directory a read has probed (a file created, removed or renamed in it + * moves the directory's), and of every file a read resolved (an edit in + * place moves the file's). An absent path reads `absent`, so creating it + * moves the mark too. One `stat` per directory and per resolved file. + * + * It covers item reads only. It is what lets a cache of an answer this + * loader contributed to, including a miss it remembered, be renewed on a + * confirmation instead of recompiled (`MetadataManager.loaderChangeMark`). + */ + async changeMark(): Promise { + const files = new Set(); + for (const names of this.resolvedFiles.values()) { + for (const filePath of names.values()) if (filePath) files.add(filePath); + } + const paths = [...[...this.probedTypeDirs].sort(), ...[...files].sort()]; + const marks = await Promise.all(paths.map(async (p) => { + try { + const stats = await fs.stat(p); + return `${p}:${stats.mtimeMs}:${stats.size}`; + } catch { + return `${p}:absent`; + } + })); + return createHash('sha1').update(marks.join('\n')).digest('hex'); + } + private rememberResolution(type: string, name: string, filePath: string | null): void { let remembered = this.resolvedFiles.get(type); diff --git a/packages/metadata/src/loaders/loader-interface.ts b/packages/metadata/src/loaders/loader-interface.ts index 797316ee573..975cfa36dec 100644 --- a/packages/metadata/src/loaders/loader-interface.ts +++ b/packages/metadata/src/loaders/loader-interface.ts @@ -283,6 +283,19 @@ export interface MetadataLoader { * `packagelessOnly`: delete only the name's package-less slots */ delete?(type: string, name: string, options?: MetadataLoaderDeleteOptions): Promise; + + /** + * [#34206, ADR-0156 D5] A reading of this loader's backing store that moves + * whenever something outside this process changes what {@link load} would + * answer for an item it has been asked about: a file created, removed or + * edited, a row written by another node. Compared, never interpreted. + * + * Optional. `MetadataManager.loaderChangeMark()` reads it for a cache's + * confirmation; a loader that keeps none (other than an in-process + * `memory:` one) means the confirmation cannot observe it, and a cache + * renews nothing that may have read it. + */ + changeMark?(): Promise; } /** [ADR-0150 D4, #32198] How {@link MetadataLoader.delete} scopes a removal. */ diff --git a/packages/metadata/src/metadata-manager-change-revision.test.ts b/packages/metadata/src/metadata-manager-change-revision.test.ts new file mode 100644 index 00000000000..e349455ba0d --- /dev/null +++ b/packages/metadata/src/metadata-manager-change-revision.test.ts @@ -0,0 +1,156 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34206, ADR-0156 D2 and D5] The two readings a shared compile cache keys on + * this manager with: + * + * - `MetadataManager#revision`, moved by every in-process path that changes + * what `get` / `getDiagnosed` / `list` answer (a register, an unregister, a + * new loader, a new type registry), and left alone by a read; + * - `MetadataManager#loaderChangeMark()`, the confirmation's reading of what + * another process can change: each non-memory loader's own `changeMark()`, + * or `undefined` when a loader keeps none; + * - `FilesystemLoader#changeMark()`, which moves on a file created in a type + * directory a read probed (a remembered miss would now hit) and on an edit + * of a file a read resolved, and not on a directory no read looked in. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { MetadataManager } from './metadata-manager.js'; +import { FilesystemLoader } from './loaders/filesystem-loader.js'; +import { JSONSerializer } from './serializers/json-serializer.js'; +import type { MetadataLoader } from './loaders/loader-interface.js'; + +vi.mock('@objectstack/core', async (orig) => ({ + ...((await orig()) as object), + createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }), +})); + +function readOnlyLoader(name: string, protocol: string, changeMark?: () => Promise): MetadataLoader { + return { + contract: { name, protocol, capabilities: { read: true, write: false, watch: false, list: true } }, + load: async () => ({ data: null }), + loadMany: async () => [], + list: async () => [], + exists: async () => false, + stat: async () => null, + ...(changeMark ? { changeMark } : {}), + } as unknown as MetadataLoader; +} + +describe('[#34206] MetadataManager#revision', () => { + it('moves on register, unregister, a new loader and a new type registry', async () => { + const mgr = new MetadataManager({}); + const steps: Array<[string, () => unknown]> = [ + ['register', () => mgr.register('view', 'rv_all', { name: 'rv_all', label: 'All' })], + ['register again', () => mgr.register('view', 'rv_all', { name: 'rv_all', label: 'All, renamed' })], + ['unregister', () => mgr.unregister('view', 'rv_all')], + ['registerLoader', () => mgr.registerLoader(readOnlyLoader('extra', 'extra:'))], + ['setTypeRegistry', () => mgr.setTypeRegistry([])], + ]; + for (const [label, step] of steps) { + const before = mgr.revision; + await step(); + expect(mgr.revision, label).toBeGreaterThan(before); + } + }); + + it('the store funnel counts on its own: a write that no list-cache drop or announcement follows (a rollback\'s) still moves it', () => { + const mgr = new MetadataManager({}); + const before = mgr.revision; + (mgr as unknown as { writeRegistryEntry(t: string, n: string, d: unknown): boolean }).writeRegistryEntry('view', 'rv_all', { name: 'rv_all' }); + expect(mgr.revision).toBeGreaterThan(before); + const afterWrite = mgr.revision; + (mgr as unknown as { deleteRegistryEntries(t: string, n: string): void }).deleteRegistryEntries('view', 'rv_all'); + expect(mgr.revision).toBeGreaterThan(afterWrite); + }); + + it('control: a read leaves it alone', async () => { + const mgr = new MetadataManager({}); + await mgr.register('view', 'rv_all', { name: 'rv_all', label: 'All' }); + const before = mgr.revision; + expect(await mgr.get('view', 'rv_all')).toMatchObject({ label: 'All' }); + expect((await mgr.getDiagnosed('view', 'rv_all')).data).toMatchObject({ label: 'All' }); + expect(await mgr.get('view', 'rv_none')).toBeUndefined(); + expect(mgr.revision).toBe(before); + }); +}); + +describe('[#34206] MetadataManager#loaderChangeMark', () => { + it('a memory loader contributes nothing; a loader with a mark contributes it', async () => { + const mgr = new MetadataManager({}); + mgr.registerLoader(readOnlyLoader('mem', 'memory:')); + let mark = 'a'; + mgr.registerLoader(readOnlyLoader('disk', 'file:', async () => mark)); + const first = await mgr.loaderChangeMark(); + expect(first).toBe(JSON.stringify(['disk=a'])); + expect(await mgr.loaderChangeMark()).toBe(first); + mark = 'b'; + expect(await mgr.loaderChangeMark()).not.toBe(first); + }); + + it('a non-memory loader without a mark, or whose mark throws, makes the answer undefined', async () => { + const without = new MetadataManager({}); + without.registerLoader(readOnlyLoader('remote', 'https:')); + expect(await without.loaderChangeMark()).toBeUndefined(); + + const throwing = new MetadataManager({}); + throwing.registerLoader(readOnlyLoader('disk', 'file:', async () => { throw new Error('EACCES'); })); + expect(await throwing.loaderChangeMark()).toBeUndefined(); + }); +}); + +describe('[#34206] FilesystemLoader#changeMark', () => { + let rootDir: string; + let loader: FilesystemLoader; + + beforeEach(async () => { + rootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'os-34206-')); + await fs.mkdir(path.join(rootDir, 'view'), { recursive: true }); + await fs.mkdir(path.join(rootDir, 'app'), { recursive: true }); + await fs.writeFile(path.join(rootDir, 'view', 'rv_all.json'), JSON.stringify({ name: 'rv_all', label: 'All' })); + loader = new FilesystemLoader(rootDir, new Map([['json', new JSONSerializer()]]) as never); + }); + + afterEach(async () => { + await fs.rm(rootDir, { recursive: true, force: true }); + }); + + /** Directory mtimes have a coarse grain on some filesystems: step past it. */ + const settle = () => new Promise((r) => setTimeout(r, 20)); + + it('moves when a file appears where a read remembered a miss', async () => { + expect((await loader.load('view', 'rv_later')).data).toBeNull(); + const before = await loader.changeMark(); + expect(await loader.changeMark()).toBe(before); + await settle(); + await fs.writeFile(path.join(rootDir, 'view', 'rv_later.json'), JSON.stringify({ name: 'rv_later' })); + expect(await loader.changeMark()).not.toBe(before); + }); + + it('moves when a file a read resolved is edited in place', async () => { + expect((await loader.load('view', 'rv_all')).data).toMatchObject({ label: 'All' }); + const before = await loader.changeMark(); + await settle(); + await fs.writeFile(path.join(rootDir, 'view', 'rv_all.json'), JSON.stringify({ name: 'rv_all', label: 'All of them' })); + expect(await loader.changeMark()).not.toBe(before); + }); + + it('moves when a file a read resolved is removed', async () => { + await loader.load('view', 'rv_all'); + const before = await loader.changeMark(); + await fs.rm(path.join(rootDir, 'view', 'rv_all.json')); + expect(await loader.changeMark()).not.toBe(before); + }); + + it('control: a change in a type directory no read probed leaves it alone', async () => { + await loader.load('view', 'rv_all'); + const before = await loader.changeMark(); + await settle(); + await fs.writeFile(path.join(rootDir, 'app', 'rv_app.json'), JSON.stringify({ name: 'rv_app' })); + expect(await loader.changeMark()).toBe(before); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 0a1724d6e5e..ad81a72ad26 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -737,6 +737,49 @@ export class MetadataManager implements IMetadataService { // `package-slotted-store.ts`), whose key also names the package. private registry = new Map>(); + /** + * [#34206, ADR-0156 D2] This manager's change counter, moved by every path + * that changes what {@link get} / {@link getDiagnosed} / {@link list} can + * answer: an in-memory store write or drop ({@link writeRegistryEntry}, + * {@link deleteRegistryEntries}), every stored-set mutation the manager + * learns of ({@link invalidateListCache}: local writes, repository events, + * a cluster peer's write, HMR and artifact ingest, a watched file), a new + * loader, a new type registry, and every announcement to watchers. Read it + * through {@link revision}; compared, never interpreted. What it cannot + * see: a loader whose backing store changes with nobody telling this + * manager (a file edited with no watcher running), which a cache keyed on + * it bounds with its own time limit (ADR-0156 D1 (b)). + */ + private changeRevision = 0; + + /** See {@link changeRevision}. */ + get revision(): number { + return this.changeRevision; + } + + /** + * [#34206, ADR-0156 D5] A reading of every loader's backing store that + * moves when something outside this process changes what the loader would + * answer, for a cache's confirmation: the loaders in order, each by its own + * `changeMark()`. A `memory:` loader is in-process and written through this + * manager ({@link revision} sees it), so it contributes nothing. A loader + * of any other protocol that keeps no mark makes the whole answer + * `undefined`: nothing this manager can read says whether it moved. + */ + async loaderChangeMark(): Promise { + const marks: string[] = []; + for (const loader of this.loaders.values()) { + if (loader.contract.protocol === 'memory:') continue; + if (typeof loader.changeMark !== 'function') return undefined; + try { + marks.push(`${loader.contract.name}=${await loader.changeMark()}`); + } catch { + return undefined; + } + } + return JSON.stringify(marks); + } + // Type registry for metadata type info private typeRegistry: MetadataTypeRegistryEntryParsed[] = []; @@ -1014,6 +1057,7 @@ export class MetadataManager implements IMetadataService { */ setTypeRegistry(entries: MetadataTypeRegistryEntryParsed[]): void { this.typeRegistry = entries; + this.changeRevision++; } /** @@ -1162,6 +1206,7 @@ export class MetadataManager implements IMetadataService { registerLoader(loader: MetadataLoader) { assertWritableLoaderContract(loader); this.loaders.set(loader.contract.name, loader); + this.changeRevision++; this.logger.info(`Registered metadata loader: ${loader.contract.name} (${loader.contract.protocol})`); } @@ -1373,6 +1418,7 @@ export class MetadataManager implements IMetadataService { for (const replaced of replaces) typeStore.delete(replaced); typeStore.set(key, data); recordStoreWrite(typeStore, key); + this.changeRevision++; return existed; } @@ -1382,6 +1428,7 @@ export class MetadataManager implements IMetadataService { if (!typeStore) return; for (const key of keys ?? storeKeysNamed(typeStore, type, name)) typeStore.delete(key); if (typeStore.size === 0) this.registry.delete(type); + this.changeRevision++; } /** @@ -2057,6 +2104,7 @@ export class MetadataManager implements IMetadataService { * the registry was empty and the loader was not. */ private invalidateListCache(type: string): void { + this.changeRevision++; this.listCache.delete(type); this.inflightListReads.delete(type); // [#5089] The endpoint index is a cache of the same stored set, so it goes @@ -4461,6 +4509,7 @@ export class MetadataManager implements IMetadataService { } private notifyWatchersLocal(type: string, event: MetadataWatchEvent) { + this.changeRevision++; const callbacks = this.watchCallbacks.get(type); if (!callbacks) return; diff --git a/packages/objectql/src/engine-cascade-delete-objects.test.ts b/packages/objectql/src/engine-cascade-delete-objects.test.ts index 7e58cf747b9..8cb3d111309 100644 --- a/packages/objectql/src/engine-cascade-delete-objects.test.ts +++ b/packages/objectql/src/engine-cascade-delete-objects.test.ts @@ -333,4 +333,67 @@ describe('[#34206] getCascadeDeleteObjects is memoized on the registry object re engine.registry.registerObject({ name: 'cd_later', label: 'Later', fields: { id, name } } as any, '__test__'); expect(engine.getCascadeDeleteObjects('cd_later')).toEqual([]); }); + + /** + * [#34206 L1 N1] The two paths that move the object revision without a + * register or unregister of their own: a package enable or disable + * (through `invalidateAll`), and the restore of a refused registration run. + */ + describe('the memo follows a package enable and disable', () => { + const OWNER = 'com.cd.owner'; + const EXTENDER = 'com.cd.extender'; + const manifest = (pkgId: string, type: string) => + ({ id: pkgId, name: pkgId, version: '1.0.0', type, namespace: 'cd', ...(type === 'module' ? { dependencies: { [OWNER]: '^1.0.0' } } : {}) }) as any; + + /** `cd_ext_line` is owned by one package; a second package's extension makes it a cascading child of `cd_loner`. */ + async function makeExtendedEngine() { + const { engine } = await makeEngine(); + engine.registry.installPackage(manifest(OWNER, 'app'), 'code'); + engine.registry.installPackage(manifest(EXTENDER, 'module'), 'code'); + engine.registry.registerObject({ name: 'cd_ext_line', label: 'Ext line', fields: { id, name } } as any, OWNER, 'cd', 'own'); + engine.registry.registerObject({ + name: 'cd_ext_line', + fields: { cd_loner: { name: 'cd_loner', type: 'master_detail', reference: 'cd_loner', required: true } }, + } as any, EXTENDER, 'cd', 'extend'); + return engine; + } + + it('a disable moves the revision, and the next answer leaves out the child only the disabled extension made', async () => { + const engine = await makeExtendedEngine(); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual(['cd_ext_line']); + const before = engine.registry.objectRevision; + engine.registry.disablePackage(EXTENDER); + expect(engine.registry.objectRevision).not.toBe(before); + const walk = countWalk(engine); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual([]); + expect(walk).toHaveBeenCalled(); + }); + + it('an enable moves the revision again, and the next answer names the child once more', async () => { + const engine = await makeExtendedEngine(); + engine.registry.disablePackage(EXTENDER); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual([]); + const before = engine.registry.objectRevision; + engine.registry.enablePackage(EXTENDER); + expect(engine.registry.objectRevision).not.toBe(before); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual(['cd_ext_line']); + }); + }); + + it('a refused registration run: an answer memoized inside the run is retired by the restore', async () => { + const { engine } = await makeEngine(); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual([]); + const refusal = new Error('refused for the test'); + expect(() => engine.registry.restoringOnRefusal(() => { + engine.registry.registerObject({ + name: 'cd_refused_line', label: 'Refused line', + fields: { id, name, loner: { name: 'loner', type: 'master_detail', reference: 'cd_loner', required: true } }, + } as any, '__test__'); + // Non-vacuity: inside the run the child is registered and memoized. + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual(['cd_refused_line']); + throw refusal; + })).toThrow(refusal); + expect(engine.registry.getObject('cd_refused_line')).toBeUndefined(); + expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual([]); + }); }); diff --git a/packages/objectql/src/registry-revision.test.ts b/packages/objectql/src/registry-revision.test.ts new file mode 100644 index 00000000000..2fa63495298 --- /dev/null +++ b/packages/objectql/src/registry-revision.test.ts @@ -0,0 +1,116 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34206, ADR-0156 D2] `SchemaRegistry#revision`: every public write moves it, + * a read does not. The classification itself is exhaustive by type (a public + * method without a row in `SCHEMA_REGISTRY_METHOD_KINDS` fails the type check); + * these pins hold the runtime half: every row names a real method, the writes + * are wrapped, and the reads a cached answer is built from leave it alone. + */ + +import { describe, it, expect } from 'vitest'; +import { SchemaRegistry } from './registry.js'; +import { SCHEMA_REGISTRY_METHOD_KINDS, installSchemaRegistryRevision, schemaRegistryRevisionOf } from './registry-revision.js'; + +function makeRegistry(): SchemaRegistry { + const registry = new SchemaRegistry({ multiTenant: false }); + (registry as any).logLevel = 'silent'; + return registry; +} + +const OBJECT = { name: 'rv_account', label: 'Account', fields: { name: { name: 'name', type: 'text' } } } as any; +const PKG = { id: 'com.rv.app', name: 'com.rv.app', version: '1.0.0', type: 'app', namespace: 'rv' } as any; + +describe('[#34206] SchemaRegistry#revision', () => { + it('every classified name is a method of the class, and every write is wrapped', () => { + const proto = SchemaRegistry.prototype as unknown as Record; + const keys = Reflect.ownKeys(SCHEMA_REGISTRY_METHOD_KINDS); + expect(keys.length).toBeGreaterThan(50); + for (const key of keys) { + expect(typeof proto[key], String(key)).toBe('function'); + const kind = (SCHEMA_REGISTRY_METHOD_KINDS as Record)[key]; + expect(['read', 'write']).toContain(kind); + expect((proto[key] as Function).name === 'countedWrite', String(key)).toBe(kind === 'write'); + } + }); + + it('starts at 0, and each write moves it', () => { + const registry = makeRegistry(); + expect(registry.revision).toBe(0); + const steps: Array<[string, () => unknown]> = [ + ['installPackage', () => registry.installPackage(PKG, 'code')], + ['registerObject', () => registry.registerObject(OBJECT, PKG.id, 'rv', 'own')], + ['registerItem', () => registry.registerItem('view', { name: 'rv_all', object: 'rv_account', type: 'grid' } as any, 'name', PKG.id)], + ['registerApp', () => registry.registerApp({ name: 'rv_app', label: 'App' } as any, PKG.id)], + ['disablePackage', () => registry.disablePackage(PKG.id)], + ['enablePackage', () => registry.enablePackage(PKG.id)], + ['unregisterItem', () => registry.unregisterItem('view', 'rv_all')], + ['invalidateAll', () => registry.invalidateAll()], + ['unregisterObject', () => registry.unregisterObject('rv_account', { force: true })], + ]; + for (const [label, step] of steps) { + const before = registry.revision; + step(); + expect(registry.revision, label).toBeGreaterThan(before); + } + }); + + it('a write that does not register an object still moves it, where `objectRevision` stays', () => { + const registry = makeRegistry(); + registry.registerObject(OBJECT, '__test__'); + const objectRevision = registry.objectRevision; + const before = registry.revision; + registry.registerItem('view', { name: 'rv_all', object: 'rv_account', type: 'grid' } as any, 'name', '__test__'); + expect(registry.getItem('view', 'rv_all')).toBeDefined(); + expect(registry.objectRevision).toBe(objectRevision); + expect(registry.revision).toBeGreaterThan(before); + }); + + it('a write that throws still moves it', () => { + const registry = makeRegistry(); + const before = registry.revision; + expect(() => registry.restoringOnRefusal(() => { throw new Error('refused for the test'); })).toThrow('refused for the test'); + expect(registry.revision).toBeGreaterThan(before); + }); + + it('control: the reads a served answer is built from leave it alone', () => { + const registry = makeRegistry(); + registry.installPackage(PKG, 'code'); + registry.registerObject(OBJECT, PKG.id, 'rv', 'own'); + registry.registerItem('view', { name: 'rv_all', object: 'rv_account', type: 'grid' } as any, 'name', PKG.id); + registry.registerApp({ name: 'rv_app', label: 'App' } as any, PKG.id); + const before = registry.revision; + // Non-vacuity: each read finds what it reads. + expect(registry.getObject('rv_account')).toBeDefined(); + expect(registry.getAllObjects().some((o) => o.name === 'rv_account')).toBe(true); + expect(registry.getItem('view', 'rv_all')).toBeDefined(); + expect(registry.listItems('view').length).toBe(1); + expect(registry.getApp('rv_app')).toBeDefined(); + expect(registry.getAllApps().length).toBe(1); + expect(registry.getPackage(PKG.id)).toBeDefined(); + expect(registry.isPackageDisabled(PKG.id)).toBe(false); + registry.resolveItem('view', 'rv_all'); + registry.getObjectOwner('rv_account'); + expect(registry.revision).toBe(before); + }); + + it('each registry counts its own writes', () => { + const a = makeRegistry(); + const b = makeRegistry(); + a.registerObject(OBJECT, '__test__'); + expect(a.revision).toBeGreaterThan(0); + expect(b.revision).toBe(0); + expect(schemaRegistryRevisionOf(a)).toBe(a.revision); + }); + + it('installing twice does not wrap twice', () => { + const first = makeRegistry(); + const r0 = first.revision; + first.invalidateAll(); + const perCall = first.revision - r0; + installSchemaRegistryRevision(SchemaRegistry); + const second = makeRegistry(); + second.invalidateAll(); + expect(second.revision).toBe(perCall); + }); +}); diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts new file mode 100644 index 00000000000..a00edc761e3 --- /dev/null +++ b/packages/objectql/src/registry-revision.ts @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34206, ADR-0156 D2] The schema registry's own change counter: + * `SchemaRegistry#revision`, moved by every call to a public method that can + * change what the registry answers. + * + * ## Why a classification of the public surface, and not a list of bump sites + * + * The registry's state is a dozen maps and sets spread over a dozen facet + * files, and the existing `objectRevision` covers the object set only. A + * counter bumped by hand at each mutation would be a list of call sites inside + * the source: a new mutation path that forgets the bump is invisible. Instead + * every public method of `SchemaRegistry` is classified here, once, as a + * `read` or a `write`, and every `write` is wrapped so that the call moves the + * counter, before and after it runs (and after it settles, should one ever + * return a promise). Private methods are not wrapped: they run only inside a + * public call, which is the boundary. + * + * The classification is exhaustive BY TYPE: {@link SCHEMA_REGISTRY_METHOD_KINDS} + * is a `Record` over every public method name of the class, so a new public + * method fails the type check until someone writes down which kind it is. The + * safe answer for a method nobody has read is `write`: it costs cache hits + * (a consumer sees a move where nothing it reads changed), never staleness. + * + * ⛔ `read` means "changes nothing any registry answer is a function of". A + * method that fills a derived cache (`getObject` fills the merged-object + * cache) or records a diagnostic nobody's item answer reads + * (`applyNavContributions` notes a missing nav group for + * `getAppNavDiagnostics`) is a `read`. A judge that only throws or answers a + * refusal is a `read`. Anything that registers, removes, enables, disables, + * seals, claims, records an ownership fact or a listener is a `write`. + * + * What the counter cannot see: a caller that mutates, in place, an object the + * registry handed it. That is outside the registry's own code, and the time + * bound of any cache keyed on this counter covers it (ADR-0156 D1 (b)). + */ + +import type { SchemaRegistry } from './registry.js'; +import { FIND_BOUND_ACTION_COLLISIONS } from './registry-top-level.js'; + +/** Every public method key of `SchemaRegistry`, symbol keys included (accessors and fields excluded). */ +export type SchemaRegistryMethodName = { + [K in keyof SchemaRegistry]: SchemaRegistry[K] extends (...args: any[]) => any ? K : never; +}[keyof SchemaRegistry]; + +/** + * The kind of every public `SchemaRegistry` method. See the module header for + * what `read` admits. Exhaustive by type: adding a public method to the class + * without a row here is a compile error. + */ +export const SCHEMA_REGISTRY_METHOD_KINDS: Readonly> = Object.freeze({ + // Package enablement and lifecycle listeners + setInitialDisabledPackageIds: 'write', + onPackageEnabled: 'write', + onPackageUninstalled: 'write', + restoringOnRefusal: 'write', + recordRestoreOnRefusal: 'write', + // Namespaces and claims + registerNamespace: 'write', + unregisterNamespace: 'write', + getNamespaceOwner: 'read', + getNamespaceOwners: 'read', + defaultRecordPageHoldersOf: 'read', + securityCatalogNamesHeldBy: 'read', + claimBareNameFunctions: 'write', + releaseBareNameFunctions: 'write', + sealBareNameHolders: 'write', + // Objects + objectRegistrationRefusal: 'read', + registerObject: 'write', + resolveObject: 'read', + getStorageObject: 'read', + getAllStorageObjects: 'read', + findUnboundActionTargets: 'read', + tenantRuleCopyRefusal: 'read', + foldObjectExtendersOnto: 'read', + materializeServedObjectOnto: 'read', + provisionSearchCompanionOnto: 'read', + stripProvisionedSearchCompanionFrom: 'read', + stripMaterializedStampsFrom: 'read', + setDeploymentPlatformGlobalObjects: 'write', + getObject: 'read', + getAllObjects: 'read', + getObjectContributors: 'read', + getObjectExtensionsOf: 'read', + getObjectOwner: 'read', + getPackagedObjectOwner: 'read', + getPackagedObjectBase: 'read', + extendContributionRefusal: 'read', + registerObjectExtension: 'write', + withdrawObjectExtension: 'write', + removeObjectOverlay: 'write', + assertSingleOwnerPerObject: 'read', + assertPackageUninstallable: 'read', + unregisterObjectsByPackage: 'write', + unregisterObject: 'write', + // Items + registerItem: 'write', + validate: 'read', + unregisterItem: 'write', + unregisterItemsByPackage: 'write', + replacingPackageBody: 'write', + getItem: 'read', + overlayRowBinding: 'read', + packageScopedHoldersOf: 'read', + getPackageScopedItem: 'read', + getEnvironmentScopedItem: 'read', + getEnvironmentScopedActions: 'read', + readsByPackage: 'read', + resolveItem: 'read', + refuseAmbiguousObjectLessAction: 'read', + removePackageOverlaySlots: 'write', + getArtifactItem: 'read', + removeRuntimeShadow: 'write', + removeOverlayEntry: 'write', + listItems: 'read', + isPackageDisabled: 'read', + isObjectPackageDisabled: 'read', + isFlowOfDisabledPackage: 'read', + isActionWithheldByDisabledPackage: 'read', + getRegisteredTypes: 'read', + // Packages + installPackage: 'write', + refuseResidualNamespaceNameConflicts: 'read', + recordResidualNamespaceHolder: 'write', + uninstallPackage: 'write', + getPackage: 'read', + recordResidualOwnerDependencies: 'write', + residualOwnerDependenciesOf: 'read', + getAllPackages: 'read', + enablePackage: 'write', + disablePackage: 'write', + updatePackageManifest: 'write', + // Apps and navigation + registerApp: 'write', + getApp: 'read', + getAllApps: 'read', + registerAppNavContribution: 'write', + setPackageNavContributions: 'write', + getAppNavContributions: 'read', + applyNavContributions: 'read', + getAppNavDiagnostics: 'read', + // Plugins and kinds + registerPlugin: 'write', + getAllPlugins: 'read', + registerKind: 'write', + getAllKinds: 'read', + // Picklists + registerPicklistExtension: 'write', + resolvePicklistOptions: 'read', + picklistReferenceVerdict: 'read', + findUnresolvedPicklistReferences: 'read', + findOrphanPicklistExtensions: 'read', + findOutsideClosurePicklistReferences: 'read', + sealPicklistVocabulary: 'write', + refusePicklistArrival: 'write', + registeringPicklistArrival: 'write', + admitPicklistArrival: 'write', + judgePicklistArrival: 'write', + findDisagreeingPicklistReferences: 'read', + // The boot audit of bound code actions, under its symbol key + [FIND_BOUND_ACTION_COLLISIONS]: 'read' as const, + // Cache drops and reset + invalidate: 'write', + invalidateAll: 'write', + reset: 'write', +}); + +/** The counter of each registry, held beside it rather than on it. */ +const revisions = new WeakMap(); + +/** The revision of `registry`: `0` until its first write. */ +export function schemaRegistryRevisionOf(registry: object): number { + return revisions.get(registry) ?? 0; +} + +function bump(registry: object): void { + revisions.set(registry, (revisions.get(registry) ?? 0) + 1); +} + +/** + * Wrap every `write` method of `registryClass.prototype` so that a call moves + * the instance's revision. Called once, by `registry.ts`, right after the + * class is defined. Idempotent per class. + */ +export function installSchemaRegistryRevision(registryClass: { prototype: object }): void { + const proto = registryClass.prototype as Record; + if (installed.has(proto)) return; + installed.add(proto); + for (const name of Reflect.ownKeys(SCHEMA_REGISTRY_METHOD_KINDS)) { + if ((SCHEMA_REGISTRY_METHOD_KINDS as Record)[name] !== 'write') continue; + const descriptor = Object.getOwnPropertyDescriptor(proto, name); + const original = descriptor?.value; + if (typeof original !== 'function') { + throw new Error(`[ADR-0156] SchemaRegistry has no method '${String(name)}' to count; update SCHEMA_REGISTRY_METHOD_KINDS.`); + } + Object.defineProperty(proto, name, { + ...descriptor, + value: function countedWrite(this: object, ...args: unknown[]): unknown { + bump(this); + let result: unknown; + try { + result = original.apply(this, args); + } finally { + bump(this); + } + if (result instanceof Promise) { + return result.finally(() => bump(this)); + } + return result; + }, + }); + } +} + +const installed = new WeakSet(); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 44d40587be2..d03c7c93a56 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -180,6 +180,7 @@ import { PackagesFacet } from './registry-packages.js'; import { AppsFacet } from './registry-apps.js'; // [#33949 codemod] Plugins, kinds, shared picklists and reset: the methods of the same names below hand the bodies what they read (`PicklistsHost`). import { PicklistsFacet } from './registry-picklists.js'; +import { installSchemaRegistryRevision, schemaRegistryRevisionOf } from './registry-revision.js'; // [#33949 codemod] The facets' hosts, one per registry, which the static block at the end of the class builds. import { appsHost, bareNamesHost, itemsHost, namespacesAndClaimsHost, objectRegistrationHost, packageAddressingHost, @@ -2099,6 +2100,17 @@ export class SchemaRegistry { return this._objectRevision; } + /** + * [#34206, ADR-0156 D2] Moved by every call to a public method that can + * change what this registry answers: items, objects, packages and their + * enablement, navigation contributions, namespaces, claims. Compared, + * never interpreted. The classification of the public surface, and why it + * is not a list of bump sites, is in `registry-revision.ts`. + */ + get revision(): number { + return schemaRegistryRevisionOf(this); + } + /** Namespace → Set (multiple packages can share a namespace) */ private namespaceRegistry = new Map>(); @@ -6282,6 +6294,9 @@ export class SchemaRegistry { } } +// [#34206, ADR-0156 D2] Every public write moves `revision`; see `registry-revision.ts`. +installSchemaRegistryRevision(SchemaRegistry); + /** * [#31699, epic ruling on the App pair's plain slot] Whether `item`, a row of a * paired `.custom` package that binds to `packageId` (its base), declares diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 45d1cf202bd..4c89d09b2d6 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -251,6 +251,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/meta-compile-cache.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/migrations/recorded-by-sentinel.test.ts", "verb": "delete", From e350186c30df499adc2e4802764d10507c1665f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:46:06 +0000 Subject: [PATCH 2/4] fix(metadata-protocol): the compile cache confirms on the rows' content and retires the row cache (#34206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Answers L1 6931948189 and contract review 6932160915 on #34494. - The store reading is a digest of every sys_metadata row's content, so a write that leaves updated_at alone, a timestamp-preserving import or a peer with a slow clock still moves it. - Every confirmation retires the overlay row cache and rebases the bucket's stamp: a recompile reads rows at least as new as the reading, and a compile in flight across a confirmation is not stored. - No entry is renewed past 10 bounds, the backstop for what no reading sees. - FilesystemLoader caps the probed type directories at 1000. - Clause-② yes in the changeset; docs, env row and comments follow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp --- .changeset/34206-shared-compile-cache.md | 5 +- content/docs/concepts/metadata-lifecycle.mdx | 13 ++ .../docs/deployment/environment-variables.mdx | 2 +- .../src/meta-compile-cache.test.ts | 144 ++++++++++++++++-- .../src/meta-compile-cache.ts | 133 +++++++++++----- .../src/meta-overlay-cache.ts | 21 +++ .../src/metadata-diagnostics.ts | 9 +- .../metadata/src/loaders/filesystem-loader.ts | 16 +- .../metadata-manager-change-revision.test.ts | 10 ++ packages/objectql/src/registry-revision.ts | 8 +- 10 files changed, 297 insertions(+), 64 deletions(-) diff --git a/.changeset/34206-shared-compile-cache.md b/.changeset/34206-shared-compile-cache.md index 8f75fb80be9..7d69db9f617 100644 --- a/.changeset/34206-shared-compile-cache.md +++ b/.changeset/34206-shared-compile-cache.md @@ -6,14 +6,15 @@ perf(metadata-protocol): the served item read caches its caller-independent compiled answer (ADR-0156) -Clause-②: no +Clause-②: yes Metadata-protocol: none `getMetaItem` (the served face of `GET /api/v1/meta/:type/:name`, and the per-item read an app bundle makes for every app, object, view, page and dashboard it names) no longer recompiles an item whose sources have not changed. Every caller gets the same answer it got before, the response body and ETag included: only the server's work per request moves. - **What is cached.** The compiled envelope of a by-name read of `app`, `object`, `view`, `page` and `dashboard` items, per engine. A read for a package, a state, a member or a draft preview is never cached. The per-caller gate, field mask, translation and ETag stay computed on every request, and the live trailers (`registration`, `disabledActions`, `cascadeDeleteObjects`) are read on every hit. - **What retires it.** Each source counts its own changes at its own mutation point: the `sys_metadata` overlay generation, the schema registry's `objectRevision` and a new `revision` that every public write of `SchemaRegistry` moves (the classification of its public methods is exhaustive by type), and a new `revision` on `MetadataManager`. Any move drops every entry. A source without its counter makes the cache decline. -- **What another process can change.** After a bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms) the cache confirms before it recompiles: a reading of the stored rows (count and latest change) and of each loader's backing store (`FilesystemLoader` stats the type directories and files its reads touched). If nothing moved, the entries stand for another bound. A loader that keeps no change mark makes every entry recompile at its bound, never renewed. +- **What another process can change.** After a bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms) the cache confirms before it recompiles: a digest of every stored row's content (so a write that leaves `updated_at` alone, or stamps it from a clock that is behind, still moves it) and each loader's reading of its backing store (`FilesystemLoader` stats the type directories and files its reads touched). If nothing moved, the entries stand for another bound, up to 10 bounds from when each was compiled. Every confirmation also retires the overlay row cache, so a recompile reads rows at least as new as the reading, and a read in flight across a confirmation is not stored. A loader that keeps no change mark makes every entry recompile at its bound, never renewed. +- **New public members (additive).** `SchemaRegistry#revision`, `MetadataManager#revision`, `MetadataManager#loaderChangeMark()`, the optional `MetadataLoader#changeMark()` and `FilesystemLoader#changeMark()`. - `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read, the same reads in the same order. On a showcase Setup bundle, an immediate repeat made 213 database reads before and 9 after. diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index 2905819a3fd..b8d293065fd 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -313,6 +313,19 @@ The hash is `sha256:` + 64-hex of a canonical JSON serialization of the body, wi > the in-process `memory` driver, 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](/docs/deployment/environment-variables). +> +> The served by-name read also caches its **compiled** answer for an `app`, +> `object`, `view`, `page` or `dashboard` (ADR-0156), the part that does not +> depend on the caller; the per-caller gate, field mask, translation and +> `ETag` still 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, `0` disables it), where it reads every `sys_metadata` row's content +> and the metadata files it read, and recompiles if any of them moved, also +> when a write left `updated_at` alone. Each such check also drops the cached +> rows, so the recompile reads the store as it is then, and no compiled answer +> is kept past ten bounds. --- diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index b1da9cb6fb1..633de87bf2d 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -430,7 +430,7 @@ With several replicas declared over the Redis cluster driver (`OS_CLUSTER_REPLIC | `OS_SANDBOX_WALL_CEILING_MS` | number | `30000` | Wall-clock ceiling (ADR-0102) — the backstop that cuts a hook/action body stuck on a host call that never settles (which burns no CPU, so the CPU budget alone would never fire). The effective ceiling is `max(this, cpuBudget)`, so it can never cut a body still inside its CPU budget. Positive integer only; unset keeps 30s. | | `OS_LOCALIZATION_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of a workspace's reference localization (`timezone` / `locale` / `currency`, read from `sys_setting`) — leg C of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Unlike `OS_AUTHZ_GRANTS_CACHE_TTL_MS` (which is off by default) this one ships **on**, because its invalidation is synchronous and in-process rather than TTL-bound: a `localization` settings change, a write to `sys_setting` or `sys_platform_setting` (the tables the answer is read from), and a non-`write` bump of the engine write epoch each retire a cached answer immediately. A write to any other object does not. So the TTL only bounds what none of these seams can see — a write made on another replica with no cluster bridge attached at all: neither the `metadata.mutated` channel's receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch`, #13609) nor the `authz.invalidated` bridge, both of which bump this same epoch when attached. ⚠️ A malformed value reads as `0` (off), the opposite arm from the grants variable and deliberately so: there `0` is also the default, whereas here folding `3OOO` (letter O) into the default would hand you a **longer** window than the one you were setting. Deployment config only — never a settings row, because `sys_setting` is the table this cache caches. | | `OS_METADATA_OVERLAY_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of the `sys_metadata` overlay rows read inside `getMetaItems` (the list read) and `getMetaItem` (the served by-name read the REST API-exposure gate makes on every `/data` request) — leg D of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Ships **on**, for the same reason as `OS_LOCALIZATION_CACHE_TTL_MS`: invalidation is synchronous and in-process, because every `sys_metadata` write goes through the engine, whose middleware retires the entry when the write's statement completes, before the next read. Outside a transaction that is the commit. Inside an engine transaction it is earlier than the commit: a read that lands between the statement and the commit can keep the pre-commit rows until the next `sys_metadata` write or the TTL. A write to any other object does not retire it; a non-`write` bump of the engine write epoch retires it wholesale. What is cached is the overlay ROW SET only — never the merged answer — so the SchemaRegistry, the MetadataService and the artifact table are re-consulted on every call, cached or not, and the read-side registry hydration keeps running on a cache hit. The TTL therefore bounds one thing: a write made on **another replica** with no cluster bridge attached at all — neither the `metadata.mutated` channel's own receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch` right after registry convergence, #13609) nor the `authz.invalidated` bridge, either of which retires this entry the moment it is attached and fires. ⚠️ A malformed value reads as `0` (off) — same arm and same reason as `OS_LOCALIZATION_CACHE_TTL_MS`. Deployment config only, never a settings row. | -| `OS_METADATA_COMPILE_CACHE_TTL_MS` | number | `30000` | Bound, in milliseconds, for the per-environment cache of compiled item answers ([ADR-0156](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0156-compiled-metadata-answer-cache-every-source-counts-its-own-changes.md)): the served item read (`getMetaItem`) of an app, object, view, page or dashboard, which the app bundle (`GET /api/v1/meta/app/:appId/bundle`) and the item reads make. `0` means **off**, a real path: the read is the uncached one, the same reads in the same order. Only the caller-independent answer is cached; the per-caller gate, field mask, translation and `ETag` are computed on every request. A local change is seen at once: the cache keeps the change counter of every source it reads (the `sys_metadata` overlay generation, the schema registry's `revision` and `objectRevision`, the metadata service's `revision`) and drops every entry when one moves; a source without its counter makes it decline. When the bound passes it confirms before it recompiles, with one reading of what this process cannot see (the `sys_metadata` row count and newest `updated_at`, and each metadata loader's own change mark: the file loader stats the directories and files its reads touched); unchanged, the entries stand for another bound; unreadable, nothing is renewed. The bound is therefore how long another replica's write with no cluster bridge, or a file edited under a running process, can stay unseen. ⚠️ A malformed value reads as `0` (off). Deployment config only, never a settings row. | +| `OS_METADATA_COMPILE_CACHE_TTL_MS` | number | `30000` | Bound, in milliseconds, for the per-environment cache of compiled item answers ([ADR-0156](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0156-compiled-metadata-answer-cache-every-source-counts-its-own-changes.md)): the served item read (`getMetaItem`) of an app, object, view, page or dashboard, which the app bundle (`GET /api/v1/meta/app/:appId/bundle`) and the item reads make. `0` means **off**, a real path: the read is the uncached one, the same reads in the same order. Only the caller-independent answer is cached; the per-caller gate, field mask, translation and `ETag` are computed on every request. A local change is seen at once: the cache keeps the change counter of every source it reads (the `sys_metadata` overlay generation, the schema registry's `revision` and `objectRevision`, the metadata service's `revision`) and drops every entry when one moves; a source without its counter makes it decline. When the bound passes it confirms before it recompiles, with one reading of what this process cannot see (a digest of every `sys_metadata` row's content, which moves even when a write leaves `updated_at` alone, and each metadata loader's own change mark: the file loader stats the directories and files its reads touched); unchanged, the entries stand for another bound, up to 10 bounds from when each was compiled; unreadable, nothing is renewed. Each confirmation also retires the overlay row cache, so the recompile reads the rows as they are now. The bound is therefore how long another replica's write with no cluster bridge, or a file created, removed or edited under a running process, can stay unseen; a file edit no `stat` can tell apart (same size, within the file system's time grain) is seen within 10 bounds. ⚠️ A malformed value reads as `0` (off). Deployment config only, never a settings row. | | `OS_INLINE_SEED_BUDGET_MS` | number | `8000` | Time budget for synchronous seed execution at boot before deferring to a worker. | | `OS_TENANT_AUDIT` | flag | `1` | Set to `0` to silence the tenant-isolation audit warnings emitted by the SQL driver. | diff --git a/packages/metadata-protocol/src/meta-compile-cache.test.ts b/packages/metadata-protocol/src/meta-compile-cache.test.ts index eb1fa26823a..f5388741594 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.test.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.test.ts @@ -16,7 +16,7 @@ import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; // The served read reaches a dynamic `import('@objectstack/lint')` (metadata diagnostics): pay its load at collection. import '@objectstack/lint'; import { ObjectStackProtocolImplementation } from './protocol.js'; -import { META_COMPILE_CACHE_TTL_ENV, metaCompileCacheTtlMs } from './meta-compile-cache.js'; +import { META_COMPILE_CACHE_MAX_AGE_BOUNDS, META_COMPILE_CACHE_TTL_ENV, metaCompileCacheTtlMs } from './meta-compile-cache.js'; import { servedRowChangedAtOf } from './served-row-changed-at.js'; type Row = Record; @@ -45,6 +45,13 @@ const storedView = (label: string): Row => ({ metadata: JSON.stringify({ name: 'widget_list', label, object: 'widget' }), }); +/** A stored row of one of the other cached types, bare body. */ +const storedItem = (type: string, name: string, body: Row): Row => ({ + id: `r_${type}`, type, name, state: 'active', package_id: null, + updated_at: '2026-11-16T00:00:00.000Z', + metadata: JSON.stringify({ name, ...body }), +}); + interface HarnessOptions { /** Omit the registry's `revision` (the cache must decline). */ registryRevision?: boolean; @@ -170,17 +177,26 @@ describe('[#34206, ADR-0156] the compiled item answer is cached while every sour }); it('cached ≡ uncached: the hit equals the answer the cache-off read gives, for each cached type', async () => { - const rows = [storedObject('Widget'), storedView('All widgets')]; - for (const [type, name] of [['object', 'widget'], ['view', 'widget_list']] as const) { + const rows = [ + storedObject('Widget'), storedView('All widgets'), + storedItem('app', 'widget_app', { label: 'Widgets', navigation: [{ id: 'nav_widget', type: 'object', objectName: 'widget' }] }), + storedItem('page', 'widget_page', { label: 'Widget page', type: 'record', object: 'widget', regions: [] }), + storedItem('dashboard', 'widget_dashboard', { label: 'Widget board', widgets: [] }), + ]; + const types = [['object', 'widget'], ['view', 'widget_list'], ['app', 'widget_app'], ['page', 'widget_page'], ['dashboard', 'widget_dashboard']] as const; + for (const [type, name] of types) { const cached = harness(rows); await read(cached, type, name); + const readsBefore = cached.reads.length; const hit = await read(cached, type, name); + expect(cached.reads.length).toBe(readsBefore); vi.stubEnv(META_COMPILE_CACHE_TTL_ENV, '0'); const uncached = await read(harness(rows), type, name); vi.unstubAllEnvs(); expect(hit).toEqual(uncached); expect(servedRowChangedAtOf(hit)).toBe(servedRowChangedAtOf(uncached)); expect(servedRowChangedAtOf(hit)).toBeDefined(); + expect(hit.item.name).toBe(name); } }); @@ -420,6 +436,19 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp expect(h.byNameReads('widget')).toBeGreaterThan(before); }); + /** Replace the confirmation's store reading (the whole-store `find` over the body column) until the returned restore runs. */ + const onStoreMark = (h: ReturnType, impl: (real: () => Promise) => Promise) => { + const find = h.engine.find as (table: string, q?: { where?: Row; fields?: string[] }) => Promise; + let calls = 0; + h.engine.find = (table: string, q: { where?: Row; fields?: string[] } = {}) => { + const isMark = table === 'sys_metadata' && Object.keys(q.where ?? {}).length === 0 && (q.fields ?? []).includes('metadata'); + if (!isMark) return find(table, q); + calls += 1; + return impl(() => find(table, q)); + }; + return { restore: () => { h.engine.find = find; }, get calls() { return calls; } }; + }; + it('an in-process write that lands while the confirmation awaits the store is not hidden by the entry it retires', async () => { const clock = atBound(); const h = harness([storedObject('Widget')]); @@ -427,33 +456,91 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp clock.pass(); await read(h); // The registry moves while the confirmation's store reading is in flight. - const count = h.engine.count as (...a: unknown[]) => Promise; - h.engine.count = async (...a: unknown[]) => { - h.engine.count = count; + const mark = onStoreMark(h, async (real) => { (h.registry.revision as number)++; - return count(...a); - }; + mark.restore(); + return real(); + }); clock.pass(); const before = h.byNameReads('widget'); await read(h); - expect(h.engine.count).toBe(count); // non-vacuity: the confirmation ran and saw the move mid-flight + expect(mark.calls).toBe(1); // non-vacuity: the confirmation ran and saw the move mid-flight expect(h.byNameReads('widget')).toBeGreaterThan(before); }); + it('a compute that spans a confirmation which dropped the entries is not stored under the new reading', async () => { + const clock = atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + // Read A's compute is held open after it read the old row. + const compute = h.protocol.readMetaItemFace.bind(h.protocol) as (...a: unknown[]) => Promise; + let release!: () => void; + const gate = new Promise((r) => { release = r; }); + let computed!: () => void; + const inCompute = new Promise((r) => { computed = r; }); + let held = false; + h.protocol.readMetaItemFace = async (...a: unknown[]) => { + const answer = await compute(...a); + if (held) return answer; + held = true; + computed(); + await gate; + return answer; + }; + (h.registry.revision as number)++; // a fresh bucket, so A misses + const a = read(h); + await inCompute; + // Another writer's change lands, the bound passes, and read B's + // confirmation finds the store moved: it drops the entries and stores + // the new answer. + rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + release(); + expect((await a).item.label).toBe('Widget'); // A answers what it read + // A's older answer was not stored over B's under the new reading. + expect((await read(h)).item.label).toBe('Gadget'); + }); + + it('another writer\'s change that leaves every bookkeeping column alone is still seen at the bound', async () => { + const clock = atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + clock.pass(); + await read(h); + // A write that bypasses the engine: same id, same updated_at, new body. + rows[0] = { ...rows[0], metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) }; + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + }); + + it('another node\'s write stamped with an OLDER updated_at than the newest stored is still seen at the bound', async () => { + const clock = atBound(); + const rows = [storedObject('Widget', '2026-11-16T05:00:00.000Z'), storedView('All')]; + const h = harness(rows); + await read(h); + clock.pass(); + await read(h); + rows[0] = storedObject('Gadget', '2026-11-16T00:00:01.000Z'); // a clock behind the newest row + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + }); + it('a store outage at the confirmation fails the read as the uncached read does, and never serves the unconfirmed entry', async () => { const clock = atBound(); const h = harness([storedObject('Widget')]); await read(h); - const count = h.engine.count as (...a: unknown[]) => Promise; const outage = new Error('connect ECONNREFUSED 127.0.0.1:5432'); - h.engine.count = async () => { throw outage; }; + const mark = onStoreMark(h, async () => { throw outage; }); clock.pass(); const failure = await read(h).then(() => undefined, (e: unknown) => e as Error & { cause?: unknown }); expect(failure).toBeInstanceOf(Error); expect(failure?.cause).toBe(outage); // The store is back with the reading the entry was last confirmed at: // the confirmation now succeeds, and the answer is right. - h.engine.count = count; + mark.restore(); expect((await read(h)).item.label).toBe('Widget'); }); @@ -461,13 +548,44 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp const clock = atBound(); const h = harness([storedObject('Widget')]); await read(h); - h.engine.count = async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); }; + const mark = onStoreMark(h, async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); }); clock.pass(); const before = h.byNameReads('widget'); expect((await read(h)).item.label).toBe('Widget'); + expect(mark.calls).toBe(1); expect(h.byNameReads('widget')).toBeGreaterThan(before); }); + it('the recompile after another writer\'s change reads the new row, not the overlay row cache\'s older one', async () => { + vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives the compile bound + const clock = atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + await read(h); + clock.pass(); + await read(h); + rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + clock.pass(); + expect((await read(h)).item.label).toBe('Gadget'); + }); + + it(`no entry stands past ${META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds, renewals included`, async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + await read(h); + const compiled = h.byNameReads('widget'); + for (let i = 1; i < META_COMPILE_CACHE_MAX_AGE_BOUNDS; i++) { + clock.pass(); + await read(h); + } + expect(h.byNameReads('widget')).toBe(compiled); // renewed every bound so far + clock.pass(); + await read(h); + expect(h.byNameReads('widget')).toBeGreaterThan(compiled); + }); + it('⛔ a source the confirmation cannot observe: nothing is renewed, every bound recompiles', async () => { const clock = atBound(); const h = harness([storedObject('Widget')], { metadataService: 'no-mark' }); diff --git a/packages/metadata-protocol/src/meta-compile-cache.ts b/packages/metadata-protocol/src/meta-compile-cache.ts index 11dea216ae8..6ffcd860d22 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.ts @@ -48,17 +48,29 @@ * counters above at their stamp, and a reading of everything outside this * process that the bound exists for ({@link readConfirmationMark}): * - * - the stored rows: the `sys_metadata` row count and its newest - * `updated_at` ({@link readStoreMark}), which another writer's insert, - * update or delete moves; + * - the stored rows: a digest of every `sys_metadata` row's id, state, + * version, checksum, change time and stored body ({@link readStoreMark}). + * It reads the content itself, so it moves on another writer's insert, + * update or delete whatever that writer did to the bookkeeping columns: a + * write that bypasses the engine and leaves `updated_at` alone, an import + * that preserves timestamps, a node whose clock is behind. One read of the + * whole store per bound per engine, in place of recompiling every entry; * - the metadata service's loaders: `loaderChangeMark()` on the service * (`@objectstack/metadata`), each loader's own reading of its backing * store (the file loader stats the directories and files its reads * touched, so a file a deployment creates, removes or edits under a * running process moves it). * - * Nothing moved: the entries are kept for another bound. Anything moved: - * every entry goes. + * Nothing moved: the entries are kept for another bound, up to + * {@link META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds from when each was + * compiled. The age cap is the backstop for what no reading sees: a file + * edited in place to the same size within the file system's time + * granularity, and an object the schema registry handed out that a caller + * then edited in place (`registry-revision.ts`). Anything moved: every entry + * goes. Either way the overlay row + * cache is retired (`retireMetaOverlayCache`), so a recompile under the new + * reading reads rows at least as new as the reading, never rows that cache + * filled before another writer's change. * * ⛔ A renewal is a claim about what was looked at (ADR-0156 D5). When the * confirmation cannot read one of those (the store cannot be read, the @@ -73,7 +85,11 @@ * rare, and a per-entry dependency graph would be the call-site list ADR-0127 * D2 forbids in another shape. A read in flight across a change is stamped * with the counters it STARTED under and is not stored when they moved - * before it settled. + * before it settled. A confirmation moves the stamp too (it retires the + * overlay row cache and rebases the bucket on the new generation), so a read + * that spans one is never stored: it may have compiled from what the + * confirmation found moved, and storing it under the new reading would renew + * that old answer for as long as nothing moves again. * * ## Values are cloned in both directions * @@ -82,7 +98,12 @@ * entry, and a hit is byte-equivalent to a miss. An envelope that cannot be * cloned is not stored. The served row's change time * (`servedRowChangedAtOf`, a non-enumerable symbol member) is kept beside the - * clone and put back on every served copy. + * clone and put back on every served copy. The other non-enumerable marks a + * compile can leave on an item (`markResolvedPicklistOptions`, + * `bindStoredRow`) do not travel on the clone. Each is read inside the + * compile, before the store (the diagnostics), or from the registry, never + * from a served answer (the flow binding), and each module states that a copy + * reads as unmarked and fails toward the safe side. * * ## Hydration (ADR-0156 D4) * @@ -91,8 +112,9 @@ * the registry exactly as a miss does. */ +import { createHash } from 'node:crypto'; import { isMissingTableError } from '@objectstack/metadata/errors'; -import { readOverlayCacheGeneration } from './meta-overlay-cache.js'; +import { readOverlayCacheGeneration, retireMetaOverlayCache } from './meta-overlay-cache.js'; import { metadataReadFailureError } from './protocol-client-failures.js'; import { servedRowChangedAtOf, withServedRowChangedAt } from './served-row-changed-at.js'; @@ -107,6 +129,14 @@ export const META_COMPILE_CACHE_TTL_ENV = 'OS_METADATA_COMPILE_CACHE_TTL_MS'; */ export const META_COMPILE_CACHE_DEFAULT_TTL_MS = 30_000; +/** + * How many bounds an entry may stand, renewals included, before it is + * compiled again whatever the confirmation read. A backstop for the one + * change a reading cannot tell apart: one made and undone between two + * confirmations, with a compile in between that read the middle state. + */ +export const META_COMPILE_CACHE_MAX_AGE_BOUNDS = 10; + /** The types whose served item read is cached: the app bundle's member types. */ export const META_COMPILE_CACHE_TYPES: ReadonlySet = new Set(['app', 'object', 'view', 'page', 'dashboard']); @@ -154,10 +184,13 @@ interface CompileEntry { /** A private clone of the envelope, the live trailers removed. Never handed out un-cloned. */ readonly envelope: Record; readonly changedAt: string | undefined; + /** When it was compiled: no entry is renewed past {@link META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds. */ + readonly compiledAt: number; } interface CompileBucket { - readonly stamp: CompileStamp; + /** Rebased only by a confirmation's own retirement of the overlay row cache ({@link confirm}). */ + stamp: CompileStamp; /** The confirmation reading ({@link readConfirmationMark}) the entries were last confirmed at; `undefined` until the first. */ mark: string | undefined; /** Until when the entries stand without a confirmation. */ @@ -235,45 +268,47 @@ export async function readConfirmationMark(engine: unknown, metadataService: obj return JSON.stringify([store, loaders]); } +/** The `sys_metadata` columns the store reading digests: identity, state, the bookkeeping columns and the body itself. */ +export const STORE_MARK_FIELDS: readonly string[] = Object.freeze(['id', 'state', 'version', 'checksum', 'updated_at', 'metadata']); + /** - * The store reading the confirmation compares (ADR-0156 D5): the number of - * `sys_metadata` rows and the newest `updated_at` among them, read as the - * system. Another writer's insert moves both, its update moves the second, - * its delete moves the first. + * The store reading the confirmation compares (ADR-0156 D5): a digest of + * every `sys_metadata` row's {@link STORE_MARK_FIELDS}, read as the system, + * in id order. It reads the stored body, not only the bookkeeping columns, so + * it moves on any insert, delete or content change another writer makes: + * also one that bypasses the engine and leaves `updated_at`, `version` and + * `checksum` alone, an import that preserves timestamps, and a node whose + * clock writes an older `updated_at` than the newest already stored. Only the + * digest is kept; no row leaves this function. * * `undefined` when there is nothing to read it with (an engine without - * `count` / `find`) or no store yet (`sys_metadata` not provisioned, by error - * type): the bucket's entries then go, and nothing is renewed. Any other - * failure is thrown as the uncached read throws it + * `find`) or no store yet (`sys_metadata` not provisioned, by error type): + * the bucket's entries then go, and nothing is renewed. Any other failure is + * thrown as the uncached read throws it * (`rethrowUnlessMetadataStoreUnprovisioned`): an outage is never read as * "nothing moved", and never served from the entries it could not confirm. */ export async function readStoreMark(engine: unknown): Promise { - const ql = engine as { - count?: (object: string, query: unknown) => Promise; - find?: (object: string, query: unknown) => Promise; - }; - if (typeof ql?.count !== 'function' || typeof ql?.find !== 'function') return undefined; + const ql = engine as { find?: (object: string, query: unknown) => Promise }; + if (typeof ql?.find !== 'function') return undefined; + let rows: unknown; try { - const context = { isSystem: true }; - const [count, newest] = await Promise.all([ - ql.count('sys_metadata', { where: {}, context }), - ql.find('sys_metadata', { - where: {}, - fields: ['updated_at'], - orderBy: [{ field: 'updated_at', order: 'desc' }], - limit: 1, - context, - }), - ]); - if (typeof count !== 'number') return undefined; - const row = Array.isArray(newest) ? newest[0] as { updated_at?: unknown } | undefined : undefined; - const at = row?.updated_at instanceof Date ? row.updated_at.toISOString() : String(row?.updated_at ?? ''); - return JSON.stringify([count, at]); + rows = await ql.find('sys_metadata', { where: {}, fields: [...STORE_MARK_FIELDS], context: { isSystem: true } }); } catch (error) { if (isMissingTableError(error, 'sys_metadata')) return undefined; throw metadataReadFailureError(error); } + if (!Array.isArray(rows)) return undefined; + const lines = rows.map((row) => { + const r = (row ?? {}) as Record; + return JSON.stringify(STORE_MARK_FIELDS.map((field) => { + const value = r[field]; + return value instanceof Date ? value.toISOString() : value ?? null; + })); + }).sort(); + const digest = createHash('sha1'); + for (const line of lines) digest.update(line).update('\n'); + return `${rows.length}:${digest.digest('hex')}`; } /** Whether this request is one the cache answers. */ @@ -316,7 +351,22 @@ function serve(host: MetaCompileCacheHost, request: MetaCompileCacheRequest, ent */ async function confirm(engine: object, bucket: CompileBucket, ttlMs: number, now: number): Promise { const mark = await readConfirmationMark(engine, bucket.stamp.metadataService); - if (mark === undefined || bucket.mark !== mark) bucket.entries.clear(); + if (mark === undefined || bucket.mark !== mark) { + bucket.entries.clear(); + } else { + const maxAge = META_COMPILE_CACHE_MAX_AGE_BOUNDS * ttlMs; + for (const [key, entry] of bucket.entries) if (now - entry.compiledAt >= maxAge) bucket.entries.delete(key); + } + // What is compiled under this reading must read rows at least as new as + // it: retire the overlay row cache, which may hold rows filled before + // another writer's change. Only when no write moved its generation while + // the reading was taken: a moved one has retired it already, and resets + // this bucket at the stamp check. + const overlay = readOverlayCacheGeneration(engine); + if (overlay !== undefined && overlay === bucket.stamp.overlay) { + const next = retireMetaOverlayCache(engine); + if (next !== undefined) bucket.stamp = { ...bucket.stamp, overlay: next }; + } bucket.mark = mark; bucket.confirmedUntil = now + ttlMs; } @@ -333,7 +383,7 @@ export async function readThroughMetaCompileCache( ): Promise { const ttlMs = metaCompileCacheTtlMs(); if (ttlMs <= 0 || !cacheableRequest(request)) return compute(); - const stamp = readCompileStamp(host); + let stamp = readCompileStamp(host); if (stamp === undefined) return compute(); const engine = host.engine as object; @@ -343,7 +393,10 @@ export async function readThroughMetaCompileCache( buckets.set(engine, bucket); } const now = Date.now(); - if (now >= bucket.confirmedUntil) await confirm(engine, bucket, ttlMs, now); + if (now >= bucket.confirmedUntil) { + await confirm(engine, bucket, ttlMs, now); + stamp = bucket.stamp; + } const key = entryKey(request); const hit = bucket.entries.get(key); @@ -361,7 +414,7 @@ export async function readThroughMetaCompileCache( const copy = cloned(answer) as Record | undefined; if (copy === undefined) return answer; for (const trailer of host.liveTrailerKeys) delete copy[trailer]; - bucket.entries.set(key, { envelope: copy, changedAt: servedRowChangedAtOf(answer) }); + bucket.entries.set(key, { envelope: copy, changedAt: servedRowChangedAtOf(answer), compiledAt: Date.now() }); return answer; } diff --git a/packages/metadata-protocol/src/meta-overlay-cache.ts b/packages/metadata-protocol/src/meta-overlay-cache.ts index 7c1cc04ab33..e6e0d24881f 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.ts @@ -371,6 +371,27 @@ export function readOverlayCacheGeneration(engine: unknown): number | undefined return state.gen; } +/** + * [#34206, ADR-0156 D5] Retire every row set this engine holds, from outside + * its write path, by advancing the generation the entries are stamped with. + * The shared compile cache (`meta-compile-cache.ts`) calls it each time it + * takes a reading of the store, so whatever it compiles under that reading + * reads rows at least as new as the reading: an entry here filled before + * another writer's change would otherwise feed a recompile the older rows, + * and that answer would then stand under the newer reading. + * + * ⛔ It does not move the engine's write epoch ({@link bumpWriteEpoch} does), + * which would retire the authorization cache that shares it. Returns the new + * generation, or `undefined` for an engine this cache does not cover. + */ +export function retireMetaOverlayCache(engine: unknown): number | undefined { + if (!engine || typeof engine !== 'object') return undefined; + const state = overlayWriteStates.get(engine); + if (!state) return undefined; + state.gen += 1; + return state.gen; +} + /** * [#13609] Bump the engine's write epoch from OUTSIDE this engine's own write * path — the structural sibling to {@link readWriteEpoch}, spelled the same diff --git a/packages/metadata-protocol/src/metadata-diagnostics.ts b/packages/metadata-protocol/src/metadata-diagnostics.ts index bbd2ac57816..0b635c90f78 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.ts @@ -80,10 +80,11 @@ export type MetadataDiagnostics = MetadataValidationResult; // and the spec's own constants (the node-config contract maps are fixed at // first build), and no code path installs a global zod error map. // -// ⛔ Not a cache of any read's ANSWER. The overlay cache's position in -// `readActiveOverlayRows` explains why a merged answer is never cached; this -// memo sits below every merge, on a pure function of its own input, so a -// metadata change is a different document and a different key. +// ⛔ Not a cache of any read's ANSWER. The one cache of a merged answer is +// the compile cache (`meta-compile-cache.ts`, ADR-0156), retired by every +// source's change counter; this memo sits below every merge, on a pure +// function of its own input, so a metadata change is a different document +// and a different key. // // The cached verdict never leaves this module: each caller gets its own copy // ({@link copyDiagnostics}), so a caller that edits the verdict it was handed diff --git a/packages/metadata/src/loaders/filesystem-loader.ts b/packages/metadata/src/loaders/filesystem-loader.ts index 082a34a506d..81e47994f95 100644 --- a/packages/metadata/src/loaders/filesystem-loader.ts +++ b/packages/metadata/src/loaders/filesystem-loader.ts @@ -98,11 +98,16 @@ export class FilesystemLoader implements MetadataLoader { private resolutionEpoch = 0; /** * [#34206, ADR-0156 D5] Every type directory {@link probeFile} has looked - * in, for {@link changeMark}. Never cleared: a directory once asked about - * stays observed for the life of the loader. + * in, for {@link changeMark}. A directory once asked about stays observed, + * up to {@link PROBED_TYPE_DIR_CAP} directories; the type comes from the + * read, so past the cap the set starts over. Starting over moves the mark + * (fewer paths are read), so a cache confirming on it recompiles, never + * renews: the failure direction is a recompile, not a missed change. */ private readonly probedTypeDirs = new Set(); + private static readonly PROBED_TYPE_DIR_CAP = 1_000; + private static readonly RESOLUTION_MEMO_CAP = 10_000; constructor( @@ -770,6 +775,9 @@ export class FilesystemLoader implements MetadataLoader { /** The disk read behind {@link findFile}: one `fs.access` per resolvable extension, in precedence order. */ private async probeFile(type: string, name: string): Promise { const typeDir = path.join(this.rootDir, type); + if (!this.probedTypeDirs.has(typeDir) && this.probedTypeDirs.size >= FilesystemLoader.PROBED_TYPE_DIR_CAP) { + this.probedTypeDirs.clear(); + } this.probedTypeDirs.add(typeDir); const extensions = this.resolvableExtensions(); @@ -798,6 +806,10 @@ export class FilesystemLoader implements MetadataLoader { * It covers item reads only. It is what lets a cache of an answer this * loader contributed to, including a miss it remembered, be renewed on a * confirmation instead of recompiled (`MetadataManager.loaderChangeMark`). + * + * The path set grows as reads probe new directories and resolve new files, + * so the mark also moves when nothing on disk did: the first confirmation + * after a warm-up usually recompiles. That is conservative, never stale. */ async changeMark(): Promise { const files = new Set(); diff --git a/packages/metadata/src/metadata-manager-change-revision.test.ts b/packages/metadata/src/metadata-manager-change-revision.test.ts index e349455ba0d..c242b2e41ef 100644 --- a/packages/metadata/src/metadata-manager-change-revision.test.ts +++ b/packages/metadata/src/metadata-manager-change-revision.test.ts @@ -146,6 +146,16 @@ describe('[#34206] FilesystemLoader#changeMark', () => { expect(await loader.changeMark()).not.toBe(before); }); + it('the probed type directories are bounded: past the cap the set starts over and the mark moves', async () => { + await loader.load('view', 'rv_all'); + const before = await loader.changeMark(); + const probed = (loader as unknown as { probedTypeDirs: Set }).probedTypeDirs; + for (let i = 0; i < 1_000; i += 1) await loader.load(`t${i}`, 'x'); + expect(probed.size).toBeLessThanOrEqual(1_000); + expect(probed.has(path.join(rootDir, 'view'))).toBe(false); + expect(await loader.changeMark()).not.toBe(before); + }); + it('control: a change in a type directory no read probed leaves it alone', async () => { await loader.load('view', 'rv_all'); const before = await loader.changeMark(); diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts index a00edc761e3..11eaf9432a0 100644 --- a/packages/objectql/src/registry-revision.ts +++ b/packages/objectql/src/registry-revision.ts @@ -32,8 +32,12 @@ * seals, claims, records an ownership fact or a listener is a `write`. * * What the counter cannot see: a caller that mutates, in place, an object the - * registry handed it. That is outside the registry's own code, and the time - * bound of any cache keyed on this counter covers it (ADR-0156 D1 (b)). + * registry handed it. That is outside the registry's own code, and no + * confirmation observes it either, so a cache keyed on this counter may serve + * the earlier compile until something else moves. The compile cache bounds + * it only by its age cap (`META_COMPILE_CACHE_MAX_AGE_BOUNDS`, + * `@objectstack/metadata-protocol`); a caller must not edit what the registry + * hands out. */ import type { SchemaRegistry } from './registry.js'; From b7751333b730eaa49f9f98052242c3b75a0a24ca Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:17:50 +0000 Subject: [PATCH 3/4] perf(metadata-protocol): one confirmation per bound, read over bookkeeping columns (#34206) Answers contract review 6933112344 S3, N6 and N7 on #34494. - One confirmation per bound per engine, shared by every reader that crosses the bound; a failure reaches every waiter. - A bucket opened by a counter move takes no store reading: its first bound ends at a confirmation that drops its entries and takes the reading later bounds renew on. - The store reading digests identity, binding, layering, state, version, checksum and updated_at, never the bodies. A bypassing write that changes a body and leaves all three bookkeeping columns is bounded by the age cap alone (named; #34522 tracks the column). - A renewal keeps an entry only when the bound it opens ends within the 10-bound cap. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp --- .changeset/34206-shared-compile-cache.md | 2 +- content/docs/concepts/metadata-lifecycle.mdx | 12 +-- .../docs/deployment/environment-variables.mdx | 2 +- .../src/meta-compile-cache.test.ts | 80 +++++++++++++++-- .../src/meta-compile-cache.ts | 89 +++++++++++++------ 5 files changed, 141 insertions(+), 44 deletions(-) diff --git a/.changeset/34206-shared-compile-cache.md b/.changeset/34206-shared-compile-cache.md index 7d69db9f617..d2aa4116dda 100644 --- a/.changeset/34206-shared-compile-cache.md +++ b/.changeset/34206-shared-compile-cache.md @@ -13,7 +13,7 @@ Metadata-protocol: none - **What is cached.** The compiled envelope of a by-name read of `app`, `object`, `view`, `page` and `dashboard` items, per engine. A read for a package, a state, a member or a draft preview is never cached. The per-caller gate, field mask, translation and ETag stay computed on every request, and the live trailers (`registration`, `disabledActions`, `cascadeDeleteObjects`) are read on every hit. - **What retires it.** Each source counts its own changes at its own mutation point: the `sys_metadata` overlay generation, the schema registry's `objectRevision` and a new `revision` that every public write of `SchemaRegistry` moves (the classification of its public methods is exhaustive by type), and a new `revision` on `MetadataManager`. Any move drops every entry. A source without its counter makes the cache decline. -- **What another process can change.** After a bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms) the cache confirms before it recompiles: a digest of every stored row's content (so a write that leaves `updated_at` alone, or stamps it from a clock that is behind, still moves it) and each loader's reading of its backing store (`FilesystemLoader` stats the type directories and files its reads touched). If nothing moved, the entries stand for another bound, up to 10 bounds from when each was compiled. Every confirmation also retires the overlay row cache, so a recompile reads rows at least as new as the reading, and a read in flight across a confirmation is not stored. A loader that keeps no change mark makes every entry recompile at its bound, never renewed. +- **What another process can change.** After a bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms) the cache confirms before it recompiles, once per bound per engine however many readers cross it: a digest of every stored row's identity, binding, state, `version`, `checksum` and `updated_at` (so an `updated_at` stamped from a clock that is behind still moves it; the bodies are not read) and each loader's reading of its backing store (`FilesystemLoader` stats the type directories and files its reads touched). If nothing moved, the entries stand for another bound, never past 10 bounds from when each was compiled; that cap is the only bound on a writer that bypasses the engine and rewrites a body while leaving all three bookkeeping columns as they were (#34522 tracks a column that would close it). Every confirmation also retires the overlay row cache, so a recompile reads rows at least as new as the reading, and a read in flight across a confirmation is not stored. A local counter move takes no store reading. A loader that keeps no change mark makes every entry recompile at its bound, never renewed. - **New public members (additive).** `SchemaRegistry#revision`, `MetadataManager#revision`, `MetadataManager#loaderChangeMark()`, the optional `MetadataLoader#changeMark()` and `FilesystemLoader#changeMark()`. - `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read, the same reads in the same order. diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index b8d293065fd..9c22e795edd 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -321,11 +321,13 @@ The hash is `sha256:` + 64-hex of a canonical JSON serialization of the body, wi > 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, `0` disables it), where it reads every `sys_metadata` row's content -> and the metadata files it read, and recompiles if any of them moved, also -> when a write left `updated_at` alone. Each such check also drops the cached -> rows, so the recompile reads the store as it is then, and no compiled answer -> is kept past ten bounds. +> 30s, `0` disables it), where it reads every `sys_metadata` row'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. --- diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index 633de87bf2d..2ec8ac1d094 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -430,7 +430,7 @@ With several replicas declared over the Redis cluster driver (`OS_CLUSTER_REPLIC | `OS_SANDBOX_WALL_CEILING_MS` | number | `30000` | Wall-clock ceiling (ADR-0102) — the backstop that cuts a hook/action body stuck on a host call that never settles (which burns no CPU, so the CPU budget alone would never fire). The effective ceiling is `max(this, cpuBudget)`, so it can never cut a body still inside its CPU budget. Positive integer only; unset keeps 30s. | | `OS_LOCALIZATION_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of a workspace's reference localization (`timezone` / `locale` / `currency`, read from `sys_setting`) — leg C of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Unlike `OS_AUTHZ_GRANTS_CACHE_TTL_MS` (which is off by default) this one ships **on**, because its invalidation is synchronous and in-process rather than TTL-bound: a `localization` settings change, a write to `sys_setting` or `sys_platform_setting` (the tables the answer is read from), and a non-`write` bump of the engine write epoch each retire a cached answer immediately. A write to any other object does not. So the TTL only bounds what none of these seams can see — a write made on another replica with no cluster bridge attached at all: neither the `metadata.mutated` channel's receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch`, #13609) nor the `authz.invalidated` bridge, both of which bump this same epoch when attached. ⚠️ A malformed value reads as `0` (off), the opposite arm from the grants variable and deliberately so: there `0` is also the default, whereas here folding `3OOO` (letter O) into the default would hand you a **longer** window than the one you were setting. Deployment config only — never a settings row, because `sys_setting` is the table this cache caches. | | `OS_METADATA_OVERLAY_CACHE_TTL_MS` | number | `30000` | Staleness bound, in milliseconds, for the cross-request cache of the `sys_metadata` overlay rows read inside `getMetaItems` (the list read) and `getMetaItem` (the served by-name read the REST API-exposure gate makes on every `/data` request) — leg D of #11633. `0` means **off**, a real path that restores the uncached query pattern exactly. Ships **on**, for the same reason as `OS_LOCALIZATION_CACHE_TTL_MS`: invalidation is synchronous and in-process, because every `sys_metadata` write goes through the engine, whose middleware retires the entry when the write's statement completes, before the next read. Outside a transaction that is the commit. Inside an engine transaction it is earlier than the commit: a read that lands between the statement and the commit can keep the pre-commit rows until the next `sys_metadata` write or the TTL. A write to any other object does not retire it; a non-`write` bump of the engine write epoch retires it wholesale. What is cached is the overlay ROW SET only — never the merged answer — so the SchemaRegistry, the MetadataService and the artifact table are re-consulted on every call, cached or not, and the read-side registry hydration keeps running on a cache hit. The TTL therefore bounds one thing: a write made on **another replica** with no cluster bridge attached at all — neither the `metadata.mutated` channel's own receipt path (`applyRemoteMetadataMutation` calls `bumpWriteEpoch` right after registry convergence, #13609) nor the `authz.invalidated` bridge, either of which retires this entry the moment it is attached and fires. ⚠️ A malformed value reads as `0` (off) — same arm and same reason as `OS_LOCALIZATION_CACHE_TTL_MS`. Deployment config only, never a settings row. | -| `OS_METADATA_COMPILE_CACHE_TTL_MS` | number | `30000` | Bound, in milliseconds, for the per-environment cache of compiled item answers ([ADR-0156](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0156-compiled-metadata-answer-cache-every-source-counts-its-own-changes.md)): the served item read (`getMetaItem`) of an app, object, view, page or dashboard, which the app bundle (`GET /api/v1/meta/app/:appId/bundle`) and the item reads make. `0` means **off**, a real path: the read is the uncached one, the same reads in the same order. Only the caller-independent answer is cached; the per-caller gate, field mask, translation and `ETag` are computed on every request. A local change is seen at once: the cache keeps the change counter of every source it reads (the `sys_metadata` overlay generation, the schema registry's `revision` and `objectRevision`, the metadata service's `revision`) and drops every entry when one moves; a source without its counter makes it decline. When the bound passes it confirms before it recompiles, with one reading of what this process cannot see (a digest of every `sys_metadata` row's content, which moves even when a write leaves `updated_at` alone, and each metadata loader's own change mark: the file loader stats the directories and files its reads touched); unchanged, the entries stand for another bound, up to 10 bounds from when each was compiled; unreadable, nothing is renewed. Each confirmation also retires the overlay row cache, so the recompile reads the rows as they are now. The bound is therefore how long another replica's write with no cluster bridge, or a file created, removed or edited under a running process, can stay unseen; a file edit no `stat` can tell apart (same size, within the file system's time grain) is seen within 10 bounds. ⚠️ A malformed value reads as `0` (off). Deployment config only, never a settings row. | +| `OS_METADATA_COMPILE_CACHE_TTL_MS` | number | `30000` | Bound, in milliseconds, for the per-environment cache of compiled item answers ([ADR-0156](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0156-compiled-metadata-answer-cache-every-source-counts-its-own-changes.md)): the served item read (`getMetaItem`) of an app, object, view, page or dashboard, which the app bundle (`GET /api/v1/meta/app/:appId/bundle`) and the item reads make. `0` means **off**, a real path: the read is the uncached one, the same reads in the same order. Only the caller-independent answer is cached; the per-caller gate, field mask, translation and `ETag` are computed on every request. A local change is seen at once: the cache keeps the change counter of every source it reads (the `sys_metadata` overlay generation, the schema registry's `revision` and `objectRevision`, the metadata service's `revision`) and drops every entry when one moves; a source without its counter makes it decline. When the bound passes it confirms before it recompiles, with one reading of what this process cannot see (a digest of every `sys_metadata` row's identity, state, `version`, `checksum` and `updated_at`, not the bodies, which moves on any insert, delete or bookkeeping change including an older `updated_at` from a clock that is behind, and each metadata loader's own change mark: the file loader stats the directories and files its reads touched), once per bound however many requests cross it; unchanged, the entries stand for another bound, never past 10 bounds from when each was compiled; unreadable, nothing is renewed. Each confirmation also retires the overlay row cache, so the recompile reads the rows as they are now. The bound is therefore how long another replica's write with no cluster bridge, or a file created, removed or edited under a running process, can stay unseen; a file edit no `stat` can tell apart (same size, within the file system's time grain), or a write that bypasses the engine and changes a stored body while leaving `version`, `checksum` and `updated_at` as they were, is seen within 10 bounds. ⚠️ A malformed value reads as `0` (off). Deployment config only, never a settings row. | | `OS_INLINE_SEED_BUDGET_MS` | number | `8000` | Time budget for synchronous seed execution at boot before deferring to a worker. | | `OS_TENANT_AUDIT` | flag | `1` | Set to `0` to silence the tenant-isolation audit warnings emitted by the SQL driver. | diff --git a/packages/metadata-protocol/src/meta-compile-cache.test.ts b/packages/metadata-protocol/src/meta-compile-cache.test.ts index f5388741594..2bd5559ca6b 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.test.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.test.ts @@ -436,12 +436,12 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp expect(h.byNameReads('widget')).toBeGreaterThan(before); }); - /** Replace the confirmation's store reading (the whole-store `find` over the body column) until the returned restore runs. */ + /** Replace the confirmation's store reading (the whole-store `find` over the bookkeeping columns) until the returned restore runs. */ const onStoreMark = (h: ReturnType, impl: (real: () => Promise) => Promise) => { const find = h.engine.find as (table: string, q?: { where?: Row; fields?: string[] }) => Promise; let calls = 0; h.engine.find = (table: string, q: { where?: Row; fields?: string[] } = {}) => { - const isMark = table === 'sys_metadata' && Object.keys(q.where ?? {}).length === 0 && (q.fields ?? []).includes('metadata'); + const isMark = table === 'sys_metadata' && Object.keys(q.where ?? {}).length === 0 && (q.fields ?? []).includes('checksum'); if (!isMark) return find(table, q); calls += 1; return impl(() => find(table, q)); @@ -503,19 +503,39 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp expect((await read(h)).item.label).toBe('Gadget'); }); - it('another writer\'s change that leaves every bookkeeping column alone is still seen at the bound', async () => { + it('an import that keeps updated_at but stamps its own checksum is seen at the bound', async () => { const clock = atBound(); const rows = [storedObject('Widget')]; const h = harness(rows); await read(h); clock.pass(); await read(h); - // A write that bypasses the engine: same id, same updated_at, new body. - rows[0] = { ...rows[0], metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) }; + rows[0] = { ...rows[0], checksum: 'sha256:imported', metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) }; clock.pass(); expect((await read(h)).item.label).toBe('Gadget'); }); + it('the stored body is not read at the bound: a bypassing write that leaves every bookkeeping column alone waits for the age cap', async () => { + const clock = atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + const mark = onStoreMark(h, async (real) => real()); + await read(h); + clock.pass(); + await read(h); // the first confirmation takes the reading and recompiles + rows[0] = { ...rows[0], metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) }; + clock.pass(); + expect((await read(h)).item.label).toBe('Widget'); // the named class: unseen by the reading + let label = 'Widget'; + for (let i = 0; i < META_COMPILE_CACHE_MAX_AGE_BOUNDS && label === 'Widget'; i++) { + clock.pass(); + label = (await read(h)).item.label; + } + expect(label).toBe('Gadget'); + expect(mark.calls).toBeGreaterThan(0); + mark.restore(); + }); + it('another node\'s write stamped with an OLDER updated_at than the newest stored is still seen at the bound', async () => { const clock = atBound(); const rows = [storedObject('Widget', '2026-11-16T05:00:00.000Z'), storedView('All')]; @@ -532,6 +552,8 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp const clock = atBound(); const h = harness([storedObject('Widget')]); await read(h); + clock.pass(); + await read(h); const outage = new Error('connect ECONNREFUSED 127.0.0.1:5432'); const mark = onStoreMark(h, async () => { throw outage; }); clock.pass(); @@ -548,6 +570,8 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp const clock = atBound(); const h = harness([storedObject('Widget')]); await read(h); + clock.pass(); + await read(h); const mark = onStoreMark(h, async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); }); clock.pass(); const before = h.byNameReads('widget'); @@ -571,19 +595,57 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp expect((await read(h)).item.label).toBe('Gadget'); }); - it(`no entry stands past ${META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds, renewals included`, async () => { + it(`no entry is served past ${META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds from its compile, renewals included`, async () => { const clock = atBound(); const h = harness([storedObject('Widget')]); await read(h); + clock.pass(); + await read(h); // the first confirmation drops the bucket's first-bound entries + const compiledAt = Date.now(); const compiled = h.byNameReads('widget'); - for (let i = 1; i < META_COMPILE_CACHE_MAX_AGE_BOUNDS; i++) { + const ttl = 30_000; + let renewals = 0; + for (;;) { clock.pass(); await read(h); + if (h.byNameReads('widget') > compiled) break; + renewals += 1; + // A renewal opens a bound that must still end within the cap. + expect(Date.now() + ttl - compiledAt).toBeLessThanOrEqual(META_COMPILE_CACHE_MAX_AGE_BOUNDS * ttl); + expect(renewals).toBeLessThan(META_COMPILE_CACHE_MAX_AGE_BOUNDS); } - expect(h.byNameReads('widget')).toBe(compiled); // renewed every bound so far + expect(renewals).toBe(META_COMPILE_CACHE_MAX_AGE_BOUNDS - 2); // with a bound read 1 ms late each time + }); + + it('one confirmation per bound per engine: readers that cross the bound together share it', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget'), storedView('All widgets')]); + await read(h); + await read(h, 'view', 'widget_list'); + clock.pass(); + let release!: () => void; + const gate = new Promise((r) => { release = r; }); + const mark = onStoreMark(h, async (real) => { await gate; return real(); }); + const reads = [read(h), read(h, 'view', 'widget_list'), read(h)]; + await new Promise((r) => setTimeout(r, 0)); + release(); + await Promise.all(reads); + expect(mark.calls).toBe(1); + mark.restore(); + }); + + it('a counter move costs no store read: the new bucket takes its reading at its first bound', async () => { + const clock = atBound(); + const h = harness([storedObject('Widget')]); + const mark = onStoreMark(h, async (real) => real()); + await read(h); + (h.registry.revision as number)++; + await read(h); + expect(mark.calls).toBe(0); clock.pass(); await read(h); - expect(h.byNameReads('widget')).toBeGreaterThan(compiled); + expect(mark.calls).toBe(1); + mark.restore(); }); it('⛔ a source the confirmation cannot observe: nothing is renewed, every bound recompiles', async () => { diff --git a/packages/metadata-protocol/src/meta-compile-cache.ts b/packages/metadata-protocol/src/meta-compile-cache.ts index 6ffcd860d22..46268e5de1a 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.ts @@ -48,30 +48,39 @@ * counters above at their stamp, and a reading of everything outside this * process that the bound exists for ({@link readConfirmationMark}): * - * - the stored rows: a digest of every `sys_metadata` row's id, state, - * version, checksum, change time and stored body ({@link readStoreMark}). - * It reads the content itself, so it moves on another writer's insert, - * update or delete whatever that writer did to the bookkeeping columns: a - * write that bypasses the engine and leaves `updated_at` alone, an import - * that preserves timestamps, a node whose clock is behind. One read of the - * whole store per bound per engine, in place of recompiling every entry; + * - the stored rows: a digest of every `sys_metadata` row's identity, + * binding, layering, state, `version`, `checksum` and `updated_at` + * ({@link readStoreMark}), never the stored bodies. It moves on another + * writer's insert or delete and on any move of those columns, also an + * `updated_at` older than the newest from a node whose clock is behind. + * One read of those columns per bound per engine, in place of recompiling + * every entry. A bypassing write that changes a body and leaves all three + * bookkeeping columns as they were is the one row change it cannot see; + * the age cap below bounds it; * - the metadata service's loaders: `loaderChangeMark()` on the service * (`@objectstack/metadata`), each loader's own reading of its backing * store (the file loader stats the directories and files its reads * touched, so a file a deployment creates, removes or edits under a * running process moves it). * - * Nothing moved: the entries are kept for another bound, up to - * {@link META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds from when each was - * compiled. The age cap is the backstop for what no reading sees: a file - * edited in place to the same size within the file system's time - * granularity, and an object the schema registry handed out that a caller - * then edited in place (`registry-revision.ts`). Anything moved: every entry - * goes. Either way the overlay row + * Nothing moved: the entries are kept for another bound, as long as that + * bound ends within {@link META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds of when + * each was compiled. The age cap is the backstop for what no reading sees: a + * body rewritten by a bypassing writer that left the bookkeeping columns + * alone, a file edited in place to the same size within the file system's + * time granularity, and an object the schema registry handed out that a + * caller then edited in place (`registry-revision.ts`). Anything moved: every + * entry goes. Either way the overlay row * cache is retired (`retireMetaOverlayCache`), so a recompile under the new * reading reads rows at least as new as the reading, never rows that cache * filled before another writer's change. * + * One confirmation runs per bound per engine: the readers that cross the + * bound while it runs wait for it, and its failure reaches all of them. A + * bucket opened by a counter move takes no reading: its first bound ends at + * a confirmation that drops its entries and takes the reading later bounds + * renew on, so a local change costs no store read. + * * ⛔ A renewal is a claim about what was looked at (ADR-0156 D5). When the * confirmation cannot read one of those (the store cannot be read, the * service keeps no `loaderChangeMark`, a loader keeps no mark), nothing is @@ -195,6 +204,8 @@ interface CompileBucket { mark: string | undefined; /** Until when the entries stand without a confirmation. */ confirmedUntil: number; + /** The confirmation in flight, shared by every reader that crosses the bound while it runs. */ + confirming: Promise | undefined; readonly entries: Map; } @@ -268,18 +279,32 @@ export async function readConfirmationMark(engine: unknown, metadataService: obj return JSON.stringify([store, loaders]); } -/** The `sys_metadata` columns the store reading digests: identity, state, the bookkeeping columns and the body itself. */ -export const STORE_MARK_FIELDS: readonly string[] = Object.freeze(['id', 'state', 'version', 'checksum', 'updated_at', 'metadata']); +/** + * The `sys_metadata` columns the store reading digests: identity, binding, + * layering, state and the bookkeeping columns every engine write moves. ⛔ Not + * the stored body: the reading must not carry every body through the process + * at each bound (contract review 6933112344 S3). + */ +export const STORE_MARK_FIELDS: readonly string[] = Object.freeze([ + 'id', 'type', 'name', 'namespace', 'package_id', 'bundle_member', 'extends', 'strategy', + 'state', 'version', 'checksum', 'updated_at', +]); /** * The store reading the confirmation compares (ADR-0156 D5): a digest of * every `sys_metadata` row's {@link STORE_MARK_FIELDS}, read as the system, - * in id order. It reads the stored body, not only the bookkeeping columns, so - * it moves on any insert, delete or content change another writer makes: - * also one that bypasses the engine and leaves `updated_at`, `version` and - * `checksum` alone, an import that preserves timestamps, and a node whose - * clock writes an older `updated_at` than the newest already stored. Only the - * digest is kept; no row leaves this function. + * sorted. It moves on any insert or delete, on a change of a row's identity, + * binding, layering or state, and on any change of `version`, `checksum` or + * `updated_at` whichever way it goes: a node whose clock writes an older + * `updated_at` than the newest already stored, or an import that preserves + * timestamps but stamps its own checksum. Only the digest is kept; no row + * leaves this function. + * + * What it cannot see: a writer that bypasses the engine and changes a stored + * body while leaving `version`, `checksum` and `updated_at` exactly as they + * were. That class is bounded by the age cap alone + * ({@link META_COMPILE_CACHE_MAX_AGE_BOUNDS}); a column every write moves + * would close it (#34522). * * `undefined` when there is nothing to read it with (an engine without * `find`) or no store yet (`sys_metadata` not provisioned, by error type): @@ -354,8 +379,9 @@ async function confirm(engine: object, bucket: CompileBucket, ttlMs: number, now if (mark === undefined || bucket.mark !== mark) { bucket.entries.clear(); } else { + // Renewed only when the bound it opens still ends within the cap. const maxAge = META_COMPILE_CACHE_MAX_AGE_BOUNDS * ttlMs; - for (const [key, entry] of bucket.entries) if (now - entry.compiledAt >= maxAge) bucket.entries.delete(key); + for (const [key, entry] of bucket.entries) if (now + ttlMs - entry.compiledAt > maxAge) bucket.entries.delete(key); } // What is compiled under this reading must read rows at least as new as // it: retire the overlay row cache, which may hold rows filled before @@ -389,13 +415,20 @@ export async function readThroughMetaCompileCache( let bucket = buckets.get(engine); if (bucket === undefined || !sameStamp(bucket.stamp, stamp)) { - bucket = { stamp, mark: undefined, confirmedUntil: 0, entries: new Map() }; + // A new bucket opens its first bound without a reading: its entries + // live one bound, as the row cache's do, and the first confirmation + // drops them and takes the reading later bounds are renewed on. So a + // counter move costs no store read. + bucket = { stamp, mark: undefined, confirmedUntil: Date.now() + ttlMs, confirming: undefined, entries: new Map() }; buckets.set(engine, bucket); } - const now = Date.now(); - if (now >= bucket.confirmedUntil) { - await confirm(engine, bucket, ttlMs, now); - stamp = bucket.stamp; + if (Date.now() >= bucket.confirmedUntil) { + // One confirmation per bound per engine: a reader crossing the bound + // while one runs waits for it, and a failure reaches every waiter. + const open = bucket; + open.confirming ??= confirm(engine, open, ttlMs, Date.now()).finally(() => { open.confirming = undefined; }); + await open.confirming; + stamp = open.stamp; } const key = entryKey(request); From 3fa027d40ae1608633731a2bd5e8da45f53e9d33 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:25:55 +0000 Subject: [PATCH 4/4] fix(metadata-protocol): a new compile bucket retires the overlay row cache (#34206) Answers L1 6933589708 M1 and contract review 6933631137 S4 on #34494: a bucket opened by a counter move compiled from row-cache rows up to a bound old, so a peer's write could stay unseen for two bounds. Opening a bucket now retires the row cache and rebases its stamp, as a confirmation does, with no store reading. Pinned. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp --- .../src/meta-compile-cache.test.ts | 11 +++++++++++ .../metadata-protocol/src/meta-compile-cache.ts | 16 +++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/metadata-protocol/src/meta-compile-cache.test.ts b/packages/metadata-protocol/src/meta-compile-cache.test.ts index 2bd5559ca6b..7cf06c771eb 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.test.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.test.ts @@ -634,6 +634,17 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp mark.restore(); }); + it('a counter move retires the row cache: a peer\'s write the row cache predates is in the new bucket\'s answer', async () => { + vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here + atBound(); + const rows = [storedObject('Widget')]; + const h = harness(rows); + expect((await read(h)).item.label).toBe('Widget'); // the row cache is warm + rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); // a peer replica with no bridge + (h.registry.revision as number)++; // a local counter move opens a new bucket + expect((await read(h)).item.label).toBe('Gadget'); + }); + it('a counter move costs no store read: the new bucket takes its reading at its first bound', async () => { const clock = atBound(); const h = harness([storedObject('Widget')]); diff --git a/packages/metadata-protocol/src/meta-compile-cache.ts b/packages/metadata-protocol/src/meta-compile-cache.ts index 46268e5de1a..9895bd5d12c 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.ts @@ -79,7 +79,9 @@ * bound while it runs wait for it, and its failure reaches all of them. A * bucket opened by a counter move takes no reading: its first bound ends at * a confirmation that drops its entries and takes the reading later bounds - * renew on, so a local change costs no store read. + * renew on, so a local change costs no store read. Opening it retires the + * overlay row cache, as a confirmation does, so its entries never carry + * rows older than the bucket. * * ⛔ A renewal is a claim about what was looked at (ADR-0156 D5). When the * confirmation cannot read one of those (the store cannot be read, the @@ -415,10 +417,14 @@ export async function readThroughMetaCompileCache( let bucket = buckets.get(engine); if (bucket === undefined || !sameStamp(bucket.stamp, stamp)) { - // A new bucket opens its first bound without a reading: its entries - // live one bound, as the row cache's do, and the first confirmation - // drops them and takes the reading later bounds are renewed on. So a - // counter move costs no store read. + // A new bucket opens its first bound without a reading: the first + // confirmation drops its entries and takes the reading later bounds + // are renewed on, so a counter move costs no store read. It retires + // the overlay row cache first, as a confirmation does: what it + // compiles reads rows from now on, never rows that cache filled + // before a peer's write, so its entries are at most one bound old. + const overlay = retireMetaOverlayCache(engine); + if (overlay !== undefined) stamp = { ...stamp, overlay }; bucket = { stamp, mark: undefined, confirmedUntil: Date.now() + ttlMs, confirming: undefined, entries: new Map() }; buckets.set(engine, bucket); }