diff --git a/.changeset/34554-compile-cache-keeps-fresh-rows.md b/.changeset/34554-compile-cache-keeps-fresh-rows.md new file mode 100644 index 00000000000..bd60ba17284 --- /dev/null +++ b/.changeset/34554-compile-cache-keeps-fresh-rows.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a list read that registers stored rows no longer sends the reads after it to the store + +Clause-②: no +Metadata-protocol: none + +On a kernel whose list read (`getMetaItems`) registers the stored rows back into the schema registry, every list read moves `registry.revision`, even when it registers what is already there. Each move opened a new compile-cache bucket, and opening a bucket retired the `sys_metadata` row cache. So the list read and the item reads after it all went to the store. Measured with a list read of three stored objects followed by item reads, in alternation: 3 store reads per round with the compile cache on against 1 with it off (one item read), and 7 against 3 (three item reads). + +A bucket opened by a counter move now keeps the row cache when its rows were read within the last bound, and its first bound ends one bound after they were read, so no answer carries a row more than one bound old. When the rows are older than that, opening the bucket retires them, as before. The same alternation now costs what it costs with the compile cache off. diff --git a/packages/metadata-protocol/src/meta-compile-cache.test.ts b/packages/metadata-protocol/src/meta-compile-cache.test.ts index 7cf06c771eb..667ff9bbb6a 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.test.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.test.ts @@ -57,6 +57,13 @@ interface HarnessOptions { 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; + /** + * [#34554] `registerItem` and `registerObject` move `revision` (and + * `objectRevision` for an object), as every public write of the real + * `SchemaRegistry` does (`registry-revision.ts`), so a list read's + * hydration moves the counters even when it registers what is there. + */ + hydrationMovesRevision?: boolean; } function harness(rows: Row[], opts: HarnessOptions = {}) { @@ -76,8 +83,14 @@ function harness(rows: Row[], opts: HarnessOptions = {}) { getPackage: () => undefined, getArtifactItem: () => undefined, isPackageDisabled: () => false, - registerItem: () => { registryCalls.push('registerItem'); }, - registerObject: () => { registryCalls.push('registerObject'); }, + registerItem: () => { + registryCalls.push('registerItem'); + if (opts.hydrationMovesRevision) (registry.revision as number) += 1; + }, + registerObject: () => { + registryCalls.push('registerObject'); + if (opts.hydrationMovesRevision) { (registry.revision as number) += 1; (registry.objectRevision as number) += 1; } + }, applyNavContributions: (app: unknown) => app, // ADR-0150 D3: a by-name read of a package-scoped type needs the resolver. readsByPackage: () => true, @@ -634,17 +647,57 @@ 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 () => { + it('[#34554] a counter move keeps the row sets read within the last bound, and a peer\'s write is in the answer by the next bound', async () => { vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here - atBound(); + const clock = 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 + // The item's active rows (the row cache's by-name read, a `find`). + const rowReads = () => h.reads.filter((r) => r.op === 'find' && r.where.name === 'widget').length; + const before = rowReads(); + // The rows were read inside this bound: kept, so no row is more than one bound old. + expect((await read(h)).item.label).toBe('Widget'); + expect(rowReads()).toBe(before); + clock.pass(); // the new bucket's first bound ends one bound after those rows were read + expect((await read(h)).item.label).toBe('Gadget'); + }); + + it('[#34554] the bucket a counter move opens ends its first bound one bound after the kept rows were read, not one bound after the move', async () => { + vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here + let now = 1_000_000; + vi.spyOn(Date, 'now').mockImplementation(() => now); + const rows = [storedObject('Widget')]; + const h = harness(rows); + expect((await read(h)).item.label).toBe('Widget'); // the row cache is warm, its rows read at T + now += 20_000; // part of a bound later + 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 at T + 20 s + const rowReads = () => h.reads.filter((r) => r.op === 'find' && r.where.name === 'widget').length; + const before = rowReads(); + expect((await read(h)).item.label).toBe('Widget'); // kept: the rows are less than a bound old + expect(rowReads()).toBe(before); + now = 1_000_000 + 30_001; // one bound after the rows were read, less than one after the move expect((await read(h)).item.label).toBe('Gadget'); }); + it('a counter move retires the row cache once its rows are more than a bound old: 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 + const clock = 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 + clock.pass(); + const mark = onStoreMark(h, async (real) => real()); + (h.registry.revision as number)++; // a local counter move opens a new bucket + expect((await read(h)).item.label).toBe('Gadget'); + expect(mark.calls).toBe(0); // the new bucket retired the rows: no confirmation was needed + 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')]); @@ -674,3 +727,46 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp } }); }); + +describe('[#34554] a list read that hydrates moves a counter, and the reads after it are no dearer than with the cache off', () => { + // review#2 S5 on #34494: on a kernel whose list read registers the stored + // rows back into the registry, every list read moves `registry.revision` + // with nothing changed. Each move opened a bucket that retired the row + // cache, so the list read and the item reads after it all went to the + // store. Measured before the fix: 3 store reads per round with the cache + // on against 1 with it off (one item), 7 against 3 (three items). + const rowsOf = (n: number): Row[] => Array.from({ length: n }, (_, i) => ({ + id: `r_w${i}`, type: 'object', name: `widget_${i}`, state: 'active', package_id: null, + updated_at: '2026-11-16T00:00:00.000Z', + metadata: JSON.stringify({ name: `widget_${i}`, label: `Widget ${i}`, fields: {} }), + })); + + async function storeReadsPerRound(ttl: string | undefined, items: number): Promise { + vi.unstubAllEnvs(); + if (ttl !== undefined) vi.stubEnv(META_COMPILE_CACHE_TTL_ENV, ttl); + const h = harness(rowsOf(3), { hydrationMovesRevision: true }); + const perRound: number[] = []; + for (let round = 0; round < 4; round++) { + const before = h.reads.length; + const revision = h.registry.revision as number; + await h.protocol.getMetaItems({ type: 'object' }); + // Non-vacuity: the list read moved the counter the cache reads. + expect(h.registry.revision).toBeGreaterThan(revision); + for (let i = 0; i < items; i++) { + expect((await h.protocol.getMetaItem({ type: 'object', name: `widget_${i}` })).item.label).toBe(`Widget ${i}`); + } + perRound.push(h.reads.length - before); + } + return perRound; + } + + for (const items of [1, 3]) { + it(`list then ${items} item read(s), in alternation: store reads per round equal the cache-off read`, async () => { + const on = await storeReadsPerRound(undefined, items); + const off = await storeReadsPerRound('0', items); + expect(on).toEqual(off); + // After the first round neither the list nor an item's rows are read again. + expect(on.slice(1)).toEqual([items, items, items]); + }); + } +}); diff --git a/packages/metadata-protocol/src/meta-compile-cache.ts b/packages/metadata-protocol/src/meta-compile-cache.ts index 9895bd5d12c..e14657ab320 100644 --- a/packages/metadata-protocol/src/meta-compile-cache.ts +++ b/packages/metadata-protocol/src/meta-compile-cache.ts @@ -79,9 +79,16 @@ * 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. Opening it retires the - * overlay row cache, as a confirmation does, so its entries never carry - * rows older than the bucket. + * renew on, so a local change costs no store read. Its first bound ends no + * later than one bound after the overlay row cache's current generation + * began (`readOverlayCacheGenerationSince`): every row set that cache holds + * was read since then, so no entry carries a row more than one bound old, + * and the row sets are kept. When that generation began more than a bound + * ago, opening the bucket retires the row cache, as a confirmation does. A + * counter move cannot make a stored row stale, so keeping the rows is what + * stops a list read that registers what is already registered (it moves + * `registry.revision`) from sending the list and item reads after it to + * the store (#34554). * * ⛔ 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 @@ -125,7 +132,7 @@ import { createHash } from 'node:crypto'; import { isMissingTableError } from '@objectstack/metadata/errors'; -import { readOverlayCacheGeneration, retireMetaOverlayCache } from './meta-overlay-cache.js'; +import { readOverlayCacheGeneration, readOverlayCacheGenerationSince, retireMetaOverlayCache } from './meta-overlay-cache.js'; import { metadataReadFailureError } from './protocol-client-failures.js'; import { servedRowChangedAtOf, withServedRowChangedAt } from './served-row-changed-at.js'; @@ -419,13 +426,25 @@ export async function readThroughMetaCompileCache( if (bucket === undefined || !sameStamp(bucket.stamp, stamp)) { // 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() }; + // are renewed on, so a counter move costs no store read. What it + // compiles must carry no row more than one bound old. Every row set + // the overlay row cache holds was read since its generation began, so + // the bound ends one bound after that and the rows are kept; when + // that is already past, the row cache is retired, as a confirmation + // retires it, and the bound is a full one from now. [#34554] A counter + // move never makes a stored row stale: retiring here on every move + // sent the list read and the item reads after each hydration to the + // store. + const now = Date.now(); + const since = readOverlayCacheGenerationSince(engine); + let confirmedUntil = now + ttlMs; + if (since !== undefined && since + ttlMs > now) { + confirmedUntil = since + ttlMs; + } else { + const overlay = retireMetaOverlayCache(engine); + if (overlay !== undefined) stamp = { ...stamp, overlay }; + } + bucket = { stamp, mark: undefined, confirmedUntil, confirming: undefined, entries: new Map() }; buckets.set(engine, bucket); } if (Date.now() >= bucket.confirmedUntil) { diff --git a/packages/metadata-protocol/src/meta-overlay-cache.ts b/packages/metadata-protocol/src/meta-overlay-cache.ts index e6e0d24881f..565a72ea1e2 100644 --- a/packages/metadata-protocol/src/meta-overlay-cache.ts +++ b/packages/metadata-protocol/src/meta-overlay-cache.ts @@ -301,6 +301,20 @@ const OVERLAY_READ_OPERATIONS: ReadonlySet = new Set(['find', 'findOne', /** Per-engine retirement counter. Compared, never interpreted. */ interface OverlayWriteState { gen: number; + /** + * [#34554] When {@link gen} last moved (or the state was made). Every row + * set held under the current generation was read at or after it: an entry + * is stamped with the generation its read STARTED under and refused when it + * moved, so none can predate this. Read by {@link readOverlayCacheGenerationSince}. + */ + since: number; +} + +/** Move the generation and note when (the one place a generation moves). */ +function advance(state: OverlayWriteState): number { + state.gen += 1; + state.since = Date.now(); + return state.gen; } /** @@ -341,7 +355,7 @@ export function readOverlayCacheGeneration(engine: unknown): number | undefined const seam = resolveWriteEpochSeam(engine); const register = (engine as { registerMiddleware?: unknown }).registerMiddleware; if (!seam || typeof register !== 'function') return undefined; - const state: OverlayWriteState = { gen: 0 }; + const state: OverlayWriteState = { gen: 0, since: Date.now() }; try { (register as ( fn: (ctx: { object?: unknown; operation?: unknown }, next: () => Promise) => Promise, @@ -357,11 +371,11 @@ export function readOverlayCacheGeneration(engine: unknown): number | undefined try { await next(); } finally { - state.gen += 1; + advance(state); } }); seam.subscribe((_epoch, reason) => { - if (reason !== 'write') state.gen += 1; + if (reason !== 'write') advance(state); }); } catch { overlayWriteStates.set(engine, null); @@ -388,8 +402,21 @@ 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; + return advance(state); +} + +/** + * [#34554] The wall-clock time the current generation began + * ({@link readOverlayCacheGeneration}): every row set this engine holds was + * read at or after it. `undefined` for an engine this cache does not cover. + * + * The shared compile cache reads it when a counter it watches moves, to keep + * the row sets instead of retiring them while its next bound still ends + * within one bound of this time (`meta-compile-cache.ts`). + */ +export function readOverlayCacheGenerationSince(engine: unknown): number | undefined { + if (!engine || typeof engine !== 'object') return undefined; + return overlayWriteStates.get(engine)?.since; } /**