Skip to content

Commit 1ccb445

Browse files
perf(metadata-protocol): the served item read caches its caller-independent compiled answer (ADR-0156) (#34494)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X7M2UeBw2UaWzE4U5gbL4AH)_ Fixes #34206 (the third of three changes ruled in 6920925378: the cascade-delete memo #34437, merged as `d18d54bd`; ADR-0156 #34464, merged as `f8066085`; then this cache). Clause-②: yes Metadata-protocol: none ## 维护者速读 - 改了什么:按 ADR-0156 给元数据的单项读取(应用包里每个应用、对象、视图、页面、仪表盘都走它)加了一层共享编译缓存,只存所有人共用的编译结果;权限门、字段遮罩、翻译、ETag 和实时附带信息每次请求照算。为此三个来源各自记变更:对象注册表、元数据服务、`sys_metadata` 行。 - 为什么改:你 6920925378 裁决 B。Setup 应用包一次重复请求的数据库读取从 213 次降到 9 次,隔一分钟以上再打开的请求也受益,不会串权限。 - 风险与回滚:最坏情况是另一个进程改了元数据,本进程最多 30 秒后才看到(和现有行缓存同一个上限);本进程内的改动立即生效。`OS_METADATA_COMPILE_CACHE_TTL_MS=0` 就是原来的不缓存路径,回滚也可以直接撤这个 PR。 - 先看:`packages/metadata-protocol/src/meta-compile-cache.ts` 的文件头(缓存什么、每个来源靠什么失效、到期怎么确认),再看 `packages/objectql/src/registry-revision.ts`(注册表每个公开方法登记为读或写,漏登记编译不过)。 - 两分钟验证:`pnpm --filter @objectstack/metadata-protocol exec vitest run src/meta-compile-cache.test.ts`,预期 27 个全过。 - 需要你做的:暂无;席位安排契约复审,通过后落地。 ## What changes ADR-0156 implemented for the served item read (`getMetaItem`, the face `GET /api/v1/meta/:type/:name` and every app bundle member read go through). - **`packages/metadata-protocol/src/meta-compile-cache.ts`** (new): a per-engine cache of the compiled envelope of a by-name read of `app`, `object`, `view`, `page` and `dashboard`. A read naming a package, a state, a member or a draft preview is never cached. - **Stamp (D1 (a), D2).** Each entry is held under the stamp of every in-process counter it read: the `sys_metadata` overlay generation, `SchemaRegistry#objectRevision` and the new `SchemaRegistry#revision`, and the metadata service's identity and new `revision`. Any move drops every entry (one bucket per engine). A source without its counter makes the cache decline: a registry without `revision`, a metadata service without `revision`, an engine without the write-epoch seam. - **Bound and confirmation (D1 (b), D5).** At the bound (`OS_METADATA_COMPILE_CACHE_TTL_MS`, default 30000 ms, same parse as the overlay knob) the cache reads the store (bookkeeping columns of `sys_metadata` plus an age cap (see delta 6933554702), as the system; each confirmation also retires the overlay row cache, a compile in flight across a confirmation is not stored, and no entry is renewed past 10 bounds) and each loader's change mark. If both equal the last confirmed reading, the entries stand for another bound; otherwise they all go. If any reading is unavailable, nothing is renewed: the entries go and the bucket keeps no reading, so whatever is compiled under it lives one bound at most. A store fault at the confirmation is thrown as the uncached read throws it (`metadataReadFailureError`; an unprovisioned `sys_metadata` reads as "no reading"). - **Per source, which D5 branch (review#2 N6).** `sys_metadata` rows: observed (store reading). Files under a running process: observed (`FilesystemLoader#changeMark`). A `memory:` loader: in-process, seen by the service's `revision`. Any other loader without `changeMark` (a `datasource:` or `http:` loader): the recompile-at-bound branch, never renewed. No shipped composition registers one (`MetadataPlugin` builds its manager with the file loader only). - **Caller independence (D3).** The cached envelope is computed by the served face with no caller. The live trailers (`registration`, `disabledActions`, `cascadeDeleteObjects`) are stripped before storing and read again on every hit, so a trailer the live read no longer answers is absent. Every store and every serve is a `structuredClone`; the served-row change time is carried beside the envelope. - **Hydration (D4).** The served item read registers nothing in the registry; a hit leaves the registry exactly as a miss does. The list read (`getMetaItems`), which hydrates, is not cached. - **Knob (D6).** `0` is the uncached read: the same reads in the same order (pinned against a harness the cache declines). - **`packages/metadata-protocol/src/protocol-meta-item-reads.ts`**: `getMetaItem` reads through the cache. The three live trailers move into one exported `liveItemTrailers` used by both `readMetaItem` and a hit, so they are computed one way. - **`packages/objectql/src/registry-revision.ts`** (new) and **`registry.ts`**: `SchemaRegistry#revision`. Every public method is classified once as `read` or `write` in `SCHEMA_REGISTRY_METHOD_KINDS`, a `Record` over every public method name, so a new public method fails the type check until it is classified. Each `write` is wrapped at the prototype to move the counter before, after (also when it throws) and after a returned promise settles. ADR-0127 D2: the counter is owned at the source's own boundary, not kept as a list of call sites. - **`packages/metadata/src/metadata-manager.ts`**: `MetadataManager#revision`, moved in the in-memory store funnel (`writeRegistryEntry`, `deleteRegistryEntries`), `invalidateListCache` (every stored-set mutation the manager learns of), `notifyWatchersLocal`, `registerLoader` and `setTypeRegistry`; and `loaderChangeMark()`. - **`packages/metadata/src/loaders/loader-interface.ts`** and **`filesystem-loader.ts`**: the optional `MetadataLoader#changeMark()`, and the file loader's: one `stat` per type directory a read probed and per file a read resolved (a file created where a miss was remembered, edited or removed moves it). - **`content/docs/deployment/environment-variables.mdx`**: the new knob's row, beside the overlay knob. - **`scripts/engine-double-contract.pinned.json`**: the new test file's engine double, recorded by `--write`. ## Tests - `packages/metadata-protocol/src/meta-compile-cache.test.ts` (36). Repeat reads zero sources; cached ≡ uncached for each cached type (against the knob at `0`); a copy per call; live trailers read on every hit, and an absent one stays absent; D4 registry untouched. D7 retire pins, one per source, each with the new value in the next answer where it has one: a `sys_metadata` write, `registry.revision`, `objectRevision`, a registry item change, the service's `revision` and another service in its slot; controls: a write to another object and a plain repeat keep the entry. D2 declines: no registry `revision`, no service `revision`, no write-epoch seam; no metadata service at all still caches. D6: TTL `0` makes the same reads as a declined harness; the knob's parse. D5 with a mocked clock: nothing moved renews; another writer's row is seen at the bound; a loader mark move drops; a write that lands while the confirmation awaits the store is not hidden; a store outage fails the read with the driver error as cause and serves nothing; an unprovisioned store recompiles; ⛔ a source the confirmation cannot observe is never renewed (D7's added pin). - `packages/objectql/src/registry-revision.test.ts` (7): every classified name is a method and exactly the writes are wrapped; each of nine writes moves `revision`; a view registration moves it where `objectRevision` stays; a throwing write moves it; control: eleven reads leave it alone; per-registry counters; installing twice does not double-wrap. - `packages/objectql/src/engine-cascade-delete-objects.test.ts` (+3, L1 N1 on #34437): a package disable moves `objectRevision` and the next answer drops the child only the disabled extension made; an enable restores it; a refused registration run retires an answer memoized inside the run. - `packages/metadata/src/metadata-manager-change-revision.test.ts` (9): the manager's `revision` moves on register, re-register, unregister, a new loader and a new type registry, and in the store funnel on its own (the rollback path); control: reads leave it alone. `loaderChangeMark` skips `memory:` loaders and is `undefined` for a loader without a mark or whose mark throws. The file loader's mark moves on a file created where a miss was remembered, an in-place edit and a removal; control: a change in a directory no read probed leaves it. <details><summary>Ablations (12, each through <code>scripts/ablation-replace.mjs</code>, each restored to the HEAD blob)</summary> | Mutation | Red | |:--|:--| | a hit skips the stamp re-read | the confirmation race pin | | the bucket is not reset on a stamp change | 5 retire pins (rows, `revision`, `objectRevision`, registry item, service) | | the confirmation never drops entries | 3 D5 pins (store moved, loader mark moved, unobservable source) | | an unreadable mark renews | the unobservable-source pin | | a hit is served without a clone | the copy-per-call pin | | trailers are stored with the entry | the absent-trailer pin | | a store fault at the confirmation reads as "no reading" | the store outage pin | | registry writes are not wrapped | 5 registry revision pins | | the file loader does not record probed directories | the remembered-miss pin | | the manager's store funnel does not count | the store funnel pin | | a loader without a mark is skipped | the markless loader pin | </details> ## Acceptance (ruling item 5) Readings on one shared box, showcase `--fresh`, seeded admin, `X-OS-Debug-Timing: 1`, `meta` in ms; before is `main` d5e6b20 with the same build, after is this change. Absolutes are about a shared box; the database read counts are not. | Case | Before | After | |:--|:--|:--| | Setup bundle, immediate repeat | ~141 (131 to 145), 213 database reads | ~110 (92 to 124), 9 database reads | | Setup bundle, 304 | ~154 (121 to 178) | ~90 (83 to 100) | | Setup bundle, reload 65 s after the previous call | 426 / 372 / 402 (218 reads) | at `e350186c` (comment 6933083314): first bound 446 (warm-up recompile), then 176 / 154 (42 reads against 220); repeat and 304 unchanged at 9 reads | | showcase_app bundle, repeat | 62 to 89 | ~46 | | showcase_app bundle, 304 | 63 to 81 | 47 to 72 | The response bodies are byte-identical (md5) and the `ETag` is the same before and after. cloud#4563 acceptance 1 is judged on its staging reading. **At `b7751333` (delta 6933554702) and `3fa027d4` (delta 6933725901, review#2 S4 and L1 M1):** the store confirmation no longer digests row content. It reads bookkeeping columns plus an age cap; readings on a seeded 5 000-row store are in that delta. Where the Acceptance, Gates and D5 text above says otherwise, it describes `e350186c`, and the delta comment governs. Follow-up: #34522 (a write-moved column on `sys_metadata`), filed unclaimed. ## Verification <details><summary>Gates and tests (head 00fef25)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 104 commands derived at first, 112 after the ledger file joined the diff; all 112 run locally under `scripts/pm/os-verify-lock.sh`. Four were red on the first run and are fixed in this head: `check:durability-log-level` (the confirmation's store read now rethrows a non-benign fault), `check:test-source-alias` (the new test pays `@objectstack/lint` at collection), `check:engine-double-contract` (ledger recorded), and `check:adr-anchors` (ADR-0156 was not on `main` yet; green after #34464 merged). - Package suites: `pnpm --filter <pkg> test` under the verify lock, on the B commits over `main` d5e6b20 with a full build: `@objectstack/metadata-protocol` 347 files, 22995 passed, 45 skipped (rerun on the final code); `@objectstack/metadata` 2631 passed; `@objectstack/objectql` 13514 passed; `@objectstack/rest` 8564 passed, 350 skipped; `@objectstack/runtime` 609 files, 11290 tests, 11271 passed, 19 skipped; all exit 0. `pnpm --filter <pkg> typecheck` exit 0 for metadata-protocol, metadata and objectql (objectql's `check:test-typecheck` debt unchanged). `--ran` reconciliation: "112 derived, 112 run, 0 NOT-MEASURED, 0 UNRUN", exit 0 (record: `/mnt/project-files/pm-orders/objectstack/34206-B-gates-ran.txt`, project files). - `git merge-tree --write-tree` against every open pull request sharing a file: clean for #34347, #34333, #34429 and #34477; #30297 and #30657 are drafts based far behind `main` whose diffs touch every file here and do not merge-tree at all. - Families CI owns (the type-check lanes, Build Core, Test Core shards, the artifact rosters and the repo-wide `pnpm lint`) are read from this PR's check runs. - Dogfood battery: not owed (no `!` in the title, no `(narrowing)` arm). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (CI runs it.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset (`.changeset/34206-shared-compile-cache.md`, patch for the three packages); both declaration lines are filled in above. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is the repo's required Chinese summary). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp)_ Claim: amendment 3 on #34206 (6931913466) names this branch alone on its `Branch:` line. <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pmEYLVFDcQ1Z1CS8H --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6eceb46 commit 1ccb445

17 files changed

Lines changed: 1949 additions & 18 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/metadata': patch
4+
'@objectstack/objectql': patch
5+
---
6+
7+
perf(metadata-protocol): the served item read caches its caller-independent compiled answer (ADR-0156)
8+
9+
Clause-②: yes
10+
Metadata-protocol: none
11+
12+
`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.
13+
14+
- **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.
15+
- **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, 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.
17+
- **New public members (additive).** `SchemaRegistry#revision`, `MetadataManager#revision`, `MetadataManager#loaderChangeMark()`, the optional `MetadataLoader#changeMark()` and `FilesystemLoader#changeMark()`.
18+
- `OS_METADATA_COMPILE_CACHE_TTL_MS=0` is the uncached read, the same reads in the same order.
19+
20+
On a showcase Setup bundle, an immediate repeat made 213 database reads before and 9 after.

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,21 @@ The hash is `sha256:` + 64-hex of a canonical JSON serialization of the body, wi
313313
> the in-process `memory` driver, with no distributed driver behind it — does
314314
> a peer's overlay re-read still lag a remote publish by up to that TTL. See
315315
> [Environment variables](/docs/deployment/environment-variables).
316+
>
317+
> The served by-name read also caches its **compiled** answer for an `app`,
318+
> `object`, `view`, `page` or `dashboard` (ADR-0156), the part that does not
319+
> depend on the caller; the per-caller gate, field mask, translation and
320+
> `ETag` still run on every request. It adds no lag of its own on top of the
321+
> bound above: the same write epoch retires it, as do the schema registry's and
322+
> the metadata service's own change counters. A peer's write that reaches no
323+
> 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
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.
316331
317332
---
318333

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +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 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. |
433434
| `OS_INLINE_SEED_BUDGET_MS` | number | `8000` | Time budget for synchronous seed execution at boot before deferring to a worker. |
434435
| `OS_TENANT_AUDIT` | flag | `1` | Set to `0` to silence the tenant-isolation audit warnings emitted by the SQL driver. |
435436

0 commit comments

Comments
 (0)