Skip to content

Commit 1e8d229

Browse files
committed
test(service-automation): pin the predicate delete walk's probe count per batch (red first)
Claude-Session: https://claude.ai/code/session_01FEkQ5ktxGoJfsedLmkFjdk Co-authored-by: Claude <noreply@anthropic.com>
1 parent acc9c57 commit 1e8d229

1 file changed

Lines changed: 229 additions & 0 deletions

File tree

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A `delete_record` node with `multi: true` walks the rows its filter matches
5+
* as ONE set: each relation pointing at the deleted object is asked once per
6+
* batch of matched ids, not once per matched row, and every row still gets
7+
* the outcome its declared `deleteBehavior` gives it.
8+
*
9+
* The engine's predicate arm used to run the by-id walk once per matched id,
10+
* so its cost was matched rows times referencing relations: deleting 1,001
11+
* rows of an object three relations point at made 4,004 dependents probes and
12+
* took about 1.7 s on SQLite, where the same delete took about 0.1 s before
13+
* the walk existed. The walk now takes a root set; a by-id delete is a set of
14+
* one.
15+
*
16+
* Composition: the real stack `delete-record-predicate-referential-walk`
17+
* boots (`ObjectKernel`, `ObjectQLPlugin`, `driver-sql` on better-sqlite3
18+
* `:memory:`, the real `delete_record` executor). Driver calls are counted on
19+
* the driver itself; rows are read out of the driver, not through the engine.
20+
*/
21+
22+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
23+
import type { FilterCondition } from '@objectstack/spec/data';
24+
import { ObjectKernel } from '@objectstack/core';
25+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
26+
import { SqlDriver } from '@objectstack/driver-sql';
27+
import { AutomationServicePlugin } from '../plugin.js';
28+
import { AutomationEngine } from '../engine.js';
29+
import { registerCrudNodes } from './crud-nodes.js';
30+
import { installDefaultOrganization } from '../default-organization.testkit.js';
31+
32+
const SYS = { isSystem: true } as const;
33+
34+
/** Matched rows: more than two of the walk's 500-id batches. */
35+
const N = 1_001;
36+
37+
const PARENT = {
38+
name: 'pin_batch_parent',
39+
label: 'Pin batch parent',
40+
fields: {
41+
title: { name: 'title', label: 'Title', type: 'text' },
42+
grp: { name: 'grp', label: 'Group', type: 'text' },
43+
},
44+
};
45+
/** The three relations of the rest cap test: a master_detail, a lookup and a multiple lookup. */
46+
const DETAIL = {
47+
name: 'pin_batch_detail',
48+
label: 'Pin batch detail',
49+
fields: {
50+
title: { name: 'title', label: 'Title', type: 'text' },
51+
parent: { name: 'parent', label: 'Parent', type: 'master_detail', reference: 'pin_batch_parent' },
52+
},
53+
};
54+
const LINK = {
55+
name: 'pin_batch_link',
56+
label: 'Pin batch link',
57+
fields: {
58+
title: { name: 'title', label: 'Title', type: 'text' },
59+
parent: { name: 'parent', label: 'Parent', type: 'lookup', reference: 'pin_batch_parent' },
60+
},
61+
};
62+
const TAGS = {
63+
name: 'pin_batch_tags',
64+
label: 'Pin batch tags',
65+
fields: {
66+
title: { name: 'title', label: 'Title', type: 'text' },
67+
parents: { name: 'parents', label: 'Parents', type: 'lookup', reference: 'pin_batch_parent', multiple: true },
68+
},
69+
};
70+
71+
/** A second parent with a REQUIRED multiple lookup pointing at it: the per-row escalation. */
72+
const HOLDER = {
73+
name: 'pin_batch_holder',
74+
label: 'Pin batch holder',
75+
fields: {
76+
title: { name: 'title', label: 'Title', type: 'text' },
77+
grp: { name: 'grp', label: 'Group', type: 'text' },
78+
},
79+
};
80+
const MEMBERS = {
81+
name: 'pin_batch_members',
82+
label: 'Pin batch members',
83+
fields: {
84+
title: { name: 'title', label: 'Title', type: 'text' },
85+
holders: { name: 'holders', label: 'Holders', type: 'lookup', reference: 'pin_batch_holder', multiple: true, required: true },
86+
},
87+
};
88+
89+
function makeLogger(): any {
90+
const l: any = { info() {}, warn() {}, error() {}, debug() {}, trace() {}, fatal() {} };
91+
l.child = () => l;
92+
return l;
93+
}
94+
95+
type Executor = { execute: (node: any, variables: Map<string, unknown>, context: any) => Promise<any> };
96+
97+
describe('[#27004] a multi delete_record walks its matched rows as a set', () => {
98+
let kernel: ObjectKernel;
99+
let ql: ObjectQL;
100+
let driver: SqlDriver;
101+
let deleteRecord: Executor;
102+
103+
beforeAll(async () => {
104+
kernel = new ObjectKernel({ logger: { level: 'fatal' } });
105+
await kernel.use(new ObjectQLPlugin());
106+
await kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' }));
107+
await kernel.bootstrap();
108+
ql = kernel.getService<ObjectQL>('objectql');
109+
110+
driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
111+
await driver.connect();
112+
ql.registerDriver(driver, true);
113+
for (const o of [PARENT, DETAIL, LINK, TAGS, HOLDER, MEMBERS]) ql.registry.registerObject(o as any, 'pin-batch-delete', 'pin-batch-delete');
114+
await ql.syncSchemas();
115+
await installDefaultOrganization(ql);
116+
117+
const executors = new Map<string, Executor>();
118+
const capture = new Proxy(new AutomationEngine(makeLogger()), {
119+
get(target, key, receiver) {
120+
if (key === 'registerNodeExecutor') return (e: any) => { executors.set(e.type, e); };
121+
return Reflect.get(target, key, receiver);
122+
},
123+
});
124+
registerCrudNodes(capture as AutomationEngine, { logger: makeLogger(), getService: (n: string) => (n === 'data' ? ql : undefined) } as any);
125+
deleteRecord = executors.get('delete_record')!;
126+
expect(deleteRecord, 'control: the delete_record executor was registered').toBeDefined();
127+
}, 60_000);
128+
129+
afterAll(async () => {
130+
try { await kernel?.shutdown(); } catch { /* best-effort teardown */ }
131+
});
132+
133+
const insert = async (object: string, data: Record<string, unknown>): Promise<string> =>
134+
((await ql.insert(object, data, { context: SYS })) as any).id;
135+
/** `count` rows of `object` in one group, inserted 100 at a time; their ids in order. */
136+
const insertMany = async (object: string, grp: string, count: number): Promise<string[]> => {
137+
const ids: string[] = [];
138+
for (let i = 0; i < count; i += 100) {
139+
const batch = Array.from({ length: Math.min(100, count - i) }, (_, j) => ({ id: `${grp}_${i + j}`, title: `${grp} ${i + j}`, grp }));
140+
await ql.insert(object, batch, { context: SYS });
141+
ids.push(...batch.map((r) => r.id));
142+
}
143+
return ids;
144+
};
145+
/** Rows of `object`, read from the driver with no engine in between. */
146+
const rows = async (object: string, where: FilterCondition = {}): Promise<any[]> =>
147+
(await driver.find(object, { where })) as any[];
148+
const sweep = (objectName: string, grp: string) => deleteRecord.execute(
149+
{ id: 'sweep', type: 'delete_record', config: { objectName, filter: { grp }, multi: true } },
150+
new Map(),
151+
{ runAs: 'system', flowName: 'pin_batch_sweep' },
152+
);
153+
154+
it('asks each referencing relation once per 500 matched ids, not once per matched row', async () => {
155+
await insertMany(PARENT.name, 'counted', N);
156+
const finds = vi.spyOn(driver, 'find');
157+
const deletes = vi.spyOn(driver, 'deleteMany');
158+
try {
159+
const res: any = await sweep(PARENT.name, 'counted');
160+
expect(res.success, JSON.stringify(res)).toBe(true);
161+
const probesOf = (object: string) => finds.mock.calls.filter((call) => call[0] === object).length;
162+
// ⌈1,001 / 500⌉ = 3 batches. The master_detail is read twice per batch
163+
// (the cascade set is collected, then walked); the lookup and the
164+
// multiple lookup once each. Per row it was 2,002, 1,001 and 1,001.
165+
expect({ detail: probesOf(DETAIL.name), link: probesOf(LINK.name), tags: probesOf(TAGS.name) })
166+
.toEqual({ detail: 6, link: 3, tags: 3 });
167+
expect(deletes.mock.calls.filter((call) => call[0] === PARENT.name)).toHaveLength(3);
168+
} finally {
169+
finds.mockRestore();
170+
deletes.mockRestore();
171+
}
172+
expect(await rows(PARENT.name, { grp: 'counted' })).toEqual([]);
173+
});
174+
175+
it('every matched row still gets its own outcome, across batch boundaries', async () => {
176+
const ids = await insertMany(PARENT.name, 'mixed', N);
177+
const kept = await insert(PARENT.name, { title: 'k', grp: 'kept' });
178+
// Details of rows in the first and the second batch, and of the kept row.
179+
await insert(DETAIL.name, { title: 'd-0', parent: ids[0] });
180+
await insert(DETAIL.name, { title: 'd-700', parent: ids[700] });
181+
const keptDetail = await insert(DETAIL.name, { title: 'd-k', parent: kept });
182+
const l600 = await insert(LINK.name, { title: 'l-600', parent: ids[600] });
183+
const l1000 = await insert(LINK.name, { title: 'l-1000', parent: ids[1000] });
184+
const keptLink = await insert(LINK.name, { title: 'l-k', parent: kept });
185+
// One set spanning two batches and the kept row; one emptied by the delete.
186+
const spanning = await insert(TAGS.name, { title: 't-span', parents: [ids[1], ids[900], kept] });
187+
const emptied = await insert(TAGS.name, { title: 't-empty', parents: [ids[2], ids[3]] });
188+
189+
const res: any = await sweep(PARENT.name, 'mixed');
190+
expect(res.success, JSON.stringify(res)).toBe(true);
191+
192+
expect(await rows(PARENT.name, { grp: 'mixed' })).toEqual([]);
193+
expect((await rows(PARENT.name, { grp: 'kept' })).map((r) => r.id)).toEqual([kept]);
194+
// master_detail: cascaded on both sides of the batch boundary.
195+
expect((await rows(DETAIL.name)).map((r) => r.id)).toEqual([keptDetail]);
196+
// set_null lookup: cleared, the kept row's untouched.
197+
const links = new Map((await rows(LINK.name)).map((r) => [r.id, r.parent ?? null]));
198+
expect([links.get(l600), links.get(l1000), links.get(keptLink)]).toEqual([null, null, kept]);
199+
// set_null multiple lookup: every deleted member removed, the kept one
200+
// stays, and an emptied set is written as `[]`, never `null`.
201+
const tags = new Map((await rows(TAGS.name)).map((r) => [r.id, r.parents]));
202+
expect(tags.get(spanning)).toEqual([kept]);
203+
expect(tags.get(emptied)).toEqual([]);
204+
});
205+
206+
it('a required multiple lookup emptied only by the whole set refuses, naming the row whose removal empties it', async () => {
207+
const ids = await insertMany(HOLDER.name, 'held', 600);
208+
const other = await insert(HOLDER.name, { title: 'o', grp: 'other' });
209+
// Keeps `other`: takes the member removal, refuses nothing.
210+
await insert(MEMBERS.name, { title: 'm-keeps', holders: [ids[10], other] });
211+
// Every member is matched, one in each batch: emptied by the delete.
212+
await insert(MEMBERS.name, { title: 'm-empties', holders: [ids[20], ids[550]] });
213+
214+
const node: any = await sweep(HOLDER.name, 'held');
215+
expect(node.success).toBe(false);
216+
expect(node.innerRefusal).toMatchObject({ code: 'DELETE_RESTRICTED' });
217+
// The engine's own error, for its structured half: the count is the rows
218+
// the removal would empty, and the record named is the one whose removal
219+
// empties the set, as when the rows were walked one by one.
220+
const err: any = await ql.delete(HOLDER.name, { where: { grp: 'held' }, multi: true, context: SYS }).catch((e: unknown) => e);
221+
expect(err).toMatchObject({ code: 'DELETE_RESTRICTED', status: 409, dependentObject: MEMBERS.name, dependentCount: 1 });
222+
expect(err.developerMessage).toContain(`Cannot delete ${HOLDER.name} (${ids[550]}): 1 dependent ${MEMBERS.name} record(s)`);
223+
// One unit of work: nothing deleted, nothing cleared.
224+
expect(await rows(HOLDER.name, { grp: 'held' })).toHaveLength(600);
225+
const members = new Map((await rows(MEMBERS.name)).map((r) => [r.title, r.holders]));
226+
expect(members.get('m-keeps')).toEqual([ids[10], other]);
227+
expect(members.get('m-empties')).toEqual([ids[20], ids[550]]);
228+
});
229+
});

0 commit comments

Comments
 (0)