Skip to content

Commit 4ec9cc2

Browse files
fix(metadata-protocol): a compile-cache bucket opened by a counter move keeps the row sets read within the last bound (#34592)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9D7K4emLL9dNcp4rQPn22Dw)_ Fixes #34554 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么:** 元数据编译缓存(#34494 加的)在注册表计数器变动、开新桶时,不再一律清掉 `sys_metadata` 行缓存;只要这批行是在一个周期(默认 30 秒)内读到的就留着,新桶第一个周期在「这批行读到后满一个周期」时结束。行更旧才照旧清掉。 - **为什么改:** 契约复审 S5 怀疑的情况实测成立:会把存储行注册回注册表的内核上,每次列表读都会推动 `registry.revision`,哪怕注册的东西没变。每次推动都清掉行缓存,于是列表读和其后的单项读全回到数据库。「列表 + 单项」交替时,缓存开着每轮 3 次库读,关着 1 次;三个单项时 7 对 3。 - **风险与回滚:** 新鲜度上限不变:任何答案里的行都不超过一个周期旧,同一进程内的写入照旧立即清缓存。修后同样的交替读与关缓存时一样多。回滚 = revert 本 PR。 - **先看:** `packages/metadata-protocol/src/meta-compile-cache.ts` 里开新桶的那段(`readThroughMetaCompileCache`),再看 `meta-overlay-cache.ts` 新增的 `readOverlayCacheGenerationSince`。 - **两分钟验证:** `pnpm --filter @objectstack/metadata-protocol exec vitest run src/meta-compile-cache.test.ts`,预期 40 个全过。 - **需要你做的:** 不需要。区线程审核后合入。 ## What changes - `meta-overlay-cache.ts`: the per-engine generation state now records `since`, the wall-clock time the current generation began (set wherever the generation moves: a `sys_metadata` write at the middleware seam, a non-`write` epoch bump, `retireMetaOverlayCache`). Every row set held under the current generation was read at or after it, because an entry is stamped with the generation its read started under. New export `readOverlayCacheGenerationSince(engine)`. - `meta-compile-cache.ts`: a bucket opened by a counter move (`registry.revision`, `objectRevision`, the metadata service's `revision`) no longer always retires the row cache. When the row cache's generation began less than one bound ago, the rows are kept and the bucket's first bound ends at `since + ttl`, so no answer carries a row more than one bound old, which is the bound the retirement was there to give. When it began a bound or more ago, the bucket retires the rows as before and its first bound is a full one. Confirmations are unchanged: each still retires the row cache. The module header says the same. ## Tests - New group in `meta-compile-cache.test.ts`, on a harness option `hydrationMovesRevision` (the double's `registerItem` and `registerObject` move the registry's counters, as every public write of the real `SchemaRegistry` does through `registry-revision.ts`): a list read of three stored objects, then 1 or 3 item reads, four rounds. Store reads per round with the cache on equal the cache-off reads, and after the first round they are only the item count. Each round asserts the list read moved `registry.revision` (non-vacuity). - **Forced test edit, named:** the existing pin "a counter move retires the row cache: a peer's write the row cache predates is in the new bucket's answer" asserted the old rule. It is replaced by two pins: (1) within one bound of the rows' read, a counter move keeps them (no row read from the store, the earlier answer served) and the peer's write is in the answer once that bound ends; (2) once the rows are more than a bound old, a counter move retires them and the peer's write is in the new bucket's answer with no confirmation reading (the old pin's assertion, at the age the rule now names). - [L1 R1, rework 1] `the bucket a counter move opens ends its first bound one bound after the kept rows were read, not one bound after the move`: rows read at T, a peer's write and a counter move at T + 20 s, the earlier answer still served with no row read, and the peer's write in the answer at T + 30.001 s, less than one bound after the move. Ablation of the mutant L1 named (`confirmedUntil = now + ttlMs` in the keep arm): this pin red, `expected 'Widget' to be 'Gadget'`, 1 of 40; restored, 40 of 40. - Ablation (one-off, not kept): the keep branch disabled (`if (false && …)`), 3 of 39 red: the keep pin (`expected 'Gadget' to be 'Widget'`) and both alternation pins (`[3,3,3,3]` against `[3,1,1,1]`, `[7,7,7,7]` against `[7,3,3,3]`); restored, all green. ## Reading (the card's acceptance) The double's store, three stored `object` rows, `getMetaItems({ type: 'object' })` then N `getMetaItem` reads, per round, store reads counted at the engine: | | round 1 | rounds 2 to 5 | |:--|:--|:--| | before, cache on, N=1 | 3 | 3 each (list rows, the item's rows, one `findOne`) | | before, cache off (`OS_METADATA_COMPILE_CACHE_TTL_MS=0`), N=1 | 3 | 1 each (the `findOne`) | | before, cache on, N=3 | 7 | 7 each | | before, cache off, N=3 | 7 | 3 each | | after, cache on, N=1 / N=3 | 3 / 7 | 1 / 3 each | "Cache off" is the uncached path the compile cache's own `0` setting gives (ADR-0156 D6), not a build of `main` before #34494; the one `findOne` per item read is the same in every row and is not this cache's. ## Verification Rework 1 (head a6661f5, one test added, no source change): `src/meta-compile-cache.test.ts` 40 of 40, `pnpm --filter @objectstack/metadata-protocol typecheck` exit 0. At head e62453c: - `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2`: exit 0, `Test Files 347 passed | 9 skipped (356)`, `Tests 23014 passed | 45 skipped (23059)`. - `pnpm --filter @objectstack/metadata-protocol typecheck`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands` derived 67 families; all 67 run with `< /dev/null`, exit codes captured before any pipe. `--ran`: `67 derived famil(ies) accounted for — 65 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)`: `check:dual-build-cjs-loads` and `check:lean-entry-closure` need a whole-workspace build; CI runs them. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRfW5u1LRmhWwaYHRp <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRfW5u1LRmhWwaYHRp --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 082f9c2 commit 4ec9cc2

4 files changed

Lines changed: 174 additions & 20 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a list read that registers stored rows no longer sends the reads after it to the store
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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).
11+
12+
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.

‎packages/metadata-protocol/src/meta-compile-cache.test.ts‎

Lines changed: 100 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ interface HarnessOptions {
5757
registryRevision?: boolean;
5858
/** The metadata service: `true` (counted, with a loader mark), `'no-revision'`, `'no-mark'`, or `false` (none). */
5959
metadataService?: true | 'no-revision' | 'no-mark' | false;
60+
/**
61+
* [#34554] `registerItem` and `registerObject` move `revision` (and
62+
* `objectRevision` for an object), as every public write of the real
63+
* `SchemaRegistry` does (`registry-revision.ts`), so a list read's
64+
* hydration moves the counters even when it registers what is there.
65+
*/
66+
hydrationMovesRevision?: boolean;
6067
}
6168

6269
function harness(rows: Row[], opts: HarnessOptions = {}) {
@@ -76,8 +83,14 @@ function harness(rows: Row[], opts: HarnessOptions = {}) {
7683
getPackage: () => undefined,
7784
getArtifactItem: () => undefined,
7885
isPackageDisabled: () => false,
79-
registerItem: () => { registryCalls.push('registerItem'); },
80-
registerObject: () => { registryCalls.push('registerObject'); },
86+
registerItem: () => {
87+
registryCalls.push('registerItem');
88+
if (opts.hydrationMovesRevision) (registry.revision as number) += 1;
89+
},
90+
registerObject: () => {
91+
registryCalls.push('registerObject');
92+
if (opts.hydrationMovesRevision) { (registry.revision as number) += 1; (registry.objectRevision as number) += 1; }
93+
},
8194
applyNavContributions: (app: unknown) => app,
8295
// ADR-0150 D3: a by-name read of a package-scoped type needs the resolver.
8396
readsByPackage: () => true,
@@ -634,17 +647,57 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
634647
mark.restore();
635648
});
636649

637-
it('a counter move retires the row cache: a peer\'s write the row cache predates is in the new bucket\'s answer', async () => {
650+
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 () => {
638651
vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here
639-
atBound();
652+
const clock = atBound();
640653
const rows = [storedObject('Widget')];
641654
const h = harness(rows);
642655
expect((await read(h)).item.label).toBe('Widget'); // the row cache is warm
643656
rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); // a peer replica with no bridge
644657
(h.registry.revision as number)++; // a local counter move opens a new bucket
658+
// The item's active rows (the row cache's by-name read, a `find`).
659+
const rowReads = () => h.reads.filter((r) => r.op === 'find' && r.where.name === 'widget').length;
660+
const before = rowReads();
661+
// The rows were read inside this bound: kept, so no row is more than one bound old.
662+
expect((await read(h)).item.label).toBe('Widget');
663+
expect(rowReads()).toBe(before);
664+
clock.pass(); // the new bucket's first bound ends one bound after those rows were read
665+
expect((await read(h)).item.label).toBe('Gadget');
666+
});
667+
668+
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 () => {
669+
vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here
670+
let now = 1_000_000;
671+
vi.spyOn(Date, 'now').mockImplementation(() => now);
672+
const rows = [storedObject('Widget')];
673+
const h = harness(rows);
674+
expect((await read(h)).item.label).toBe('Widget'); // the row cache is warm, its rows read at T
675+
now += 20_000; // part of a bound later
676+
rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); // a peer replica with no bridge
677+
(h.registry.revision as number)++; // a local counter move opens a new bucket at T + 20 s
678+
const rowReads = () => h.reads.filter((r) => r.op === 'find' && r.where.name === 'widget').length;
679+
const before = rowReads();
680+
expect((await read(h)).item.label).toBe('Widget'); // kept: the rows are less than a bound old
681+
expect(rowReads()).toBe(before);
682+
now = 1_000_000 + 30_001; // one bound after the rows were read, less than one after the move
645683
expect((await read(h)).item.label).toBe('Gadget');
646684
});
647685

686+
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 () => {
687+
vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '600000'); // the row cache outlives every bound here
688+
const clock = atBound();
689+
const rows = [storedObject('Widget')];
690+
const h = harness(rows);
691+
expect((await read(h)).item.label).toBe('Widget'); // the row cache is warm
692+
rows[0] = storedObject('Gadget', '2026-11-16T01:00:00.000Z'); // a peer replica with no bridge
693+
clock.pass();
694+
const mark = onStoreMark(h, async (real) => real());
695+
(h.registry.revision as number)++; // a local counter move opens a new bucket
696+
expect((await read(h)).item.label).toBe('Gadget');
697+
expect(mark.calls).toBe(0); // the new bucket retired the rows: no confirmation was needed
698+
mark.restore();
699+
});
700+
648701
it('a counter move costs no store read: the new bucket takes its reading at its first bound', async () => {
649702
const clock = atBound();
650703
const h = harness([storedObject('Widget')]);
@@ -674,3 +727,46 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
674727
}
675728
});
676729
});
730+
731+
describe('[#34554] a list read that hydrates moves a counter, and the reads after it are no dearer than with the cache off', () => {
732+
// review#2 S5 on #34494: on a kernel whose list read registers the stored
733+
// rows back into the registry, every list read moves `registry.revision`
734+
// with nothing changed. Each move opened a bucket that retired the row
735+
// cache, so the list read and the item reads after it all went to the
736+
// store. Measured before the fix: 3 store reads per round with the cache
737+
// on against 1 with it off (one item), 7 against 3 (three items).
738+
const rowsOf = (n: number): Row[] => Array.from({ length: n }, (_, i) => ({
739+
id: `r_w${i}`, type: 'object', name: `widget_${i}`, state: 'active', package_id: null,
740+
updated_at: '2026-11-16T00:00:00.000Z',
741+
metadata: JSON.stringify({ name: `widget_${i}`, label: `Widget ${i}`, fields: {} }),
742+
}));
743+
744+
async function storeReadsPerRound(ttl: string | undefined, items: number): Promise<number[]> {
745+
vi.unstubAllEnvs();
746+
if (ttl !== undefined) vi.stubEnv(META_COMPILE_CACHE_TTL_ENV, ttl);
747+
const h = harness(rowsOf(3), { hydrationMovesRevision: true });
748+
const perRound: number[] = [];
749+
for (let round = 0; round < 4; round++) {
750+
const before = h.reads.length;
751+
const revision = h.registry.revision as number;
752+
await h.protocol.getMetaItems({ type: 'object' });
753+
// Non-vacuity: the list read moved the counter the cache reads.
754+
expect(h.registry.revision).toBeGreaterThan(revision);
755+
for (let i = 0; i < items; i++) {
756+
expect((await h.protocol.getMetaItem({ type: 'object', name: `widget_${i}` })).item.label).toBe(`Widget ${i}`);
757+
}
758+
perRound.push(h.reads.length - before);
759+
}
760+
return perRound;
761+
}
762+
763+
for (const items of [1, 3]) {
764+
it(`list then ${items} item read(s), in alternation: store reads per round equal the cache-off read`, async () => {
765+
const on = await storeReadsPerRound(undefined, items);
766+
const off = await storeReadsPerRound('0', items);
767+
expect(on).toEqual(off);
768+
// After the first round neither the list nor an item's rows are read again.
769+
expect(on.slice(1)).toEqual([items, items, items]);
770+
});
771+
}
772+
});

‎packages/metadata-protocol/src/meta-compile-cache.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,16 @@
7979
* bound while it runs wait for it, and its failure reaches all of them. A
8080
* bucket opened by a counter move takes no reading: its first bound ends at
8181
* a confirmation that drops its entries and takes the reading later bounds
82-
* renew on, so a local change costs no store read. Opening it retires the
83-
* overlay row cache, as a confirmation does, so its entries never carry
84-
* rows older than the bucket.
82+
* renew on, so a local change costs no store read. Its first bound ends no
83+
* later than one bound after the overlay row cache's current generation
84+
* began (`readOverlayCacheGenerationSince`): every row set that cache holds
85+
* was read since then, so no entry carries a row more than one bound old,
86+
* and the row sets are kept. When that generation began more than a bound
87+
* ago, opening the bucket retires the row cache, as a confirmation does. A
88+
* counter move cannot make a stored row stale, so keeping the rows is what
89+
* stops a list read that registers what is already registered (it moves
90+
* `registry.revision`) from sending the list and item reads after it to
91+
* the store (#34554).
8592
*
8693
* ⛔ A renewal is a claim about what was looked at (ADR-0156 D5). When the
8794
* confirmation cannot read one of those (the store cannot be read, the
@@ -125,7 +132,7 @@
125132

126133
import { createHash } from 'node:crypto';
127134
import { isMissingTableError } from '@objectstack/metadata/errors';
128-
import { readOverlayCacheGeneration, retireMetaOverlayCache } from './meta-overlay-cache.js';
135+
import { readOverlayCacheGeneration, readOverlayCacheGenerationSince, retireMetaOverlayCache } from './meta-overlay-cache.js';
129136
import { metadataReadFailureError } from './protocol-client-failures.js';
130137
import { servedRowChangedAtOf, withServedRowChangedAt } from './served-row-changed-at.js';
131138

@@ -419,13 +426,25 @@ export async function readThroughMetaCompileCache<T>(
419426
if (bucket === undefined || !sameStamp(bucket.stamp, stamp)) {
420427
// A new bucket opens its first bound without a reading: the first
421428
// confirmation drops its entries and takes the reading later bounds
422-
// are renewed on, so a counter move costs no store read. It retires
423-
// the overlay row cache first, as a confirmation does: what it
424-
// compiles reads rows from now on, never rows that cache filled
425-
// before a peer's write, so its entries are at most one bound old.
426-
const overlay = retireMetaOverlayCache(engine);
427-
if (overlay !== undefined) stamp = { ...stamp, overlay };
428-
bucket = { stamp, mark: undefined, confirmedUntil: Date.now() + ttlMs, confirming: undefined, entries: new Map() };
429+
// are renewed on, so a counter move costs no store read. What it
430+
// compiles must carry no row more than one bound old. Every row set
431+
// the overlay row cache holds was read since its generation began, so
432+
// the bound ends one bound after that and the rows are kept; when
433+
// that is already past, the row cache is retired, as a confirmation
434+
// retires it, and the bound is a full one from now. [#34554] A counter
435+
// move never makes a stored row stale: retiring here on every move
436+
// sent the list read and the item reads after each hydration to the
437+
// store.
438+
const now = Date.now();
439+
const since = readOverlayCacheGenerationSince(engine);
440+
let confirmedUntil = now + ttlMs;
441+
if (since !== undefined && since + ttlMs > now) {
442+
confirmedUntil = since + ttlMs;
443+
} else {
444+
const overlay = retireMetaOverlayCache(engine);
445+
if (overlay !== undefined) stamp = { ...stamp, overlay };
446+
}
447+
bucket = { stamp, mark: undefined, confirmedUntil, confirming: undefined, entries: new Map() };
429448
buckets.set(engine, bucket);
430449
}
431450
if (Date.now() >= bucket.confirmedUntil) {

‎packages/metadata-protocol/src/meta-overlay-cache.ts‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,20 @@ const OVERLAY_READ_OPERATIONS: ReadonlySet<string> = new Set(['find', 'findOne',
301301
/** Per-engine retirement counter. Compared, never interpreted. */
302302
interface OverlayWriteState {
303303
gen: number;
304+
/**
305+
* [#34554] When {@link gen} last moved (or the state was made). Every row
306+
* set held under the current generation was read at or after it: an entry
307+
* is stamped with the generation its read STARTED under and refused when it
308+
* moved, so none can predate this. Read by {@link readOverlayCacheGenerationSince}.
309+
*/
310+
since: number;
311+
}
312+
313+
/** Move the generation and note when (the one place a generation moves). */
314+
function advance(state: OverlayWriteState): number {
315+
state.gen += 1;
316+
state.since = Date.now();
317+
return state.gen;
304318
}
305319

306320
/**
@@ -341,7 +355,7 @@ export function readOverlayCacheGeneration(engine: unknown): number | undefined
341355
const seam = resolveWriteEpochSeam(engine);
342356
const register = (engine as { registerMiddleware?: unknown }).registerMiddleware;
343357
if (!seam || typeof register !== 'function') return undefined;
344-
const state: OverlayWriteState = { gen: 0 };
358+
const state: OverlayWriteState = { gen: 0, since: Date.now() };
345359
try {
346360
(register as (
347361
fn: (ctx: { object?: unknown; operation?: unknown }, next: () => Promise<void>) => Promise<void>,
@@ -357,11 +371,11 @@ export function readOverlayCacheGeneration(engine: unknown): number | undefined
357371
try {
358372
await next();
359373
} finally {
360-
state.gen += 1;
374+
advance(state);
361375
}
362376
});
363377
seam.subscribe((_epoch, reason) => {
364-
if (reason !== 'write') state.gen += 1;
378+
if (reason !== 'write') advance(state);
365379
});
366380
} catch {
367381
overlayWriteStates.set(engine, null);
@@ -388,8 +402,21 @@ export function retireMetaOverlayCache(engine: unknown): number | undefined {
388402
if (!engine || typeof engine !== 'object') return undefined;
389403
const state = overlayWriteStates.get(engine);
390404
if (!state) return undefined;
391-
state.gen += 1;
392-
return state.gen;
405+
return advance(state);
406+
}
407+
408+
/**
409+
* [#34554] The wall-clock time the current generation began
410+
* ({@link readOverlayCacheGeneration}): every row set this engine holds was
411+
* read at or after it. `undefined` for an engine this cache does not cover.
412+
*
413+
* The shared compile cache reads it when a counter it watches moves, to keep
414+
* the row sets instead of retiring them while its next bound still ends
415+
* within one bound of this time (`meta-compile-cache.ts`).
416+
*/
417+
export function readOverlayCacheGenerationSince(engine: unknown): number | undefined {
418+
if (!engine || typeof engine !== 'object') return undefined;
419+
return overlayWriteStates.get(engine)?.since;
393420
}
394421

395422
/**

0 commit comments

Comments
 (0)