Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/33950-summary-recompute-system-stamp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/objectql': patch
---

fix(objectql): a roll-up recompute records the master's last change as the system, not as the person who wrote the child

Clause-②: no
Metadata-protocol: none (runtime audit stamping; no authorable key changes; the dev confirms against the diff)

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.

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.

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.
40 changes: 39 additions & 1 deletion packages/objectql/src/engine-summaries-and-expansion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,29 @@ import { ENGINE_WIRE_ONLY_SLOTS, WIRE_ONLY_CANONICAL_SHAPES } from './engine-top
import { ObjectQLStatics as ObjectQL } from './engine.js';
import type { ObjectQL as ObjectQLClass } from './engine.js';

/**
* The engine's own mark on the master `update` a roll-up recompute issues
* ({@link SummariesAndExpansionFacet.recomputeSummaries}): the write is the
* SYSTEM's on the master's audit trail. `ObjectQLPlugin`'s
* `sys_stamp_audit_update` hook reads it off the hook's `input.options` and
* stamps `updated_by = null` (ADR-0118 D1: a system actor is `null` in a user
* lookup column, no system account, no sentinel) and a fresh `updated_at`,
* instead of the triggering child writer's `userId`. Ruling recorded on the
* card, comment 6902001862: 「确定汇总字段自动重算时主记录的修改人和修改时间怎么记」
* → 「记为系统并刷新时间」.
*
* An OPTION, not a context key, so it reaches exactly the one update it is put
* on: the master's hooks keep the caller's context — `userId` included, so a
* record-triggered flow or a hook on the master still knows who triggered the
* write — and a write one of those hooks issues through `ctx.api` carries the
* context, never this bag. A symbol, so no options object a door assembles
* from a request can carry it (`rejectUnknownEngineOptions` reads string keys
* only, and JSON has no symbols). `Symbol.for`, so every bundle of this
* package — both entries, ESM and CJS — names the one key, the shape
* `SECURITY_SERVICE_SOURCE_SLOT` takes for the same reason.
*/
export const SUMMARY_RECOMPUTE_WRITE: unique symbol = Symbol.for('objectstack.objectql.summaryRecomputeWrite');

/**
* The `ObjectQL` members the bodies of {@link SummariesAndExpansionFacet} read — every one of
* them, and no other. Each is typed AS the class member (an indexed access on
Expand Down Expand Up @@ -441,6 +464,17 @@ export class SummariesAndExpansionFacet {
* `update` of the parent is refused exactly as before), the summary field
* stays subject to the parent's FLS on read, and the only value this path can
* move is the one the author DECLARED as a function of the child collection.
*
* # Who the master's audit trail names
*
* The SYSTEM, not the child's writer: the parent update carries
* {@link SUMMARY_RECOMPUTE_WRITE}, so the audit stamp writes
* `updated_by = null` and refreshes `updated_at` (a figure on the master did
* change). Elevation alone would not say this — `userId` rides the elevated
* context on purpose, and the stamp reads it — which is how a finance user
* who only inserted an invoice came to read as the contract's last editor.
* Insert, update, delete and a re-parent of a child all reach the master
* through this one write, so they all stamp the same way.
*/
static async recomputeSummaries(this: Pick<SummariesAndExpansionHost, 'facade' | 'getSummaryDescriptors' | 'logger' | 'summaryRetryOptions' | 'update'>, childObject: string, records: any, previous: any, execCtx?: ExecutionContext): Promise<SummaryRecomputeFailure[]> {
const descriptors = this.getSummaryDescriptors(childObject);
Expand All @@ -467,7 +501,11 @@ export class SummariesAndExpansionFacet {
// lives where the insert-time seed and the one-off NULL backfill
// can read the identical computation instead of copying it.
const value = await aggregateSummaryValue(this.facade, desc, parentId, systemCtx);
await this.update(desc.parentObject, { id: parentId, [desc.summaryField]: value }, { context: systemCtx } as any);
await this.update(
desc.parentObject,
{ id: parentId, [desc.summaryField]: value },
{ context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any,
);
}, this.summaryRetryOptions);
} catch (err) {
// Retries exhausted (or a non-transient failure). Record it so the
Expand Down
217 changes: 217 additions & 0 deletions packages/objectql/src/engine-summary-recompute-audit-actor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// ── A roll-up recompute is a SYSTEM write on the master's audit trail ──
//
// A child write recomputes the master's `summary` columns through
// `recomputeSummaries`, which issues an ordinary `update` of the master under a
// `sudo()`-shaped context (`{ ...caller, isSystem: true }`). The caller's
// `userId` rides along on purpose — hooks and record-triggered flows on the
// master still know who triggered the write — but the audit stamp read that
// same `userId` and wrote it into the master's `updated_by`. A finance user who
// inserted an invoice under a contract therefore showed up as the contract's
// last editor, though they edit neither record and hold no edit on it.
//
// Ruling (recorded on the card, comment 6902001862): 「确定汇总字段自动重算时
// 主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. Under ADR-0118 D1
// a system actor is `null` in a user lookup column (no system account, no
// sentinel), so the recompute stamps `updated_by = null` and refreshes
// `updated_at`; the UI renders the null as 系统.
//
// Every child write that recomputes goes through the same door, so each one is
// a row here: insert, update, delete, and a re-parent (which recomputes BOTH the
// old and the new master). The CONTROL is the other half of the contract: a
// direct edit of the master by the same user still stamps that user — the fix
// is scoped to the recompute's own write, not to `isSystem` writes in general.
//
// The harness boots the real `ObjectQLPlugin`, because the stamp under test is
// its `sys_stamp_audit_update` hook. What reaches the fake driver's store IS the
// stored row, so the store is the verdict.

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { ObjectKernel } from '@objectstack/core';
import { ObjectQLPlugin } from './plugin.js';
import { ObjectQL } from './engine.js';

const USER_A = 'u_owner_a';
const USER_B = 'u_child_writer_b';
/** An `updated_at` far in the past, so "the recompute refreshed it" is never a same-millisecond tie. */
const STALE_AT = '2000-01-01T00:00:00.000Z';

function makeDriver() {
const stores = new Map<string, Map<string, any>>();
const storeFor = (o: string) => {
let s = stores.get(o);
if (!s) { s = new Map(); stores.set(o, s); }
return s;
};
const matches = (row: any, where: any): boolean => {
if (!where || typeof where !== 'object') return true;
return Object.entries(where).every(([k, v]: [string, any]) => {
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
if ('$eq' in v) return row?.[k] === v.$eq;
if ('$in' in v) return Array.isArray(v.$in) && v.$in.includes(row?.[k]);
throw new Error(`fake driver: unsupported operator in ${JSON.stringify(v)}`);
}
return row?.[k] === v;
});
};
let n = 0;
const driver: any = {
name: 'rollup-audit', version: '0.0.0', supports: {},
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
async syncSchema() {},
async find(object: string, ast: any) {
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
return page.map((r) => ({ ...r }));
},
async findOne(object: string, ast: any) {
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
return null;
},
async create(object: string, data: Record<string, unknown>) {
n += 1;
const id = (data.id as string) ?? `r_${n}`;
const row = { ...data, id };
storeFor(object).set(id, row);
return { ...row };
},
async update(object: string, id: string, data: Record<string, unknown>) {
const s = storeFor(object);
const row = { ...s.get(id), ...data, id };
s.set(id, row);
return { ...row };
},
async delete(object: string, id: string) { return storeFor(object).delete(id); },
async count(object: string, ast: any) {
return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).length;
},
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
return Promise.all(rows.map((r) => this.create(object, r)));
},
async bulkUpdate() { return []; }, async bulkDelete() {},
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
async commit() {}, async rollback() {},
};
return { driver, storeFor };
}

describe('roll-up recompute stamps the master as a system write (updated_by = null)', () => {
let kernel: ObjectKernel;
let ql: ObjectQL;
let storeFor: ReturnType<typeof makeDriver>['storeFor'];

beforeEach(async () => {
kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false });
const d = makeDriver();
storeFor = d.storeFor;
await kernel.use({
name: 'rollup-audit-driver-plugin', type: 'driver', version: '1.0.0',
init: async (ctx: any) => { ctx.registerService('driver.rollup-audit', d.driver); },
} as any);
await kernel.use(new ObjectQLPlugin());
await kernel.bootstrap();
ql = kernel.getService<ObjectQL>('objectql');
// The audit family (`updated_by` / `updated_at` / …) is NOT declared: the
// registry injects it, exactly as on an authored business object.
ql.registry.registerObject({
name: 'contract',
label: 'Contract',
datasource: 'rollup-audit',
fields: {
name: { name: 'name', label: 'Name', type: 'text' },
invoiced: { name: 'invoiced', label: 'Invoiced', type: 'summary', summaryOperations: { object: 'invoice', field: 'amount', function: 'sum' } },
invoice_count: { name: 'invoice_count', label: 'Invoices', type: 'summary', summaryOperations: { object: 'invoice', function: 'count' } },
},
} as any, 'test', 'test');
ql.registry.registerObject({
name: 'invoice',
label: 'Invoice',
datasource: 'rollup-audit',
fields: {
amount: { name: 'amount', label: 'Amount', type: 'number' },
contract: { name: 'contract', label: 'Contract', type: 'master_detail', reference: 'contract' },
},
} as any, 'test', 'test');
});

afterEach(async () => {
if (kernel.getState() === 'running') await kernel.shutdown();
});

const as = (userId: string) => ({ context: { userId } as any });
const master = (id: string) => storeFor('contract').get(id);

/** User A creates and last edits the master; its `updated_at` is then aged so a refresh is visible. */
async function masterLastEditedByA(name: string): Promise<string> {
const c = await ql.insert('contract', { name }, as(USER_A));
await ql.update('contract', { id: c.id, name: `${name} (edited)` }, as(USER_A));
expect(master(c.id).updated_by).toBe(USER_A);
storeFor('contract').set(c.id, { ...master(c.id), updated_at: STALE_AT });
return c.id;
}

function expectSystemStamp(id: string) {
const row = master(id);
expect(row.updated_by).toBeNull();
expect(row.updated_by).not.toBe(USER_B);
expect(typeof row.updated_at).toBe('string');
expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT));
}

it('CONTROL: a direct edit of the master by B still stamps B', async () => {
const id = await masterLastEditedByA('CTR-CONTROL');
await ql.update('contract', { id, name: 'CTR-CONTROL (B)' }, as(USER_B));
expect(master(id).updated_by).toBe(USER_B);
expect(Date.parse(master(id).updated_at)).toBeGreaterThan(Date.parse(STALE_AT));
});

it('a child INSERT by B recomputes the master and stamps it as the system', async () => {
const id = await masterLastEditedByA('CTR-INSERT');
await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_B));
expect(master(id).invoiced).toBe(40);
expect(master(id).invoice_count).toBe(1);
expectSystemStamp(id);
});

it('a child UPDATE by B recomputes the master and stamps it as the system', async () => {
const id = await masterLastEditedByA('CTR-UPDATE');
const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A));
await ql.update('contract', { id, name: 'CTR-UPDATE (A again)' }, as(USER_A));
storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT });
expect(master(id).updated_by).toBe(USER_A);

await ql.update('invoice', { id: inv.id, amount: 55 }, as(USER_B));
expect(master(id).invoiced).toBe(55);
expectSystemStamp(id);
});

it('a child DELETE by B recomputes the master and stamps it as the system', async () => {
const id = await masterLastEditedByA('CTR-DELETE');
const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A));
await ql.update('contract', { id, name: 'CTR-DELETE (A again)' }, as(USER_A));
storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT });
expect(master(id).updated_by).toBe(USER_A);

await ql.delete('invoice', { where: { id: inv.id }, ...as(USER_B) } as any);
expect(master(id).invoiced).toBe(0);
expect(master(id).invoice_count).toBe(0);
expectSystemStamp(id);
});

it('a child RE-PARENT by B recomputes BOTH masters and stamps each as the system', async () => {
const from = await masterLastEditedByA('CTR-FROM');
const inv = await ql.insert('invoice', { contract: from, amount: 40 }, as(USER_A));
await ql.update('contract', { id: from, name: 'CTR-FROM (A again)' }, as(USER_A));
storeFor('contract').set(from, { ...master(from), updated_at: STALE_AT });
const to = await masterLastEditedByA('CTR-TO');

await ql.update('invoice', { id: inv.id, contract: to }, as(USER_B));
expect(master(from).invoiced).toBe(0);
expect(master(to).invoiced).toBe(40);
expectSystemStamp(from);
expectSystemStamp(to);
});
});
31 changes: 28 additions & 3 deletions packages/objectql/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type UnservableControlledByParentMaster,
} from './engine.js';
import { OWNERSHIP_QUEUE_SOURCE_SLOT, describeMissingOwnershipQueueService } from './assignment-rules.js';
import { SUMMARY_RECOMPUTE_WRITE } from './engine-summaries-and-expansion.js';
import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts';
import { assembleMetadataProtocol, isServedOverrideRowOf } from '@objectstack/metadata-protocol';
import { installedManifestsOf, isTenantAuthored, readLegacyOrganizationRows } from '@objectstack/metadata-core';
Expand Down Expand Up @@ -2099,8 +2100,22 @@ export class ObjectQLPlugin implements Plugin {
session: any,
isInsert: boolean,
seedReplay: boolean,
systemActor: boolean,
) => {
const now = stamp();
// A roll-up recompute's write onto the master (`SUMMARY_RECOMPUTE_WRITE`,
// set only by `recomputeSummaries`) is the SYSTEM's on the audit trail:
// `updated_by = null` (ADR-0118 D1) and a fresh `updated_at`, never the
// child writer the elevated context still carries as `userId`. Ruling
// recorded on the card, comment 6902001862 (「记为系统并刷新时间」). Update-only
// and unconditional on the session: a recompute triggered by a user-less
// write stamps the same null, and `preserveAudit` on the triggering
// import does not make a recompute historical.
if (systemActor && !isInsert) {
record.updated_at = now;
if (hasField(objectName, 'updated_by')) record.updated_by = null;
return;
}
// A "historical" import (#3493) reinstates the ORIGINAL timeline, so a
// client-supplied created_at/created_by/updated_at/updated_by is
// CLIENT-PREFERRED under `preserveAudit` — instead of being overwritten
Expand Down Expand Up @@ -2176,15 +2191,16 @@ export class ObjectQLPlugin implements Plugin {
session: any,
isInsert: boolean,
seedReplay: boolean,
systemActor = false,
) => {
if (Array.isArray(data)) {
for (const row of data) {
if (row && typeof row === 'object') {
applyToRecord(row as Record<string, any>, objectName, session, isInsert, seedReplay);
applyToRecord(row as Record<string, any>, objectName, session, isInsert, seedReplay, systemActor);
}
}
} else if (data && typeof data === 'object') {
applyToRecord(data as Record<string, any>, objectName, session, isInsert, seedReplay);
applyToRecord(data as Record<string, any>, objectName, session, isInsert, seedReplay, systemActor);
}
};

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

/**
* Whether this `beforeUpdate` is the master write of a roll-up recompute.
* Read from `input.options` (the caller's own options bag, as above) under
* the engine's symbol key, which only `recomputeSummaries` sets — see
* `SUMMARY_RECOMPUTE_WRITE` for why it is an option and not a context key.
*/
const isSummaryRecomputeWrite = (hookCtx: any): boolean =>
hookCtx?.input?.options?.[SUMMARY_RECOMPUTE_WRITE] === true;

const builtinHooks: any[] = [
{
name: 'sys_stamp_audit_insert',
Expand All @@ -2224,7 +2249,7 @@ export class ObjectQLPlugin implements Plugin {
handler: async (hookCtx: any) => {
if (hookCtx.input?.data) {
// `seedReplay` is moot here: the update stamp never writes `created_at`.
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false);
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false, false, isSummaryRecomputeWrite(hookCtx));
}
},
},
Expand Down
Loading
Loading