Skip to content

Commit b775133

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp
1 parent e350186 commit b775133

5 files changed

Lines changed: 141 additions & 44 deletions

File tree

‎.changeset/34206-shared-compile-cache.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Metadata-protocol: none
1313

1414
- **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.
1515
- **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.
16-
- **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.
16+
- **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.
1717
- **New public members (additive).** `SchemaRegistry#revision`, `MetadataManager#revision`, `MetadataManager#loaderChangeMark()`, the optional `MetadataLoader#changeMark()` and `FilesystemLoader#changeMark()`.
1818
- `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read, the same reads in the same order.
1919

‎content/docs/concepts/metadata-lifecycle.mdx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -321,11 +321,13 @@ The hash is `sha256:` + 64-hex of a canonical JSON serialization of the body, wi
321321
> bound above: the same write epoch retires it, as do the schema registry's and
322322
> the metadata service's own change counters. A peer's write that reaches no
323323
> epoch is seen at its own bound, `OS_METADATA_COMPILE_CACHE_TTL_MS` (default
324-
> 30s, `0` disables it), where it reads every `sys_metadata` row's content
325-
> and the metadata files it read, and recompiles if any of them moved, also
326-
> when a write left `updated_at` alone. Each such check also drops the cached
327-
> rows, so the recompile reads the store as it is then, and no compiled answer
328-
> is kept past ten bounds.
324+
> 30s, `0` disables it), where it reads every `sys_metadata` row's
325+
> bookkeeping columns (`version`, `checksum`, `updated_at`, identity and
326+
> state) and the metadata files it read, and recompiles if any of them moved.
327+
> Each such check also drops the cached rows, so the recompile reads the store
328+
> as it is then. No compiled answer is kept past ten bounds, which also bounds
329+
> a write that bypasses the engine and changes a body without moving any of
330+
> those columns.
329331
330332
---
331333

‎content/docs/deployment/environment-variables.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ With several replicas declared over the Redis cluster driver (`OS_CLUSTER_REPLIC
430430
| `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. |
431431
| `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. |
432432
| `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. |
433-
| `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. |
433+
| `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. |
434434
| `OS_INLINE_SEED_BUDGET_MS` | number | `8000` | Time budget for synchronous seed execution at boot before deferring to a worker. |
435435
| `OS_TENANT_AUDIT` | flag | `1` | Set to `0` to silence the tenant-isolation audit warnings emitted by the SQL driver. |
436436

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

Lines changed: 71 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -436,12 +436,12 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
436436
expect(h.byNameReads('widget')).toBeGreaterThan(before);
437437
});
438438

439-
/** Replace the confirmation's store reading (the whole-store `find` over the body column) until the returned restore runs. */
439+
/** Replace the confirmation's store reading (the whole-store `find` over the bookkeeping columns) until the returned restore runs. */
440440
const onStoreMark = (h: ReturnType<typeof harness>, impl: (real: () => Promise<unknown>) => Promise<unknown>) => {
441441
const find = h.engine.find as (table: string, q?: { where?: Row; fields?: string[] }) => Promise<unknown>;
442442
let calls = 0;
443443
h.engine.find = (table: string, q: { where?: Row; fields?: string[] } = {}) => {
444-
const isMark = table === 'sys_metadata' && Object.keys(q.where ?? {}).length === 0 && (q.fields ?? []).includes('metadata');
444+
const isMark = table === 'sys_metadata' && Object.keys(q.where ?? {}).length === 0 && (q.fields ?? []).includes('checksum');
445445
if (!isMark) return find(table, q);
446446
calls += 1;
447447
return impl(() => find(table, q));
@@ -503,19 +503,39 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
503503
expect((await read(h)).item.label).toBe('Gadget');
504504
});
505505

506-
it('another writer\'s change that leaves every bookkeeping column alone is still seen at the bound', async () => {
506+
it('an import that keeps updated_at but stamps its own checksum is seen at the bound', async () => {
507507
const clock = atBound();
508508
const rows = [storedObject('Widget')];
509509
const h = harness(rows);
510510
await read(h);
511511
clock.pass();
512512
await read(h);
513-
// A write that bypasses the engine: same id, same updated_at, new body.
514-
rows[0] = { ...rows[0], metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) };
513+
rows[0] = { ...rows[0], checksum: 'sha256:imported', metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) };
515514
clock.pass();
516515
expect((await read(h)).item.label).toBe('Gadget');
517516
});
518517

518+
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 () => {
519+
const clock = atBound();
520+
const rows = [storedObject('Widget')];
521+
const h = harness(rows);
522+
const mark = onStoreMark(h, async (real) => real());
523+
await read(h);
524+
clock.pass();
525+
await read(h); // the first confirmation takes the reading and recompiles
526+
rows[0] = { ...rows[0], metadata: JSON.stringify({ name: 'widget', label: 'Gadget', fields: {}, actions: [] }) };
527+
clock.pass();
528+
expect((await read(h)).item.label).toBe('Widget'); // the named class: unseen by the reading
529+
let label = 'Widget';
530+
for (let i = 0; i < META_COMPILE_CACHE_MAX_AGE_BOUNDS && label === 'Widget'; i++) {
531+
clock.pass();
532+
label = (await read(h)).item.label;
533+
}
534+
expect(label).toBe('Gadget');
535+
expect(mark.calls).toBeGreaterThan(0);
536+
mark.restore();
537+
});
538+
519539
it('another node\'s write stamped with an OLDER updated_at than the newest stored is still seen at the bound', async () => {
520540
const clock = atBound();
521541
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
532552
const clock = atBound();
533553
const h = harness([storedObject('Widget')]);
534554
await read(h);
555+
clock.pass();
556+
await read(h);
535557
const outage = new Error('connect ECONNREFUSED 127.0.0.1:5432');
536558
const mark = onStoreMark(h, async () => { throw outage; });
537559
clock.pass();
@@ -548,6 +570,8 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
548570
const clock = atBound();
549571
const h = harness([storedObject('Widget')]);
550572
await read(h);
573+
clock.pass();
574+
await read(h);
551575
const mark = onStoreMark(h, async () => { throw new Error('SQLITE_ERROR: no such table: sys_metadata'); });
552576
clock.pass();
553577
const before = h.byNameReads('widget');
@@ -571,19 +595,57 @@ describe('[#34206, ADR-0156 D5] at the bound the cache confirms before it recomp
571595
expect((await read(h)).item.label).toBe('Gadget');
572596
});
573597

574-
it(`no entry stands past ${META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds, renewals included`, async () => {
598+
it(`no entry is served past ${META_COMPILE_CACHE_MAX_AGE_BOUNDS} bounds from its compile, renewals included`, async () => {
575599
const clock = atBound();
576600
const h = harness([storedObject('Widget')]);
577601
await read(h);
602+
clock.pass();
603+
await read(h); // the first confirmation drops the bucket's first-bound entries
604+
const compiledAt = Date.now();
578605
const compiled = h.byNameReads('widget');
579-
for (let i = 1; i < META_COMPILE_CACHE_MAX_AGE_BOUNDS; i++) {
606+
const ttl = 30_000;
607+
let renewals = 0;
608+
for (;;) {
580609
clock.pass();
581610
await read(h);
611+
if (h.byNameReads('widget') > compiled) break;
612+
renewals += 1;
613+
// A renewal opens a bound that must still end within the cap.
614+
expect(Date.now() + ttl - compiledAt).toBeLessThanOrEqual(META_COMPILE_CACHE_MAX_AGE_BOUNDS * ttl);
615+
expect(renewals).toBeLessThan(META_COMPILE_CACHE_MAX_AGE_BOUNDS);
582616
}
583-
expect(h.byNameReads('widget')).toBe(compiled); // renewed every bound so far
617+
expect(renewals).toBe(META_COMPILE_CACHE_MAX_AGE_BOUNDS - 2); // with a bound read 1 ms late each time
618+
});
619+
620+
it('one confirmation per bound per engine: readers that cross the bound together share it', async () => {
621+
const clock = atBound();
622+
const h = harness([storedObject('Widget'), storedView('All widgets')]);
623+
await read(h);
624+
await read(h, 'view', 'widget_list');
625+
clock.pass();
626+
let release!: () => void;
627+
const gate = new Promise<void>((r) => { release = r; });
628+
const mark = onStoreMark(h, async (real) => { await gate; return real(); });
629+
const reads = [read(h), read(h, 'view', 'widget_list'), read(h)];
630+
await new Promise((r) => setTimeout(r, 0));
631+
release();
632+
await Promise.all(reads);
633+
expect(mark.calls).toBe(1);
634+
mark.restore();
635+
});
636+
637+
it('a counter move costs no store read: the new bucket takes its reading at its first bound', async () => {
638+
const clock = atBound();
639+
const h = harness([storedObject('Widget')]);
640+
const mark = onStoreMark(h, async (real) => real());
641+
await read(h);
642+
(h.registry.revision as number)++;
643+
await read(h);
644+
expect(mark.calls).toBe(0);
584645
clock.pass();
585646
await read(h);
586-
expect(h.byNameReads('widget')).toBeGreaterThan(compiled);
647+
expect(mark.calls).toBe(1);
648+
mark.restore();
587649
});
588650

589651
it('⛔ a source the confirmation cannot observe: nothing is renewed, every bound recompiles', async () => {

0 commit comments

Comments
 (0)