Skip to content

Commit d18d54b

Browse files
perf(objectql): memoize the cascade-delete closure on the registry object revision (#34437)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X7M2UeBw2UaWzE4U5gbL4AH)_ Part of #34206 (route C, the first of three changes: C, then the ADR PR, then the shared compile cache, per ruling 6920925378 and claim amendment 2 6920972383). The card stays open after this lands. Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:「删除时会连带删掉哪些对象」这份清单,以前每读一个对象就把全部对象扫一遍重算;现在按对象注册表的版本号记住,版本号不变就直接给答案。 - 为什么改:控制台每次打开应用都要读整包元数据,包里每个对象都重算一次这份清单。Setup 包重复请求的 meta 中位数从约 184 ms 降到约 147 ms,隔一分钟再开从约 464 ms 降到约 356 ms。 - 风险与回滚:只有一种风险,就是对象变了而版本号没动、清单变旧;已核对注册表里每个让对象缓存失效的地方都会推进版本号。回滚就是撤掉这一个 PR,行为回到每次重算。 - 先看:`packages/objectql/src/engine-references-and-master-detail.ts` 末尾的 `getCascadeDeleteObjects` 与 `cascadeDeleteObjectsMemo` 说明块;`packages/objectql/src/engine-cascade-delete-objects.test.ts` 末尾新增的 describe。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-cascade-delete-objects.test.ts`,预期 14 个测试全绿。 - 需要你做的:无,席位落地。 ## What changes `ObjectQL#getCascadeDeleteObjects` (the objects a delete of a record can cascade into, which the metadata read serves beside every `object` item as `cascadeDeleteObjects`) is memoized per engine on the schema registry's existing `objectRevision`. - Key: the object name as asked, inside one memo per engine stamped with the revision it was filled at. A moved revision replaces the whole memo. A registry without the counter (a test double) declines the memo and every call computes, as before. - Value: the computed list, frozen; every call returns its own copy, so a caller that edits its list cannot change the next caller's answer. - A name the registry does not hold answers `undefined` and is not remembered, so the memo grows with the registered objects and never with what callers ask. - Only `packages/objectql/src/engine-references-and-master-detail.ts` changes in the runtime. The rule (`collectCascadeDeleteObjects`, `cascadeRelationsInto`, `cascadeRelationBehavior`) is untouched, and so is the delete walk, which still reads the rule fresh. ## Why The card's profile and the earlier report (6919782135) put the closure at about 47 ms of a Setup bundle call: an app bundle reads every object it names, and each read walked every registered object. The walk reads the registered object set and nothing else, and the registry already keeps a counter that moves on every change to that set, which the roll-up summary index and the record-currency parent lock already key on. ### Closure inputs, re-verified on 9e6fee1 before the first edit - `resolveObjectName` and `getObject` read the registry's object index (`resolveObjectKey`, `resolveObject`); `getAllObjects` reads the merged objects. - `cascadeRelationBehavior` reads one field definition (`statesDeleteSemantics`, `deleteWalkTargetOf`), resolves its target through the same index, and asks `isFederatedUnprovisionedInjectedColumn`, which reads only the schema it is handed (`isFederatedObject` and `resolveInjectedColumnProvenance` are pure functions of the definition). - Package enablement reaches the merged objects only through the fold (`withholdDisabledExtensions`), and `enablePackage` / `disablePackage` both call `invalidateAll`, which moves the revision. - Every site that drops the registry's merged-object cache moves `objectRevision`: `registerObject`, `unregisterObject`, `unregisterObjectsByPackage`, `removeObjectOverlay`, `withdrawObjectExtension`, `invalidate`, `invalidateAll`, `reset`. The refused-registration restore (`noteObjectEntry`'s restore closure) drops the cache without a bump itself, but its only caller, `restoringOnRefusal`, runs it inside a synchronous registration and calls `invalidateAll` right after `point.restore()`, so the revision moves there too. The earlier report's note on that restore is answered by this. - No row, no caller context, no datasource posture and no per-call option feeds it. ## Tests Seven pins in `packages/objectql/src/engine-cascade-delete-objects.test.ts`, a new top-level `describe` in the closure's existing harness file: - a second call at the same revision does no walk (`cascadeRelationBehavior` spy not called) and answers the same list; - invalidation: registering a cascading child moves the revision and the next call names it; unregistering one drops it; - control: a registry change that leaves the object revision alone (a `view` item) keeps the memo (no walk) and the answer stays right, with non-vacuity asserts that the view landed and the counter did not move; - cached equals uncached for every fixture object plus an unregistered name, the uncached reading taken through the same facet over a registry whose counter is hidden; - each call gets its own copy; - an unregistered name answers `undefined`, and its later registration is answered. Ablations (`scripts/ablation-replace.mjs`, each restored to the HEAD blob `ba03b08f`, `git diff HEAD` empty after each): | mutation | red pins | |:--|:--| | never invalidate (`memo.revision !== revision` dropped from the refill test) | 3: both invalidation pins and the existing protocol pin "an object registered later ... is on the next read" | | no memo (the lookup always misses) | 2: the second-call pin and the control | | no copy (the frozen list returned as is) | 1: the copy pin | <details><summary>Package runs</summary> - `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-cascade-delete-objects.test.ts`: Test Files 1 passed, Tests 14 passed. - `pnpm --filter @objectstack/objectql test`: Test Files 603 passed (603), Tests 13477 passed (13477), exit 0. - `pnpm --filter @objectstack/objectql typecheck`: exit 0; `check:test-typecheck: OK`, 39 files / 233 errors / 64 pinned signatures held in `test-typecheck-debt.json` (unchanged). </details> ## Acceptance notes - Readings for the card's three cases plus first call, below. The Setup bundle moves; the showcase app bundle (few objects) does not move beyond noise, which is what a per-object saving predicts. - The "reload more than one minute later" case is still dominated by the expired overlay row cache (about 219 queries, `db` 65 to 87 ms) and the full recompile; that is the shared compile cache's job (the third change), not this one. - Not measured: hosted staging; cloud#4563 acceptance 1 is judged there. ## Verification Same box, same build, `pnpm dev -- --fresh` showcase, seeded admin, `X-OS-Debug-Timing: 1`, `meta` member of `Server-Timing` in ms. "Before" is this branch with only `engine-references-and-master-detail.ts` restored to `origin/main` 9e6fee1 and objectql rebuilt (dist checked: 0 hits of the memo's name, 4 after the restore). Shared box: other agents' work may have been running. | case | Setup before | Setup after | showcase_app before | showcase_app after | |:--|:--|:--|:--|:--| | immediate repeat, 6 calls (median, range) | 183.5 (165–201) | 146.6 (142–204) | 68.4 (66–80) | 70.2 (64–107) | | 304 with If-None-Match, 6 calls | 169.6 (158–178) | 134.8 (117–153) | 76.4 (68–101) | 71.0 (65–78) | | reload 65 s after the previous call, 3 calls | 464 (364–481) | 356 (330–366) | 114 (100–114) | 83 (77–92) | | first call after a fresh boot, 3 boots | 889 (822–954) | 738 (664–781) | n/a | n/a | <details><summary>Raw readings</summary> Before, Setup: repeat 201.02 / 187.39 / 183.25 / 183.83 / 165.43 / 170.27; 304 168.97 / 158.21 / 167.23 / 171.11 / 170.15 / 177.99; reload 464.12 / 480.78 / 363.73; first call 953.69 / 889.24 / 822.17. After, Setup: repeat 157.06 / 143.86 / 204.05 / 148.84 / 144.26 / 142.43; 304 152.45 / 153.17 / 118.51 / 117.11 / 150.09 / 119.56; reload 329.69 / 365.96 / 355.66; first call 663.82 / 780.87 / 737.67. Before, showcase_app: repeat 65.54 / 66.51 / 71.57 / 68.52 / 68.19 / 79.83; 304 77.19 / 68.62 / 75.6 / 67.98 / 101 / 77.63; reload 114.31 / 114.27 / 99.81. After, showcase_app: repeat 73.99 / 106.76 / 63.87 / 66.49 / 64.4 / 77.97; 304 70.8 / 64.81 / 75.38 / 71.17 / 77.53 / 65.38; reload 82.84 / 92.1 / 77.31. </details> <details><summary>Gates (head a61501a)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 65 commands derived for this diff (49 by path, 9 by change kind, 9 whole-tree); all 65 run locally, each exit 0, recorded as `COMMAND :: exit CODE`. - `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE`: "65 derived famil(ies) accounted for — 65 run, 0 NOT-MEASURED (a DERIVED zero — all 65 recorded an exit code and none of them is 3)", exit 0. - `node scripts/check-nul-bytes.mjs`: exit 0. - `git merge-tree --write-tree origin/main HEAD` against `origin/main` c9ef653: clean (exit 0); `origin/main` has not touched the closure files or the registry since the base. No open pull request touches the three files (39 open heads read; two old ones whose history this checkout lacks were read through their file lists, both empty). - 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, not re-run here. - 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, and both declaration lines are filled in here and in the changeset. - [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 by [Claude Code](https://claude.ai/code/session_01FEkQ5oyZgRX9Qc1ZHsMRQp)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6a7403b commit d18d54b

3 files changed

Lines changed: 185 additions & 8 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
`ObjectQL#getCascadeDeleteObjects` remembers its answer per object name until the schema registry's `objectRevision` moves, instead of walking every registered object on each call. The metadata read serves this list beside every `object` item (`cascadeDeleteObjects`), so an app bundle request no longer repeats the walk once per object it names. The answer is unchanged: every registry change that drops the registry's merged-object cache also moves `objectRevision`, and each call still gets its own copy of the list.

‎packages/objectql/src/engine-cascade-delete-objects.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,101 @@ describe('[#28001] the object read serves `cascadeDeleteObjects` beside the item
236236
.toEqual(['cd_loner_line']);
237237
});
238238
});
239+
240+
/**
241+
* [#34206] The closure is memoized per engine on the registry's
242+
* `objectRevision`: the metadata read serves it beside every object, and an
243+
* app bundle reads every object it names, so the walk over the whole registry
244+
* ran once per object per bundle request. The pins: a move of the revision
245+
* retires the memo; a registry change that does not move it (a view) keeps the
246+
* memo and the answer stays right; the memoized answer equals the uncached
247+
* one for every object; and a caller's copy is its own.
248+
*/
249+
describe('[#34206] getCascadeDeleteObjects is memoized on the registry object revision', () => {
250+
/** How many relation judgements the closure made: the walk's own unit of work. */
251+
function countWalk(engine: ObjectQL) {
252+
return vi.spyOn(engine as any, 'cascadeRelationBehavior');
253+
}
254+
255+
it('a second call at the same revision does no walk, and answers the same list', async () => {
256+
const { engine } = await makeEngine();
257+
const first = engine.getCascadeDeleteObjects('cd_parent');
258+
const walk = countWalk(engine);
259+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(first);
260+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child', 'cd_grandchild']);
261+
expect(walk).not.toHaveBeenCalled();
262+
});
263+
264+
it('invalidation: registering a cascading child moves the revision, and the next call names it', async () => {
265+
const { engine } = await makeEngine();
266+
expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual([]);
267+
const before = engine.registry.objectRevision;
268+
engine.registry.registerObject({
269+
name: 'cd_loner_line', label: 'Loner line',
270+
fields: { id, name, loner: { name: 'loner', type: 'master_detail', reference: 'cd_loner', required: true } },
271+
} as any, '__test__');
272+
expect(engine.registry.objectRevision).not.toBe(before);
273+
expect(engine.getCascadeDeleteObjects('cd_loner')).toEqual(['cd_loner_line']);
274+
});
275+
276+
it('invalidation: unregistering the cascading child drops it from the next answer', async () => {
277+
const { engine } = await makeEngine();
278+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child', 'cd_grandchild']);
279+
engine.registry.unregisterObject('cd_grandchild', { force: true });
280+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child']);
281+
});
282+
283+
it('control: a registry change that leaves the object revision alone keeps the memo, and the answer is still right', async () => {
284+
const { engine } = await makeEngine();
285+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child', 'cd_grandchild']);
286+
const before = engine.registry.objectRevision;
287+
engine.registry.registerItem('view', { name: 'cd_parent_all', object: 'cd_parent', type: 'grid' } as any, 'name', '__test__');
288+
// Non-vacuity: the view really landed, and the counter did not move.
289+
expect(engine.registry.getItem('view', 'cd_parent_all')).toBeDefined();
290+
expect(engine.registry.objectRevision).toBe(before);
291+
const walk = countWalk(engine);
292+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child', 'cd_grandchild']);
293+
expect(walk).not.toHaveBeenCalled();
294+
});
295+
296+
it('cached equals uncached for every object, the uncached reading taken from a registry with no counter', async () => {
297+
const { engine } = await makeEngine();
298+
const { ReferencesAndMasterDetailFacet } = await import('./engine-references-and-master-detail.js');
299+
// The registry with its counter hidden: the memo declines and every call walks.
300+
const registry = engine.registry;
301+
const counterless = new Proxy(registry, {
302+
get: (target, key) => (key === 'objectRevision' ? undefined : Reflect.get(target, key, target)),
303+
});
304+
const uncachedHost = {
305+
_registry: counterless,
306+
cascadeRelationBehavior: (...a: unknown[]) => (engine as any).cascadeRelationBehavior(...a),
307+
resolveObjectName: (n: string) => (engine as any).resolveObjectName(n),
308+
};
309+
const names = [...OBJECTS.map((o) => o.name), 'cd_no_such_object'];
310+
for (const n of names) {
311+
const uncached = ReferencesAndMasterDetailFacet.getCascadeDeleteObjects.call(uncachedHost as any, n);
312+
// First call fills the memo, the second reads it.
313+
expect(engine.getCascadeDeleteObjects(n)).toEqual(uncached);
314+
expect(engine.getCascadeDeleteObjects(n)).toEqual(uncached);
315+
}
316+
// Non-vacuity: the uncached path walked at least once.
317+
const walk = countWalk(engine);
318+
ReferencesAndMasterDetailFacet.getCascadeDeleteObjects.call(uncachedHost as any, 'cd_parent');
319+
expect(walk).toHaveBeenCalled();
320+
});
321+
322+
it('each call gets its own copy: editing one answer does not change the next', async () => {
323+
const { engine } = await makeEngine();
324+
const mine = engine.getCascadeDeleteObjects('cd_parent')!;
325+
mine.push('cd_tag');
326+
mine.reverse();
327+
expect(engine.getCascadeDeleteObjects('cd_parent')).toEqual(['cd_child', 'cd_grandchild']);
328+
});
329+
330+
it('a name the registry does not hold answers `undefined`, and its later registration is answered', async () => {
331+
const { engine } = await makeEngine();
332+
expect(engine.getCascadeDeleteObjects('cd_later')).toBeUndefined();
333+
engine.registry.registerObject({ name: 'cd_later', label: 'Later', fields: { id, name } } as any, '__test__');
334+
expect(engine.getCascadeDeleteObjects('cd_later')).toEqual([]);
335+
});
336+
});

‎packages/objectql/src/engine-references-and-master-detail.ts‎

Lines changed: 79 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -638,14 +638,85 @@ export class ReferencesAndMasterDetailFacet {
638638
return members;
639639
}
640640

641-
/** The body of `ObjectQL#getCascadeDeleteObjects`; the method's docblock there is its contract. */
641+
/**
642+
* The body of `ObjectQL#getCascadeDeleteObjects`; the method's docblock there is its contract.
643+
*
644+
* [#34206] Memoized per engine on the registry's `objectRevision`
645+
* ({@link cascadeDeleteObjectsMemo}): the answer is computed once per
646+
* object name per revision and each call gets its own copy.
647+
*/
642648
static getCascadeDeleteObjects(this: Pick<ReferencesAndMasterDetailHost, '_registry' | 'cascadeRelationBehavior' | 'resolveObjectName'>, object: string): string[] | undefined {
643-
if (!this._registry.getObject(object)) return undefined;
644-
const host: ThisParameterType<typeof collectCascadeDeleteObjects> = {
645-
cascadeRelationBehavior: (...a) => this.cascadeRelationBehavior(...a),
646-
};
647-
return collectCascadeDeleteObjects.call(
648-
host, this.resolveObjectName(object), this._registry.getAllObjects(),
649-
);
649+
const revision = (this._registry as unknown as { objectRevision?: unknown }).objectRevision;
650+
if (typeof revision !== 'number') return computeCascadeDeleteObjects.call(this, object);
651+
let memo = cascadeDeleteObjectsMemo.get(this);
652+
if (memo === undefined || memo.revision !== revision) {
653+
memo = { revision, answers: new Map() };
654+
cascadeDeleteObjectsMemo.set(this, memo);
655+
}
656+
let answer = memo.answers.get(object);
657+
if (answer === undefined) {
658+
const computed = computeCascadeDeleteObjects.call(this, object);
659+
// A name the registry does not hold is not remembered: the miss is one
660+
// index read, and remembering it would let a caller grow the memo with
661+
// names that do not exist.
662+
if (computed === undefined) return undefined;
663+
answer = Object.freeze(computed);
664+
memo.answers.set(object, answer);
665+
}
666+
return [...answer];
650667
}
651668
}
669+
670+
/**
671+
* [#34206] The memo of {@link ReferencesAndMasterDetailFacet.getCascadeDeleteObjects},
672+
* one per engine (keyed on the engine's facet host, which `FacetHost.of`
673+
* builds once per engine and keeps for its life).
674+
*
675+
* WHY: the metadata read serves this closure beside every `object` item
676+
* (`cascadeDeleteObjects`), and an app bundle reads every object it names, so
677+
* the walk over every registered object ran once per object per bundle
678+
* request: about a fifth of a Setup bundle's server time, a 304 included.
679+
*
680+
* WHY THE KEY IS SOUND: the closure reads the registered object set and
681+
* nothing else. `resolveObjectName` and `getObject` read the registry's
682+
* object index; `getAllObjects` reads the merged objects;
683+
* `cascadeRelationBehavior` reads one field definition and resolves its
684+
* target's name through the same index (`statesDeleteSemantics`,
685+
* `deleteWalkTargetOf`, `isFederatedUnprovisionedInjectedColumn` read the
686+
* definitions they are handed). No row, no package flag of its own, no
687+
* caller, no datasource. The registry's `objectRevision` moves on every
688+
* change to that set: every site that drops its merged-object cache bumps it
689+
* (`registerObject`, `unregisterObject`, `unregisterObjectsByPackage`,
690+
* `removeObjectOverlay`, `withdrawObjectExtension`, `invalidate`,
691+
* `invalidateAll` (which every package enable and disable calls), `reset`,
692+
* and a refused registration run's restore, which `invalidateAll` follows).
693+
* So this memo is exactly as fresh as the registry's own merged-object cache,
694+
* and the roll-up summary index and the record-currency parent lock already
695+
* key on the same counter.
696+
*
697+
* A registry without the counter (a test double) declines the memo: every
698+
* call computes. Only a name the registry holds is remembered, so the memo
699+
* grows with the registered objects, never with what callers ask. The
700+
* cached list is frozen and every call returns a copy, so a caller that edits
701+
* its list cannot change the next caller's answer.
702+
*
703+
* What it does not see: a subclass or spy that changes
704+
* `cascadeRelationBehavior`'s answer AFTER the first call at a revision. The
705+
* rule is code, not state, and the engine's own delete walk reads the same
706+
* rule fresh, so this only matters to a test that swaps the rule mid-run.
707+
*/
708+
const cascadeDeleteObjectsMemo = new WeakMap<object, {
709+
revision: number;
710+
answers: Map<string, readonly string[]>;
711+
}>();
712+
713+
/** The uncached closure: the body {@link ReferencesAndMasterDetailFacet.getCascadeDeleteObjects} memoizes. */
714+
function computeCascadeDeleteObjects(this: Pick<ReferencesAndMasterDetailHost, '_registry' | 'cascadeRelationBehavior' | 'resolveObjectName'>, object: string): string[] | undefined {
715+
if (!this._registry.getObject(object)) return undefined;
716+
const host: ThisParameterType<typeof collectCascadeDeleteObjects> = {
717+
cascadeRelationBehavior: (...a) => this.cascadeRelationBehavior(...a),
718+
};
719+
return collectCascadeDeleteObjects.call(
720+
host, this.resolveObjectName(object), this._registry.getAllObjects(),
721+
);
722+
}

0 commit comments

Comments
 (0)