Skip to content

Commit 8fd5004

Browse files
fix(objectql): a roll-up recompute stamps the master as the system, not the child's writer (#34242)
domain:server#5 · zhuangjianguo · session_01QsR2jTEivi2wogPpeo3xd5 <!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ Fixes #33950 Clause-②: no Metadata-protocol: none (runtime audit stamping; no authorable key changes; the dev confirms against the diff) ## 维护者速读 - 改了什么:子记录增删改或换父记录触发汇总字段重算时,主记录的「修改人」记为系统(`updated_by = null`,界面显示「系统」),「修改时间」刷新;不再记成写子记录的人。 - 为什么改:按裁决「记为系统并刷新时间」。原来财务只录了一张发票,合同就显示「最后修改人:财务」,审计记录误导。 - 风险与回滚:只改汇总重算这一次主记录写入的审计戳;用户直接改主记录、写子记录本身照旧记本人;主记录上的钩子和流程仍知道是谁触发的。回滚即回退本 PR。 - 先看:`packages/objectql/src/plugin.ts`(审计戳钩子里新增的系统分支),`packages/objectql/src/engine-summaries-and-expansion.ts`(重算写入带上引擎内部标记)。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run src/engine-summary-recompute-audit-actor.test.ts`,预期 5 个用例全绿(插入/修改/删除/换父 + 对照)。 - 需要你做的:无,席位落地。 ## What changes `recomputeSummaries` writes a child's roll-up onto the master through an ordinary engine `update`, under a `sudo()`-shaped context (`{ ...caller, isSystem: true }`). The caller's `userId` rides that context on purpose, so the master's hooks and record-triggered flows still know who triggered the write. The `sys_stamp_audit_update` hook read the same `userId` and stamped it into the master's `updated_by`. - `engine-summaries-and-expansion.ts`: the master update now carries `SUMMARY_RECOMPUTE_WRITE`, an engine-only `Symbol.for` option key. It reaches only that one update: the master's hooks keep the caller's context, and a write a hook issues through `ctx.api` carries the context, not this options bag. No door can build it from a request: `rejectUnknownEngineOptions` reads string keys only, and JSON carries no symbols. `WRITE_PRECONDITION_OPTION` already uses this precedent. - `plugin.ts`: the update stamp reads the key off `input.options`. When it is present, it stamps `updated_by = null` (ADR-0118 D1, only when the object has the column) and a fresh `updated_at`, whoever the session is. Every other write stamps exactly as before. A child insert, update and delete, and a re-parent (both the old and the new master), all reach the master through this one write. Ruling recorded on the card (comment 6902001862): 「确定汇总字段自动重算时主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. ## Tests - `packages/objectql/src/engine-summary-recompute-audit-actor.test.ts` boots the real `ObjectQLPlugin` stamp hook over a fake driver. It has rows for child insert, update, delete and re-parent (both masters) by user B on a master that user A last edited. Each asserts `updated_by === null` and a refreshed `updated_at`. CONTROL: B's direct edit of the master still stamps B. - `packages/qa/dogfood/test/summary-recompute-system-stamp.dogfood.test.ts` runs a real showcase boot (SQL driver, the app's own security profile, `AuditPlugin`). A signed-up member, who may create `showcase_task` but is refused a PATCH of `showcase_project`, adds a task. The project's `task_count` moves, its `updated_by` is `null`, `updated_at` moves, and no `sys_audit_log` row on the project names the member. CONTROL: the admin's own PATCH stamps the admin. ## Acceptance notes - Field history: the CRUD audit writer already drops summary-only updates, because `diff()` skips computed field types and the audit noise fields. So a recompute writes no ledger row at all. The dogfood pin asserts that no row on the master names the child writer. - The hook-level `runAs: 'system'` rule ("elevation is not anonymity, `updated_by` still names the operator") is unchanged. This PR scopes the system stamp to the recompute's own write, not to `isSystem` writes in general. - The `engine.ts` docblock on `ScopedRepo.execute` elevation still says `recomputeSummaries`'s `systemCtx` stamps `updated_by` from `userId`. That file is outside this card's file surface, so the sentence is left as is. It is now stale for the recompute only. - `backfillSummaryNulls` (`os migrate summary-nulls`) is a separate one-off writer and is not touched. ## Verification Readings were taken at `f89df01cd3` (same source as the head, before the `origin/main` merge and the double's bound fix). Every run went through `scripts/pm/os-verify-lock.sh`. <details><summary>Unit pin: green, then ablated red, then restored</summary> - Green: `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-summary-recompute-audit-actor.test.ts` gave `Tests 5 passed (5)` (VERDICT command-exit 0). - Ablation through `scripts/ablation-replace.mjs`, anchor `{ context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any` replaced by `{ context: systemCtx } as any`. This is the recompute write as it stands on `origin/main`. The mutation landed (anchor 1 to 0). Result: `Tests 4 failed | 1 passed (5)`. Insert, update, delete and re-parent each failed with `expected 'u_child_writer_b' to be null`, and the CONTROL passed. This also re-measures the card's premise on main: the child writer is stamped on the master. - Restore: blob equal to HEAD, `git diff HEAD` empty. </details> <details><summary>Dogfood pin (real driver, dist): green, then ablated red, then restored</summary> - Green after `pnpm --filter '@objectstack/dogfood^...' build`: `Tests 3 passed (3)`. - Ablation of the hook's read in `plugin.ts`: `hookCtx?.input?.options?.[SUMMARY_RECOMPUTE_WRITE] === true` was replaced by a never-true marker expression, then `@objectstack/objectql` was rebuilt. `ablation-dist-preflight` reported the marker present in 2 built files. Result: `Tests 1 failed | 2 passed (3)`, with `expected 'Cn8RZN9WCVK0GCCNpkmfRXg6YsOd4y1m' to be null`: the member's id was stamped on the project. - Restore leg: blob equal to HEAD, then a rebuild. Preflight `--absent` found the marker absent from all 14 built files, and the run was back to `Tests 3 passed (3)`. - The first ablation attempt was a no-op. Its replacement left `hookCtx` unread, so the DTS build failed (TS6133) and the suite never ran. It was redone with the expression above. </details> <details><summary>Gates (dispatch-gates --commands, derived for this diff)</summary> 76 derived commands were run locally, each with its exit code captured before any pipe. - All exited 0 except the three below. - `check:objectql-double-limit` first found the new test's driver double limit-blind. The double now applies the caller's bound after the filter and before the row copy, and the gate reads `OK` (754 graded, none new). - `check:dual-build-cjs-loads`: PREREQUISITE NOT MET. It needs `dist/` of packages outside this diff's closure. NOT MEASURED locally; CI runs it. - `check:type-check-debt`: PREREQUISITE NOT MET. Its closure build never got a turn on the shared lock. NOT MEASURED locally; CI runs it. </details> <details><summary>Declared narrowing: objectql typecheck and full suite go to CI</summary> `pnpm --filter @objectstack/objectql typecheck` and `pnpm --filter @objectstack/objectql test` were queued on the shared verify lock four times. Each attempt ended `queue-timeout (exit 99)` behind a sibling's full dogfood battery, which held the lock for over 50 minutes. NOT MEASURED locally: `TypeScript Type Check` and `Test Core` on this PR carry them. Measured later at the final head `24f850943a` (dev report, card comment 6906249947): objectql typecheck exit 0; `pnpm --filter @objectstack/objectql test` 599 files, 13285 tests passed; dogfood pin 3/3. No public export of `@objectstack/objectql` changes: the new symbol is not re-exported from `index.ts` or `core.ts`. So importers owe no tests of their own (the os-dev local-scope rule). `git merge-tree` against `origin/main`, #33887 and #33652 (the open PRs in neighbouring objectql files) is clean. No open PR touches either source file this PR edits. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4bd3f24 commit 8fd5004

5 files changed

Lines changed: 411 additions & 4 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a roll-up recompute records the master's last change as the system, not as the person who wrote the child
6+
7+
Clause-②: no
8+
Metadata-protocol: none (runtime audit stamping; no authorable key changes; the dev confirms against the diff)
9+
10+
When someone adds, changes, deletes or moves a child record, the engine recomputes the parent's `summary` (roll-up) fields. That recompute is a write onto the parent, and it used to stamp the parent's `updated_by` with the person who wrote the child. So a finance user who only added an invoice under a contract read as the contract's last editor, although they edited neither record and may hold no edit right on the contract.
11+
12+
The recompute now records the system as the actor on the parent: `updated_by` is set to `null` (the platform's system actor, which the Console shows as 系统), and `updated_at` is refreshed, because a figure on the parent did change. This holds for a child insert, update and delete, and for a child moved to another parent (both parents). The person's own write to the child is still stamped with their name, and a direct edit of the parent still stamps whoever made it. Hooks and record-triggered flows on the parent still see who triggered the change; only the parent's audit stamp changes.
13+
14+
What an upgrade changes: list views, reports, flows or filters on a parent's `updated_by` / "Last modified by" no longer match the child writer after a roll-up recompute; such a parent now reads as last changed by the system. Rows already stored keep the stamp they have until their next recompute or edit.

‎packages/objectql/src/engine-summaries-and-expansion.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,29 @@ import { ENGINE_WIRE_ONLY_SLOTS, WIRE_ONLY_CANONICAL_SHAPES } from './engine-top
5050
import { ObjectQLStatics as ObjectQL } from './engine.js';
5151
import type { ObjectQL as ObjectQLClass } from './engine.js';
5252

53+
/**
54+
* The engine's own mark on the master `update` a roll-up recompute issues
55+
* ({@link SummariesAndExpansionFacet.recomputeSummaries}): the write is the
56+
* SYSTEM's on the master's audit trail. `ObjectQLPlugin`'s
57+
* `sys_stamp_audit_update` hook reads it off the hook's `input.options` and
58+
* stamps `updated_by = null` (ADR-0118 D1: a system actor is `null` in a user
59+
* lookup column, no system account, no sentinel) and a fresh `updated_at`,
60+
* instead of the triggering child writer's `userId`. Ruling recorded on the
61+
* card, comment 6902001862: 「确定汇总字段自动重算时主记录的修改人和修改时间怎么记」
62+
* → 「记为系统并刷新时间」.
63+
*
64+
* An OPTION, not a context key, so it reaches exactly the one update it is put
65+
* on: the master's hooks keep the caller's context — `userId` included, so a
66+
* record-triggered flow or a hook on the master still knows who triggered the
67+
* write — and a write one of those hooks issues through `ctx.api` carries the
68+
* context, never this bag. A symbol, so no options object a door assembles
69+
* from a request can carry it (`rejectUnknownEngineOptions` reads string keys
70+
* only, and JSON has no symbols). `Symbol.for`, so every bundle of this
71+
* package — both entries, ESM and CJS — names the one key, the shape
72+
* `SECURITY_SERVICE_SOURCE_SLOT` takes for the same reason.
73+
*/
74+
export const SUMMARY_RECOMPUTE_WRITE: unique symbol = Symbol.for('objectstack.objectql.summaryRecomputeWrite');
75+
5376
/**
5477
* The `ObjectQL` members the bodies of {@link SummariesAndExpansionFacet} read — every one of
5578
* them, and no other. Each is typed AS the class member (an indexed access on
@@ -441,6 +464,17 @@ export class SummariesAndExpansionFacet {
441464
* `update` of the parent is refused exactly as before), the summary field
442465
* stays subject to the parent's FLS on read, and the only value this path can
443466
* move is the one the author DECLARED as a function of the child collection.
467+
*
468+
* # Who the master's audit trail names
469+
*
470+
* The SYSTEM, not the child's writer: the parent update carries
471+
* {@link SUMMARY_RECOMPUTE_WRITE}, so the audit stamp writes
472+
* `updated_by = null` and refreshes `updated_at` (a figure on the master did
473+
* change). Elevation alone would not say this — `userId` rides the elevated
474+
* context on purpose, and the stamp reads it — which is how a finance user
475+
* who only inserted an invoice came to read as the contract's last editor.
476+
* Insert, update, delete and a re-parent of a child all reach the master
477+
* through this one write, so they all stamp the same way.
444478
*/
445479
static async recomputeSummaries(this: Pick<SummariesAndExpansionHost, 'facade' | 'getSummaryDescriptors' | 'logger' | 'summaryRetryOptions' | 'update'>, childObject: string, records: any, previous: any, execCtx?: ExecutionContext): Promise<SummaryRecomputeFailure[]> {
446480
const descriptors = this.getSummaryDescriptors(childObject);
@@ -467,7 +501,11 @@ export class SummariesAndExpansionFacet {
467501
// lives where the insert-time seed and the one-off NULL backfill
468502
// can read the identical computation instead of copying it.
469503
const value = await aggregateSummaryValue(this.facade, desc, parentId, systemCtx);
470-
await this.update(desc.parentObject, { id: parentId, [desc.summaryField]: value }, { context: systemCtx } as any);
504+
await this.update(
505+
desc.parentObject,
506+
{ id: parentId, [desc.summaryField]: value },
507+
{ context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any,
508+
);
471509
}, this.summaryRetryOptions);
472510
} catch (err) {
473511
// Retries exhausted (or a non-transient failure). Record it so the
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// ── A roll-up recompute is a SYSTEM write on the master's audit trail ──
4+
//
5+
// A child write recomputes the master's `summary` columns through
6+
// `recomputeSummaries`, which issues an ordinary `update` of the master under a
7+
// `sudo()`-shaped context (`{ ...caller, isSystem: true }`). The caller's
8+
// `userId` rides along on purpose — hooks and record-triggered flows on the
9+
// master still know who triggered the write — but the audit stamp read that
10+
// same `userId` and wrote it into the master's `updated_by`. A finance user who
11+
// inserted an invoice under a contract therefore showed up as the contract's
12+
// last editor, though they edit neither record and hold no edit on it.
13+
//
14+
// Ruling (recorded on the card, comment 6902001862): 「确定汇总字段自动重算时
15+
// 主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. Under ADR-0118 D1
16+
// a system actor is `null` in a user lookup column (no system account, no
17+
// sentinel), so the recompute stamps `updated_by = null` and refreshes
18+
// `updated_at`; the UI renders the null as 系统.
19+
//
20+
// Every child write that recomputes goes through the same door, so each one is
21+
// a row here: insert, update, delete, and a re-parent (which recomputes BOTH the
22+
// old and the new master). The CONTROL is the other half of the contract: a
23+
// direct edit of the master by the same user still stamps that user — the fix
24+
// is scoped to the recompute's own write, not to `isSystem` writes in general.
25+
//
26+
// The harness boots the real `ObjectQLPlugin`, because the stamp under test is
27+
// its `sys_stamp_audit_update` hook. What reaches the fake driver's store IS the
28+
// stored row, so the store is the verdict.
29+
30+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
31+
import { ObjectKernel } from '@objectstack/core';
32+
import { ObjectQLPlugin } from './plugin.js';
33+
import { ObjectQL } from './engine.js';
34+
35+
const USER_A = 'u_owner_a';
36+
const USER_B = 'u_child_writer_b';
37+
/** An `updated_at` far in the past, so "the recompute refreshed it" is never a same-millisecond tie. */
38+
const STALE_AT = '2000-01-01T00:00:00.000Z';
39+
40+
function makeDriver() {
41+
const stores = new Map<string, Map<string, any>>();
42+
const storeFor = (o: string) => {
43+
let s = stores.get(o);
44+
if (!s) { s = new Map(); stores.set(o, s); }
45+
return s;
46+
};
47+
const matches = (row: any, where: any): boolean => {
48+
if (!where || typeof where !== 'object') return true;
49+
return Object.entries(where).every(([k, v]: [string, any]) => {
50+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
51+
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
52+
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
53+
if ('$eq' in v) return row?.[k] === v.$eq;
54+
if ('$in' in v) return Array.isArray(v.$in) && v.$in.includes(row?.[k]);
55+
throw new Error(`fake driver: unsupported operator in ${JSON.stringify(v)}`);
56+
}
57+
return row?.[k] === v;
58+
});
59+
};
60+
let n = 0;
61+
const driver: any = {
62+
name: 'rollup-audit', version: '0.0.0', supports: {},
63+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
64+
async syncSchema() {},
65+
async find(object: string, ast: any) {
66+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
67+
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
68+
return page.map((r) => ({ ...r }));
69+
},
70+
async findOne(object: string, ast: any) {
71+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
72+
return null;
73+
},
74+
async create(object: string, data: Record<string, unknown>) {
75+
n += 1;
76+
const id = (data.id as string) ?? `r_${n}`;
77+
const row = { ...data, id };
78+
storeFor(object).set(id, row);
79+
return { ...row };
80+
},
81+
async update(object: string, id: string, data: Record<string, unknown>) {
82+
const s = storeFor(object);
83+
const row = { ...s.get(id), ...data, id };
84+
s.set(id, row);
85+
return { ...row };
86+
},
87+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
88+
async count(object: string, ast: any) {
89+
return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).length;
90+
},
91+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
92+
return Promise.all(rows.map((r) => this.create(object, r)));
93+
},
94+
async bulkUpdate() { return []; }, async bulkDelete() {},
95+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
96+
async commit() {}, async rollback() {},
97+
};
98+
return { driver, storeFor };
99+
}
100+
101+
describe('roll-up recompute stamps the master as a system write (updated_by = null)', () => {
102+
let kernel: ObjectKernel;
103+
let ql: ObjectQL;
104+
let storeFor: ReturnType<typeof makeDriver>['storeFor'];
105+
106+
beforeEach(async () => {
107+
kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false });
108+
const d = makeDriver();
109+
storeFor = d.storeFor;
110+
await kernel.use({
111+
name: 'rollup-audit-driver-plugin', type: 'driver', version: '1.0.0',
112+
init: async (ctx: any) => { ctx.registerService('driver.rollup-audit', d.driver); },
113+
} as any);
114+
await kernel.use(new ObjectQLPlugin());
115+
await kernel.bootstrap();
116+
ql = kernel.getService<ObjectQL>('objectql');
117+
// The audit family (`updated_by` / `updated_at` / …) is NOT declared: the
118+
// registry injects it, exactly as on an authored business object.
119+
ql.registry.registerObject({
120+
name: 'contract',
121+
label: 'Contract',
122+
datasource: 'rollup-audit',
123+
fields: {
124+
name: { name: 'name', label: 'Name', type: 'text' },
125+
invoiced: { name: 'invoiced', label: 'Invoiced', type: 'summary', summaryOperations: { object: 'invoice', field: 'amount', function: 'sum' } },
126+
invoice_count: { name: 'invoice_count', label: 'Invoices', type: 'summary', summaryOperations: { object: 'invoice', function: 'count' } },
127+
},
128+
} as any, 'test', 'test');
129+
ql.registry.registerObject({
130+
name: 'invoice',
131+
label: 'Invoice',
132+
datasource: 'rollup-audit',
133+
fields: {
134+
amount: { name: 'amount', label: 'Amount', type: 'number' },
135+
contract: { name: 'contract', label: 'Contract', type: 'master_detail', reference: 'contract' },
136+
},
137+
} as any, 'test', 'test');
138+
});
139+
140+
afterEach(async () => {
141+
if (kernel.getState() === 'running') await kernel.shutdown();
142+
});
143+
144+
const as = (userId: string) => ({ context: { userId } as any });
145+
const master = (id: string) => storeFor('contract').get(id);
146+
147+
/** User A creates and last edits the master; its `updated_at` is then aged so a refresh is visible. */
148+
async function masterLastEditedByA(name: string): Promise<string> {
149+
const c = await ql.insert('contract', { name }, as(USER_A));
150+
await ql.update('contract', { id: c.id, name: `${name} (edited)` }, as(USER_A));
151+
expect(master(c.id).updated_by).toBe(USER_A);
152+
storeFor('contract').set(c.id, { ...master(c.id), updated_at: STALE_AT });
153+
return c.id;
154+
}
155+
156+
function expectSystemStamp(id: string) {
157+
const row = master(id);
158+
expect(row.updated_by).toBeNull();
159+
expect(row.updated_by).not.toBe(USER_B);
160+
expect(typeof row.updated_at).toBe('string');
161+
expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT));
162+
}
163+
164+
it('CONTROL: a direct edit of the master by B still stamps B', async () => {
165+
const id = await masterLastEditedByA('CTR-CONTROL');
166+
await ql.update('contract', { id, name: 'CTR-CONTROL (B)' }, as(USER_B));
167+
expect(master(id).updated_by).toBe(USER_B);
168+
expect(Date.parse(master(id).updated_at)).toBeGreaterThan(Date.parse(STALE_AT));
169+
});
170+
171+
it('a child INSERT by B recomputes the master and stamps it as the system', async () => {
172+
const id = await masterLastEditedByA('CTR-INSERT');
173+
await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_B));
174+
expect(master(id).invoiced).toBe(40);
175+
expect(master(id).invoice_count).toBe(1);
176+
expectSystemStamp(id);
177+
});
178+
179+
it('a child UPDATE by B recomputes the master and stamps it as the system', async () => {
180+
const id = await masterLastEditedByA('CTR-UPDATE');
181+
const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A));
182+
await ql.update('contract', { id, name: 'CTR-UPDATE (A again)' }, as(USER_A));
183+
storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT });
184+
expect(master(id).updated_by).toBe(USER_A);
185+
186+
await ql.update('invoice', { id: inv.id, amount: 55 }, as(USER_B));
187+
expect(master(id).invoiced).toBe(55);
188+
expectSystemStamp(id);
189+
});
190+
191+
it('a child DELETE by B recomputes the master and stamps it as the system', async () => {
192+
const id = await masterLastEditedByA('CTR-DELETE');
193+
const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A));
194+
await ql.update('contract', { id, name: 'CTR-DELETE (A again)' }, as(USER_A));
195+
storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT });
196+
expect(master(id).updated_by).toBe(USER_A);
197+
198+
await ql.delete('invoice', { where: { id: inv.id }, ...as(USER_B) } as any);
199+
expect(master(id).invoiced).toBe(0);
200+
expect(master(id).invoice_count).toBe(0);
201+
expectSystemStamp(id);
202+
});
203+
204+
it('a child RE-PARENT by B recomputes BOTH masters and stamps each as the system', async () => {
205+
const from = await masterLastEditedByA('CTR-FROM');
206+
const inv = await ql.insert('invoice', { contract: from, amount: 40 }, as(USER_A));
207+
await ql.update('contract', { id: from, name: 'CTR-FROM (A again)' }, as(USER_A));
208+
storeFor('contract').set(from, { ...master(from), updated_at: STALE_AT });
209+
const to = await masterLastEditedByA('CTR-TO');
210+
211+
await ql.update('invoice', { id: inv.id, contract: to }, as(USER_B));
212+
expect(master(from).invoiced).toBe(0);
213+
expect(master(to).invoiced).toBe(40);
214+
expectSystemStamp(from);
215+
expectSystemStamp(to);
216+
});
217+
});

‎packages/objectql/src/plugin.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
type UnservableControlledByParentMaster,
1010
} from './engine.js';
1111
import { OWNERSHIP_QUEUE_SOURCE_SLOT, describeMissingOwnershipQueueService } from './assignment-rules.js';
12+
import { SUMMARY_RECOMPUTE_WRITE } from './engine-summaries-and-expansion.js';
1213
import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts';
1314
import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol';
1415
import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core';
@@ -2099,8 +2100,22 @@ export class ObjectQLPlugin implements Plugin {
20992100
session: any,
21002101
isInsert: boolean,
21012102
seedReplay: boolean,
2103+
systemActor: boolean,
21022104
) => {
21032105
const now = stamp();
2106+
// A roll-up recompute's write onto the master (`SUMMARY_RECOMPUTE_WRITE`,
2107+
// set only by `recomputeSummaries`) is the SYSTEM's on the audit trail:
2108+
// `updated_by = null` (ADR-0118 D1) and a fresh `updated_at`, never the
2109+
// child writer the elevated context still carries as `userId`. Ruling
2110+
// recorded on the card, comment 6902001862 (「记为系统并刷新时间」). Update-only
2111+
// and unconditional on the session: a recompute triggered by a user-less
2112+
// write stamps the same null, and `preserveAudit` on the triggering
2113+
// import does not make a recompute historical.
2114+
if (systemActor && !isInsert) {
2115+
record.updated_at = now;
2116+
if (hasField(objectName, 'updated_by')) record.updated_by = null;
2117+
return;
2118+
}
21042119
// A "historical" import (#3493) reinstates the ORIGINAL timeline, so a
21052120
// client-supplied created_at/created_by/updated_at/updated_by is
21062121
// CLIENT-PREFERRED under `preserveAudit` — instead of being overwritten
@@ -2176,15 +2191,16 @@ export class ObjectQLPlugin implements Plugin {
21762191
session: any,
21772192
isInsert: boolean,
21782193
seedReplay: boolean,
2194+
systemActor = false,
21792195
) => {
21802196
if (Array.isArray(data)) {
21812197
for (const row of data) {
21822198
if (row && typeof row === 'object') {
2183-
applyToRecord(row as Record<string, any>, objectName, session, isInsert, seedReplay);
2199+
applyToRecord(row as Record<string, any>, objectName, session, isInsert, seedReplay, systemActor);
21842200
}
21852201
}
21862202
} else if (data && typeof data === 'object') {
2187-
applyToRecord(data as Record<string, any>, objectName, session, isInsert, seedReplay);
2203+
applyToRecord(data as Record<string, any>, objectName, session, isInsert, seedReplay, systemActor);
21882204
}
21892205
};
21902206

@@ -2202,6 +2218,15 @@ export class ObjectQLPlugin implements Plugin {
22022218
const isSeedReplay = (hookCtx: any): boolean =>
22032219
hookCtx?.input?.options?.context?.seedReplay === true;
22042220

2221+
/**
2222+
* Whether this `beforeUpdate` is the master write of a roll-up recompute.
2223+
* Read from `input.options` (the caller's own options bag, as above) under
2224+
* the engine's symbol key, which only `recomputeSummaries` sets — see
2225+
* `SUMMARY_RECOMPUTE_WRITE` for why it is an option and not a context key.
2226+
*/
2227+
const isSummaryRecomputeWrite = (hookCtx: any): boolean =>
2228+
hookCtx?.input?.options?.[SUMMARY_RECOMPUTE_WRITE] === true;
2229+
22052230
const builtinHooks: any[] = [
22062231
{
22072232
name: 'sys_stamp_audit_insert',
@@ -2224,7 +2249,7 @@ export class ObjectQLPlugin implements Plugin {
22242249
handler: async (hookCtx: any) => {
22252250
if (hookCtx.input?.data) {
22262251
// `seedReplay` is moot here: the update stamp never writes `created_at`.
2227-
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false);
2252+
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false, isSummaryRecomputeWrite(hookCtx));
22282253
}
22292254
},
22302255
},

0 commit comments

Comments
 (0)