Skip to content

Commit 6f9a2e8

Browse files
test(plugin-security): security-parity pins for cascade delete across child-delete shapes (#33927)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbSUQWB2j9eHYsRcrCiq1X1C)_ Fixes #33782 Clause-②: no Metadata-protocol: none Precondition of #33699 (ruling 6893661036): merges before or together with it. ## 维护者速读 - 改了什么:只加了一个测试文件,钉住"级联删除"的四条安全不变量(被拒的子记录让整个级联回滚;不会少删;不会多删;审计、共享清理、对象级钩子对每个子记录各跑一次)。不改任何源码,不发布任何包。 - 为什么改:#33699 要把级联删除改成按批次的谓词删除(裁决 6893661036 F1),裁决要求这组对照测试先于或同时合入,确保换形状后安全行为不变。 - 风险与回滚:零运行时风险(纯测试);回滚即删除该文件。注意:这组测试在 #33699 当前分支头上会变红,原因见 Acceptance notes(共享中间件把 `id` 的 `$in` 集合当成单个 id 判权限),那是 #33699 合入前要解决的问题,不是本 PR 的问题。 - 先看:`packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts` 的第 1 组(拒绝与回滚)和第 3 组第二个用例(探测之后写入的子记录不被删除)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-security exec vitest run --maxWorkers=2 src/cascade-delete-security-parity.test.ts`,预期 8 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes One new test file, `packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts`, on a real kernel (`ObjectQLPlugin` over better-sqlite3, the real `AuditPlugin`, `SecurityPlugin` and `SharingServicePlugin`). It pins four invariants of a cascade delete, observed only from outside the engine (stored rows, audit ledger rows, record-share rows, what a registered hook was handed), so they hold whether children go one by-id delete each (today) or one predicate delete per batch (#33699, ruling 6893661036 F1): 1. **A refused child refuses the whole cascade with today's refusal, and deletes nothing.** Two refused shapes: a child the caller cannot read, and a child the caller reads and may edit but not delete (edit share, ADR-0111 D3). Today both answer `403 FORBIDDEN`; the edit-share case is held equal to the caller's own by-id delete of that child. Parent, siblings, the CBP note and the share all stay; no audit delete row. 2. **Never fewer rows.** A refused child never shrinks the cascade to the rows the caller's scope admits; a cascade the caller may complete (12 lines, 2 notes) leaves no probed child. 3. **Never more rows.** Rows under another parent or none stay; a child written after the probe (by a sibling's `beforeDelete`) is not deleted. 4. **Once per child.** One audit delete row per child, every child's record shares revoked by plugin-sharing's cleanup, and an object-less `beforeDelete`/`afterDelete` pair (service-storage's file-reference registration shape) sees each child exactly once per phase, a child two cascading relations reach included. Counts, never interleaving, so it stays green under F1's batch order. No source file, no changeset (`skip-changeset`: plugin-security publishes `dist`, built from `src/index.ts`; a `*.test.ts` is no entry). ## Tests <details><summary>plugin-security on head 9455c22 (merged main 63e47fe): 268/268 files, typecheck green</summary> - `pnpm --filter @objectstack/plugin-security exec vitest run --maxWorkers=2` under os-verify-lock: Test Files 268 passed (268), Tests 6689 passed, 45 skipped. The new file: 8/8. - `pnpm --filter @objectstack/plugin-security typecheck`: exit 0; the test layer (`tsconfig.test.json`, `src/**/*`) compiles with 0 ledgered errors. - Against #33699's objectql diff (cb2cafe) applied to this tree: 4 red, 4 green (see Acceptance notes). </details> <details><summary>Ablations (each mutation through scripts/ablation-replace.mjs, landed on disk, restored to the HEAD blob; objectql resolves to src in this package's vitest config, so no rebuild leg)</summary> - A1, skipping arm: the walk swallows a refused child's delete (`.catch(() => undefined)` on the by-id child delete). 4 red: both pins of invariant 1 and both refusal pins of invariant 2 (`expected { kind: 'landed' } to match object { kind: 'refused', ... }`). - A2, widening arm: the walk deletes children by the FK predicate (`where: { [fieldName]: id }, multi: true`) instead of by id. 5 red: the four refusal pins, and invariant 3's row written after the probe (`qa_ccp_line: ["m2_a_written_after_probe"]` expected, `[]` received). - A3, hookless arm: a cascaded child's by-id `beforeDelete`/`afterDelete` dispatch skipped. 3 red: invariant 4 (`expected { h1: 1 } to deeply equal { h1: 1, h1_by_alt: 1, ... }`), and the audit-row and hook-written-row pins that depend on child hooks running. - Two earlier A3 attempts did not reach the engine (a direct driver delete outside the unit timed out; a second spelling threw `this.buildDriverOptions is not a function`). Both were discarded as no-ops, not read as results. </details> ## Acceptance notes - **These pins are RED against #33699's branch head `cb2cafef` as it stands.** With its objectql diff applied to this tree, the four cascades that should land are refused `403 FORBIDDEN` (invariants 2 complete, 3 both, 4); the refusal pins stay green. Cause, measured: plugin-sharing's write middleware reads the target id through `inferTargetId` (`sharing-plugin.ts`), which returns `options.where.id` when it is any non-null value, so the batch's `where: { id: { $in: [...] } }` is gated as ONE by-id delete of the row `String({ $in })`, and `canDelete` denies it. The same refusal reproduces on `main` with no #33699 change: a member's `delete(LINE, { where: { id: { $in: ['own_row'] } }, multi: true })` on a private-OWD object it owns answers `403 FORBIDDEN` from `sharingMiddleware`. The engine contract declares that shape a multi delete (`engine-delete-dispatch.ts`, case "multi alongside an $in id set" → `multi`). - With a scratch fix that keeps an operator object out of the by-id gate (not part of this PR), the #33699 diff passes all 8 pins: its narrowed-batch fallback refuses and rolls back as today, and the hook, audit and share-cleanup counts hold. - Today's refusal of a cascaded child is sharing's `403 FORBIDDEN`, not plugin-security's `PERMISSION_DENIED`, for both refused shapes on a sharing-enforced child. - Not wired: the real service-storage file-reference hooks (`@objectstack/service-storage` is not a dependency of plugin-security; adding it is outside this card's surface). The object-less hook pair has its registration shape. ## Verification Final-head readings (tests, typecheck, gate families with exit codes) are in the os-dev report on #33782. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5fe7bfa commit 6f9a2e8

1 file changed

Lines changed: 393 additions & 0 deletions

File tree

Lines changed: 393 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,393 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Security parity for a cascade delete, whatever SHAPE the engine deletes a
5+
* parent's dependents in: one by-id `delete()` per child (the path this suite
6+
* was written against), or one predicate `delete()` per batch of children
7+
* (ruling 6893661036, option F1: every child's before-hooks, one set delete,
8+
* then the after-hooks). The four invariants, from ruling 6893104201 point
9+
* (2) and the preconditions of ruling 6893661036:
10+
*
11+
* 1. **A refused child refuses the whole cascade.** A child the caller may
12+
* not delete (one it cannot read, and one it reads and may edit but may
13+
* not delete) makes the parent's delete answer the refusal it answers
14+
* today, and no row is deleted: not the parent, not a sibling the caller
15+
* owns, not a child of another relation.
16+
* 2. **Never fewer rows.** A cascade either deletes every child it probed or
17+
* none: a refused child never shrinks the set to the rows the caller's
18+
* scope admits, and a cascade the caller may complete leaves no probed
19+
* child behind.
20+
* 3. **Never more rows.** The cascade deletes the children it probed and
21+
* nothing else: a row of the same object under another parent, or under
22+
* none, stays, and so does a child written AFTER the probe (here by a
23+
* sibling's own `beforeDelete`), which a predicate-shaped scope
24+
* (`DELETE ... WHERE fk = ?`) would reach and an id-shaped one does not.
25+
* 4. **Each child's delete-side work runs once per child.** The audit ledger
26+
* records one delete per child, every record share on a child is revoked
27+
* (plugin-sharing's cleanup), and an object-less `beforeDelete` /
28+
* `afterDelete` pair (the registration shape of service-storage's
29+
* file-reference release) sees each child exactly once in each phase,
30+
* including a child two relations reach. Counts, never interleaving: under
31+
* F1 the before-hooks of a batch all run before its after-hooks.
32+
*
33+
* Everything is observed from outside the engine: rows left in the store,
34+
* ledger rows, share rows, and what a registered hook was handed. No engine
35+
* internal is named, so the pins hold across a rewrite of the cascade walk.
36+
*
37+
* Real stack: an `ObjectKernel` with `ObjectQLPlugin` over better-sqlite3,
38+
* the real `AuditPlugin`, `SecurityPlugin` and `SharingServicePlugin`. The
39+
* caller is a member holding one permission set that grants full CRUD on the
40+
* three objects, so every refusal below is row-level: record sharing's
41+
* delete gate, never an object permission.
42+
*/
43+
44+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
45+
import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core';
46+
import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql';
47+
import { SqlDriver } from '@objectstack/driver-sql';
48+
import { AuditPlugin } from '@objectstack/plugin-audit';
49+
import { SharingServicePlugin } from '@objectstack/plugin-sharing';
50+
import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity';
51+
import { PermissionSetSchema } from '@objectstack/spec/security';
52+
import { SecurityPlugin } from './security-plugin.js';
53+
import { defaultPermissionSets } from './objects/default-permission-sets.js';
54+
55+
const ORG = 'org_ccp';
56+
const ME = 'usr_ccp_me';
57+
const OTHER = 'usr_ccp_other';
58+
59+
/** The parent: open to every member, so its own delete is never the refusal. */
60+
const ORDER = 'qa_ccp_order';
61+
/** A record-shared child, owner-scoped (`private`), reached by two cascading lookups. */
62+
const LINE = 'qa_ccp_line';
63+
/** A `controlled_by_parent` child (ADR-0055): its write authority is the order's. */
64+
const NOTE = 'qa_ccp_note';
65+
const FIXTURE_OBJECTS: readonly string[] = [ORDER, LINE, NOTE];
66+
67+
const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } as const;
68+
const WRITER = PermissionSetSchema.parse({
69+
name: 'qa_ccp_writer',
70+
objects: { [ORDER]: CRUD, [LINE]: CRUD, [NOTE]: CRUD },
71+
});
72+
73+
const SYSTEM = { isSystem: true, tenantId: ORG } as const;
74+
const SYS = { context: SYSTEM } as never;
75+
const asCaller = () => ({ userId: ME, tenantId: ORG, positions: [], permissions: [WRITER.name] });
76+
77+
type Outcome = { kind: 'landed' } | { kind: 'refused'; code?: string; status?: number; message: string };
78+
const outcomeOf = (p: Promise<unknown>): Promise<Outcome> =>
79+
p.then(
80+
() => ({ kind: 'landed' as const }),
81+
(e: { code?: unknown; status?: unknown; statusCode?: unknown; message?: unknown } | null) => {
82+
const status = e?.statusCode ?? e?.status;
83+
return {
84+
kind: 'refused' as const,
85+
code: e?.code == null ? undefined : String(e.code),
86+
status: status == null ? undefined : Number(status),
87+
message: String(e?.message),
88+
};
89+
},
90+
);
91+
92+
function sqliteDriverPlugin(): Plugin {
93+
return {
94+
name: 'test.driver.sqlite',
95+
type: 'standard',
96+
version: '1.0.0',
97+
async init(ctx: PluginContext) {
98+
ctx.registerService(
99+
'driver.default',
100+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
101+
);
102+
},
103+
};
104+
}
105+
106+
function objectsPlugin(): Plugin {
107+
return {
108+
name: 'test.objects',
109+
type: 'standard',
110+
version: '1.0.0',
111+
dependencies: ['com.objectstack.engine.objectql'],
112+
async init(ctx: PluginContext) {
113+
ctx.getService<{ register(m: unknown): unknown }>('manifest').register({
114+
id: 'test.cascade-delete-security-parity',
115+
namespace: 'qa_ccp',
116+
version: '1.0.0',
117+
type: 'plugin',
118+
name: 'Cascade delete security parity',
119+
objects: [
120+
SysUser, SysMember, SysOrganization,
121+
{ name: ORDER, label: 'Order', sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' } } },
122+
{
123+
name: LINE,
124+
label: 'Line',
125+
sharingModel: 'private',
126+
fields: {
127+
name: { type: 'text', label: 'Name' },
128+
owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' },
129+
order: { type: 'lookup', reference: ORDER, deleteBehavior: 'cascade', label: 'Order' },
130+
alt_order: { type: 'lookup', reference: ORDER, deleteBehavior: 'cascade', label: 'Alternate order' },
131+
},
132+
},
133+
{
134+
name: NOTE,
135+
label: 'Note',
136+
sharingModel: 'controlled_by_parent',
137+
fields: {
138+
name: { type: 'text', label: 'Name' },
139+
order: { type: 'master_detail', reference: ORDER, required: true, deleteBehavior: 'cascade', label: 'Order' },
140+
},
141+
},
142+
],
143+
});
144+
},
145+
};
146+
}
147+
148+
interface Seen { phase: 'before' | 'after'; object: string; id: string }
149+
interface HookCtx { object?: string; input?: { id?: unknown }; previous?: { order?: unknown } }
150+
151+
describe('cascade delete: security parity between id-shaped and predicate-shaped child deletes', () => {
152+
let kernel: ObjectKernel;
153+
let ql: ObjectQL;
154+
/** Every delete dispatch on a fixture object, as an object-less hook pair sees it. */
155+
const seen: Seen[] = [];
156+
/** Armed with a line id: that line's `beforeDelete` writes a new sibling under the same order. */
157+
let spawnFrom: string | undefined;
158+
159+
beforeAll(async () => {
160+
kernel = new ObjectKernel({ logger: { level: 'silent' } } as never);
161+
await kernel.use(sqliteDriverPlugin());
162+
await kernel.use(new ObjectQLPlugin());
163+
await kernel.use(objectsPlugin());
164+
await kernel.use(new AuditPlugin());
165+
await kernel.use(new SecurityPlugin({
166+
defaultPermissionSets: [...defaultPermissionSets, WRITER],
167+
fallbackPermissionSet: 'member_default',
168+
}));
169+
await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false }));
170+
await kernel.bootstrap();
171+
ql = kernel.getService<ObjectQL>('objectql');
172+
173+
await ql.insert('sys_organization', { id: ORG, name: 'Acme', slug: 'acme' }, SYS);
174+
for (const userId of [ME, OTHER]) {
175+
await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@acme.test`, email_verified: true }, SYS);
176+
await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role: 'member' }, SYS);
177+
}
178+
179+
// Object-less, as service-storage registers its file-reference release:
180+
// dispatched for every object, filtered here to the fixture's.
181+
const record = (phase: Seen['phase']) => async (hookCtx: HookCtx) => {
182+
const object = String(hookCtx?.object);
183+
if (!FIXTURE_OBJECTS.includes(object)) return;
184+
seen.push({ phase, object, id: String(hookCtx?.input?.id) });
185+
};
186+
ql.registerHook('beforeDelete', record('before') as never, { packageId: 'qa.cascade-parity.object-less' } as never);
187+
ql.registerHook('afterDelete', record('after') as never, { packageId: 'qa.cascade-parity.object-less' } as never);
188+
// A child written during the cascade, after the walk probed the order's lines.
189+
const spawn = async (hookCtx: HookCtx) => {
190+
const id = String(hookCtx?.input?.id);
191+
if (spawnFrom === undefined || id !== spawnFrom) return;
192+
spawnFrom = undefined;
193+
await ql.insert(LINE, { id: `${id}_written_after_probe`, owner_id: ME, order: hookCtx?.previous?.order }, SYS);
194+
};
195+
ql.registerHook('beforeDelete', spawn as never, { object: LINE, packageId: 'qa.cascade-parity.spawn' } as never);
196+
}, 120_000);
197+
198+
afterAll(async () => {
199+
if (kernel) await Promise.race([kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
200+
}, 30_000);
201+
202+
/** The ids stored under `prefix`, per fixture object, as a system read sees them. */
203+
const stored = async (prefix: string) => {
204+
const out: Record<string, string[]> = {};
205+
for (const object of FIXTURE_OBJECTS) {
206+
const rows = (await ql.find(object, { context: SYSTEM } as never)) as Array<{ id: string }>;
207+
out[object] = rows.map((r) => String(r.id)).filter((id) => id.startsWith(prefix)).sort();
208+
}
209+
return out;
210+
};
211+
/** The record ids the audit ledger holds a `delete` row for, under `prefix`. */
212+
const auditedDeletes = async (prefix: string) => {
213+
const rows = (await ql.find('sys_audit_log', { where: { action: 'delete' }, context: SYSTEM } as never)) as
214+
Array<{ record_id?: string }>;
215+
return rows.map((r) => String(r.record_id)).filter((id) => id.startsWith(prefix)).sort();
216+
};
217+
/** The record ids still carrying a record share, under `prefix`. */
218+
const sharedRecords = async (prefix: string) => {
219+
const rows = (await ql.find('sys_record_share', { context: SYSTEM } as never)) as Array<{ record_id?: string }>;
220+
return rows.map((r) => String(r.record_id)).filter((id) => id.startsWith(prefix)).sort();
221+
};
222+
const share = (recordId: string, recipient: string, accessLevel: 'read' | 'edit') =>
223+
ql.insert('sys_record_share', {
224+
object_name: LINE, record_id: recordId, recipient_type: 'user', recipient_id: recipient,
225+
access_level: accessLevel, source: 'manual',
226+
}, SYS);
227+
const deleteOrder = (id: string) => outcomeOf(ql.delete(ORDER, { where: { id }, context: asCaller() } as never));
228+
229+
/**
230+
* One order with three lines and a note. The middle line is the caller's
231+
* own unless `refused` names how it is not deletable: owned by someone
232+
* else and not shared (unreadable), or owned by someone else and shared to
233+
* the caller at `edit` (read and update, never delete: ADR-0111 D3).
234+
*/
235+
const seedOrder = async (prefix: string, refused?: 'unreadable' | 'edit-shared') => {
236+
await ql.insert(ORDER, { id: prefix, name: prefix }, SYS);
237+
await ql.insert(LINE, [
238+
{ id: `${prefix}_a`, owner_id: ME, order: prefix },
239+
{ id: `${prefix}_b`, owner_id: refused ? OTHER : ME, order: prefix },
240+
{ id: `${prefix}_c`, owner_id: ME, order: prefix },
241+
], SYS);
242+
await ql.insert(NOTE, { id: `${prefix}_n`, order: prefix }, SYS);
243+
if (refused === 'edit-shared') await share(`${prefix}_b`, ME, 'edit');
244+
return {
245+
[ORDER]: [prefix],
246+
[LINE]: [`${prefix}_a`, `${prefix}_b`, `${prefix}_c`],
247+
[NOTE]: [`${prefix}_n`],
248+
} as Record<string, string[]>;
249+
};
250+
251+
describe('1. a child the caller may not delete refuses the whole cascade, with today\'s refusal, and deletes nothing', () => {
252+
it('a child the caller cannot read: 403 FORBIDDEN, and the order, every line and the note stay', async () => {
253+
const all = await seedOrder('r1', 'unreadable');
254+
// The precondition, off the read door: the caller does not see it.
255+
expect(await ql.findOne(LINE, { where: { id: 'r1_b' }, context: asCaller() } as never)).toBeNull();
256+
257+
const got = await deleteOrder('r1');
258+
259+
expect(got).toMatchObject({ kind: 'refused', code: 'FORBIDDEN', status: 403 });
260+
// The refusal names no row the caller was never shown.
261+
expect(got.kind === 'refused' && got.message).not.toContain('r1_b');
262+
expect(await stored('r1')).toEqual(all);
263+
expect(await auditedDeletes('r1'), 'a rolled-back delete leaves no ledger row').toEqual([]);
264+
});
265+
266+
it('a child the caller reads and may edit but not delete: the refusal its own delete of that child gets, and nothing is deleted', async () => {
267+
const all = await seedOrder('r2', 'edit-shared');
268+
expect(await ql.findOne(LINE, { where: { id: 'r2_b' }, context: asCaller() } as never)).toMatchObject({ id: 'r2_b' });
269+
// Today's refusal, measured off the caller's own by-id delete of that child.
270+
const own = await outcomeOf(ql.delete(LINE, { where: { id: 'r2_b' }, context: asCaller() } as never));
271+
expect(own).toMatchObject({ kind: 'refused', code: 'FORBIDDEN', status: 403 });
272+
273+
const got = await deleteOrder('r2');
274+
275+
expect(got).toEqual(own);
276+
expect(await stored('r2')).toEqual(all);
277+
expect(await sharedRecords('r2'), 'the share outlives the refused delete').toEqual(['r2_b']);
278+
expect(await auditedDeletes('r2')).toEqual([]);
279+
});
280+
});
281+
282+
describe('2. never fewer rows: a cascade deletes every child it probed, or none', () => {
283+
for (const refused of ['unreadable', 'edit-shared'] as const) {
284+
it(`a refused child (${refused}) never shrinks the cascade to the rows the caller's scope admits`, async () => {
285+
const prefix = `f_${refused === 'unreadable' ? 'u' : 'e'}`;
286+
await seedOrder(prefix, refused);
287+
// The rows a narrowed delete would take: everything the caller may delete.
288+
const deletable = [`${prefix}_a`, `${prefix}_c`];
289+
290+
expect(await deleteOrder(prefix)).toMatchObject({ kind: 'refused', status: 403 });
291+
292+
const left = await stored(prefix);
293+
expect(left[ORDER]).toEqual([prefix]);
294+
expect(left[LINE]).toEqual(expect.arrayContaining(deletable));
295+
expect(left[LINE]).toHaveLength(3);
296+
expect(left[NOTE]).toEqual([`${prefix}_n`]);
297+
});
298+
}
299+
300+
it('a cascade the caller may complete leaves none of the children its probe found', async () => {
301+
const prefix = 'f_all';
302+
await ql.insert(ORDER, { id: prefix }, SYS);
303+
const lines = Array.from({ length: 12 }, (_, i) => ({ id: `${prefix}_l${String(i).padStart(2, '0')}`, owner_id: ME, order: prefix }));
304+
await ql.insert(LINE, lines, SYS);
305+
await ql.insert(NOTE, [{ id: `${prefix}_n1`, order: prefix }, { id: `${prefix}_n2`, order: prefix }], SYS);
306+
const before = await stored(prefix);
307+
expect(before[LINE]).toHaveLength(12);
308+
309+
expect(await deleteOrder(prefix)).toEqual({ kind: 'landed' });
310+
311+
expect(await stored(prefix)).toEqual({ [ORDER]: [], [LINE]: [], [NOTE]: [] });
312+
expect(await auditedDeletes(prefix)).toEqual([...before[ORDER], ...before[LINE], ...before[NOTE]].sort());
313+
});
314+
});
315+
316+
describe('3. never more rows: the cascade deletes the children it probed and nothing else', () => {
317+
it('rows of the child objects under another order, or under none, stay', async () => {
318+
const prefix = 'm1';
319+
await ql.insert(ORDER, [{ id: prefix }, { id: `${prefix}_other` }], SYS);
320+
await ql.insert(LINE, [
321+
{ id: `${prefix}_mine`, owner_id: ME, order: prefix },
322+
{ id: `${prefix}_other_line`, owner_id: ME, order: `${prefix}_other` },
323+
{ id: `${prefix}_orphan_line`, owner_id: ME },
324+
], SYS);
325+
await ql.insert(NOTE, [{ id: `${prefix}_note`, order: prefix }, { id: `${prefix}_other_note`, order: `${prefix}_other` }], SYS);
326+
327+
expect(await deleteOrder(prefix)).toEqual({ kind: 'landed' });
328+
329+
expect(await stored(prefix)).toEqual({
330+
[ORDER]: [`${prefix}_other`],
331+
[LINE]: [`${prefix}_orphan_line`, `${prefix}_other_line`],
332+
[NOTE]: [`${prefix}_other_note`],
333+
});
334+
});
335+
336+
it('a child written after the probe (by a sibling\'s beforeDelete) is not deleted by this cascade', async () => {
337+
const prefix = 'm2';
338+
await ql.insert(ORDER, { id: prefix }, SYS);
339+
await ql.insert(LINE, [{ id: `${prefix}_a`, owner_id: ME, order: prefix }, { id: `${prefix}_b`, owner_id: ME, order: prefix }], SYS);
340+
spawnFrom = `${prefix}_a`;
341+
342+
try {
343+
expect(await deleteOrder(prefix)).toEqual({ kind: 'landed' });
344+
} finally {
345+
spawnFrom = undefined;
346+
}
347+
348+
// The hook ran (its row exists), and the cascade deleted only what it probed.
349+
expect(await stored(prefix)).toEqual({ [ORDER]: [], [LINE]: [`${prefix}_a_written_after_probe`], [NOTE]: [] });
350+
});
351+
});
352+
353+
describe('4. each child\'s delete-side work runs once per child', () => {
354+
it('one audit delete row, every share revoked, and each object-less hook phase once, per child, a child two relations reach included', async () => {
355+
const prefix = 'h1';
356+
await ql.insert(ORDER, { id: prefix }, SYS);
357+
await ql.insert(LINE, [
358+
{ id: `${prefix}_by_order`, owner_id: ME, order: prefix },
359+
{ id: `${prefix}_by_both`, owner_id: ME, order: prefix, alt_order: prefix },
360+
{ id: `${prefix}_by_alt`, owner_id: ME, alt_order: prefix },
361+
], SYS);
362+
await ql.insert(NOTE, [{ id: `${prefix}_n1`, order: prefix }, { id: `${prefix}_n2`, order: prefix }], SYS);
363+
const lines = [`${prefix}_by_alt`, `${prefix}_by_both`, `${prefix}_by_order`];
364+
const children = [...lines, `${prefix}_n1`, `${prefix}_n2`];
365+
for (const id of lines) await share(id, OTHER, 'read');
366+
expect(await sharedRecords(prefix)).toEqual(lines);
367+
seen.length = 0;
368+
369+
expect(await deleteOrder(prefix)).toEqual({ kind: 'landed' });
370+
371+
const count = (phase: Seen['phase']) => {
372+
const byId: Record<string, number> = {};
373+
for (const s of seen) if (s.phase === phase && s.id.startsWith(prefix)) byId[s.id] = (byId[s.id] ?? 0) + 1;
374+
return byId;
375+
};
376+
const once = Object.fromEntries([prefix, ...children].map((id) => [id, 1]));
377+
// One object, so a failure shows every face at once.
378+
expect({
379+
objectLessBefore: count('before'),
380+
objectLessAfter: count('after'),
381+
auditedDeletes: await auditedDeletes(prefix),
382+
sharesLeft: await sharedRecords(prefix),
383+
stored: await stored(prefix),
384+
}).toEqual({
385+
objectLessBefore: once,
386+
objectLessAfter: once,
387+
auditedDeletes: [prefix, ...children].sort(),
388+
sharesLeft: [],
389+
stored: { [ORDER]: [], [LINE]: [], [NOTE]: [] },
390+
});
391+
});
392+
});
393+
});

0 commit comments

Comments
 (0)