Skip to content

Commit 6a07be6

Browse files
committed
fix(objectql,plugin-audit): keep predicate deletes, platform objects and the bin's own bookkeeping out of the recycle bin and the ledger
The lifecycle sweep reaps each row with `where: { id }, multi: true`, which the engine routes as a by-id delete, so a business object that declares a lifecycle would have entered the bin on every reap. The capture now opens only when the caller did not ask for `multi: true`. The bin also leaves out every platform namespace (sys_, cloud_, ai_), not only sys_. plugin-audit's generic writer would have copied each entry, snapshot and internal columns included, into sys_audit_log and sys_activity on its reap, on the set_null of its deleted_by and on an organization delete's cascade. sys_recycle_bin joins SKIP_OBJECTS beside the other engine-owned plumbing. Pins: a predicate-shaped by-id delete and a lifecycle sweep of a business object write no entry; cloud_ and ai_ objects write none; an organization delete removes its entries without being refused by them; a reap and an update of an entry write no ledger row while a business delete still does. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4czFGLnXKQd6cQjv3Pr
1 parent 819b02f commit 6a07be6

8 files changed

Lines changed: 174 additions & 24 deletions

File tree

‎.changeset/30237-recycle-bin-snapshot-on-delete.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,27 @@
33
'@objectstack/platform-objects': minor
44
'@objectstack/spec': minor
55
'@objectstack/cli': minor
6+
'@objectstack/plugin-audit': minor
67
---
78

89
feat(objectql,platform-objects): a by-id delete keeps its rows in the recycle bin (ADR-0148): the `sys_recycle_bin` object, the snapshot on delete, the retention stamp and the TTL reap
910

1011
Clause-②: yes (widening)
1112
Metadata-protocol: added
12-
Skills-docs: follow-up owed — skills/objectstack-api/SKILL.md :268, :417 (they still teach that there is no recycle bin; not moved in this release)
13+
Skills-docs: follow-up owed — skills/objectstack-api/SKILL.md :268, :417 (they teach that there is no recycle bin)
1314

1415
The recycle bin's write side. A delete is still a physical delete, and no read path changed: the rows are gone from every query the moment the delete commits. What is new is the copy kept beside them. Restoring, purging and emptying the bin, the two grants that govern them and their REST doors are not in this release.
1516

1617
- **`@objectstack/platform-objects`:** registers `sys_recycle_bin`, built from the spec's `RECYCLE_BIN_ENTRY_FIELDS`. One entry per delete operation. It is engine-owned, with no generic data-API method, because the snapshot holds every field of the deleted rows. Its tenant column cascades, so deleting an organization deletes its entries. The lifecycle sweep reaps an entry once its stamped `purge_after` has passed (`ttl` on `purge_after`, window `0h`), and asks no resolver.
1718
- **`@objectstack/objectql`:** a by-id delete of a business record writes one entry in the delete's own unit of work, before the record's row is removed. The entry holds the record and its master-detail cascade, the master first. Each row keeps its declared columns, and `secret` columns are left out, so a restored record's secret fields come back empty. The entry also records the `set_null` references the delete cleared, and `deleted_by`, `deleted_at`, `retention_days` and `purge_after`. If removing the row fails, the entry goes too: the transaction rolls it back, or the engine removes it when no transaction covered it.
1819
- **Retention:** `ObjectQLPlugin`'s new `recycleBinRetention: { resolve, token }` option takes the host's retention resolver, called once per delete with the token the host handed over. When the option is absent or the resolver answers `undefined`, the retention is `OS_RECYCLE_BIN_RETENTION_DAYS`, else 30 days. A value that is not a positive whole number of days is refused: from the resolver, the delete is refused before it writes anything; in the variable, the boot is refused, because the plugin reads it in `init()`.
1920
- **Which deletes do NOT enter the bin:**
20-
- a delete by predicate (`multi: true`), which includes the lifecycle sweep;
21+
- a delete by predicate (`multi: true`), which includes every lifecycle sweep reap, even though the sweep names each reaped row by its id;
2122
- a child the cascade deletes, which is a row of its root's entry instead;
22-
- any `sys_*` object, whose rows are also left out of a business record's snapshot;
23+
- any platform object, meaning a `sys_*`, `cloud_*` or `ai_*` object, whose rows are also left out of a business record's snapshot;
2324
- any delete on a composition that does not register `PlatformObjectsPlugin`, which logs one `info` line saying so.
2425
- **Forward-only:** records deleted before this release have no entry.
2526
- **Storage:** every by-id delete of a business record now also writes one `sys_recycle_bin` row holding the deleted rows. The row is reaped once its retention has passed.
2627
- **`@objectstack/spec`:** `PLATFORM_OBJECTS_BY_PACKAGE['platform-objects']` lists `sys_recycle_bin`, so a reference to it lints as a real platform object. The comment above `RECYCLE_BIN_OBJECT` now names the object file that builds the table; no exported name, shape or description changed.
2728
- **`@objectstack/cli`:** the organization-ownership inventory has a row for `sys_recycle_bin` (fate `attribution`).
29+
- **`@objectstack/plugin-audit`:** `sys_recycle_bin` is excluded from the generic audit and activity writer, like the other engine-owned plumbing, so reaping an entry, clearing its `deleted_by` or cascading an organization's delete into its entries never copies a snapshot into `sys_audit_log` or `sys_activity`. The business delete an entry was taken for is audited exactly as before.

‎packages/cli/src/utils/organization-ownership-inventory.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -805,8 +805,10 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [
805805
{ object: 'sys_exchange_rate', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] },
806806
// The recycle bin (`@objectstack/platform-objects`, ADR-0148, #30237): the
807807
// engine writes each entry with the organization of the record it holds,
808-
// else the deleting context's, so a NULL row has no producer; the record it
809-
// names is gone, so no parent row anchors an entry.
808+
// else the deleting context's. A NULL row comes only from a delete with
809+
// neither (a tenancy-disabled object deleted by a context with no active
810+
// organization). The record an entry names is gone, so no parent row
811+
// anchors an entry.
810812
{ object: 'sys_recycle_bin', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] },
811813
// A reader's own named list views (`@objectstack/platform-objects`, ruling
812814
// 6570568131 on #28971): user data on the preference template, each row in

‎packages/objectql/src/engine.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9054,6 +9054,7 @@ export class ObjectQL implements IObjectQLEngine {
90549054
object: string,
90559055
id: string | number,
90569056
context: ExecutionContext | undefined,
9057+
predicate: boolean,
90579058
): RecycleBinCapture | undefined {
90589059
// [#30237] The body lives in `recycle-bin/capture.ts`, its docblock with it (see `RecycleBinCaptureHost`).
90599060
const readRegistry = () => this._registry;
@@ -9070,7 +9071,7 @@ export class ObjectQL implements IObjectQLEngine {
90709071
getDriver: (...a) => this.getDriver(...a),
90719072
buildDriverOptions: (...a) => this.buildDriverOptions(...a),
90729073
};
9073-
return openRecycleBinCapture.call(host, object, id, context);
9074+
return openRecycleBinCapture.call(host, object, id, context, predicate);
90749075
}
90759076

90769077
/**
@@ -9745,9 +9746,10 @@ export class ObjectQL implements IObjectQLEngine {
97459746
// walk touches it, and writes the one entry after the walk and
97469747
// before this row goes. A removal that throws takes the entry
97479748
// with it: the transaction's rollback when one covers the bin,
9748-
// the capture's compensation otherwise.
9749+
// the capture's compensation otherwise. A caller's `multi: true`
9750+
// opens none, even here: the lifecycle sweep reaps by id with it.
97499751
const runByIdDelete = async (writeContext?: ExecutionContext) => {
9750-
const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext);
9752+
const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true);
97519753
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected)
97529754
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
97539755
const entry = await bin?.write();

‎packages/objectql/src/recycle-bin/capture.test.ts‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,19 @@ const task = {
199199
watchers: { name: 'watchers', type: 'lookup' as const, reference: 'account', multiple: true },
200200
},
201201
};
202-
/** A system object: never enters the bin. */
202+
/** Platform objects, one per namespace: never enter the bin. */
203203
const sysThing = { name: 'sys_thing', label: 'Thing', fields: { id: text('id'), name: text('name') } };
204+
const cloudThing = { name: 'cloud_thing', label: 'Cloud Thing', fields: { id: text('id'), name: text('name') } };
205+
const aiThing = { name: 'ai_thing', label: 'AI Thing', fields: { id: text('id'), name: text('name') } };
206+
/** The organization the bin's tenant column cascades from (ruling Q4). */
207+
const organization = { name: 'sys_organization', label: 'Organization', fields: { id: text('id'), name: text('name') } };
208+
/** A business object that declares its own retention (ADR-0057's authoring surface). */
209+
const ephemeral = {
210+
name: 'ephemeral',
211+
label: 'Ephemeral',
212+
fields: { id: text('id'), expires_at: { name: 'expires_at', type: 'datetime' as const } },
213+
lifecycle: { class: 'transient', ttl: { field: 'expires_at', expireAfter: '0h' } },
214+
};
204215
/** Nothing references it: the plain, non-cascading delete. */
205216
const loner = { name: 'loner', label: 'Loner', fields: { id: text('id'), name: text('name') } };
206217

@@ -210,7 +221,7 @@ async function makeEngine(options: { withBin?: boolean; transactional?: boolean;
210221
const driver = makeDriver(options);
211222
engine.registerDriver(driver, true);
212223
await engine.init();
213-
const objects: any[] = [account, contact, note, task, sysThing, loner];
224+
const objects: any[] = [account, contact, note, task, sysThing, cloudThing, aiThing, organization, ephemeral, loner];
214225
if (options.withBin !== false) objects.push(bin);
215226
for (const o of objects) engine.registry.registerObject(o as any, '__test__');
216227
return { engine, driver, rec };
@@ -329,11 +340,37 @@ describe('deletes that do not enter the bin (v1 reach, seat ruling Q6)', () => {
329340
expect(entriesOf(driver)).toHaveLength(0);
330341
});
331342

332-
it('a sys_* object writes no entry', async () => {
343+
it('a by-id delete that its caller asked as a predicate (`multi: true`) writes no entry', async () => {
344+
const { engine, driver } = await makeEngine();
345+
driver.seed('loner', { id: 'l1', name: 'x' });
346+
await engine.delete('loner', { where: { id: 'l1' }, multi: true, ...USER } as any);
347+
expect(driver.rowsOf('loner')).toHaveLength(0);
348+
expect(entriesOf(driver)).toHaveLength(0);
349+
});
350+
351+
it("the lifecycle sweep's reap of a business object writes no entry", async () => {
352+
const { engine, driver } = await makeEngine();
353+
driver.seed('ephemeral', { id: 'e_due', expires_at: '2026-11-01T00:00:00.000Z' });
354+
driver.seed('ephemeral', { id: 'e_kept', expires_at: '2026-12-01T00:00:00.000Z' });
355+
const lifecycle = new LifecycleService({
356+
getEngine: () => engine as any,
357+
logger: { info: () => {}, warn: () => {}, debug: () => {}, error: () => {} } as any,
358+
now: () => Date.parse('2026-11-06T00:00:00.000Z'),
359+
initialDelayMs: 1,
360+
sweepIntervalMs: 10,
361+
});
362+
const report = await lifecycle.sweep();
363+
expect(report.errors).toEqual([]);
364+
// The reap ran: the due row is gone, by id, through the engine.
365+
expect(driver.rowsOf('ephemeral').map((r: Row) => r.id)).toEqual(['e_kept']);
366+
expect(entriesOf(driver)).toHaveLength(0);
367+
});
368+
369+
it.each(['sys_thing', 'cloud_thing', 'ai_thing'])('a platform object (%s) writes no entry', async (object) => {
333370
const { engine, driver } = await makeEngine();
334-
driver.seed('sys_thing', { id: 's1', name: 'x' });
335-
await engine.delete('sys_thing', { where: { id: 's1' } } as any);
336-
expect(driver.rowsOf('sys_thing')).toHaveLength(0);
371+
driver.seed(object, { id: 's1', name: 'x' });
372+
await engine.delete(object, { where: { id: 's1' }, ...USER } as any);
373+
expect(driver.rowsOf(object)).toHaveLength(0);
337374
expect(entriesOf(driver)).toHaveLength(0);
338375
});
339376

@@ -417,6 +454,24 @@ describe('the TTL sweep reaps an entry once its stamped deadline has passed (D3)
417454
});
418455
});
419456

457+
describe("an organization's delete takes its entries with it (ruling Q4)", () => {
458+
it('removes the entries of that organization, is not refused by them, and leaves other organizations\' entries', async () => {
459+
const { engine, driver } = await makeEngine();
460+
driver.seed('sys_organization', { id: 'org_1', name: 'One' });
461+
driver.seed('sys_organization', { id: 'org_2', name: 'Two' });
462+
driver.seed('loner', { id: 'l1', name: 'one' });
463+
driver.seed('loner', { id: 'l2', name: 'two' });
464+
await engine.delete('loner', { where: { id: 'l1' }, context: { userId: 'u_alice', tenantId: 'org_1' } } as any);
465+
await engine.delete('loner', { where: { id: 'l2' }, context: { userId: 'u_bob', tenantId: 'org_2' } } as any);
466+
expect(entriesOf(driver).map((e) => e.organization_id).sort()).toEqual(['org_1', 'org_2']);
467+
468+
await expect(engine.delete('sys_organization', { where: { id: 'org_1' }, ...USER } as any)).resolves.toBeTruthy();
469+
470+
expect(driver.rowsOf('sys_organization').map((r: Row) => r.id)).toEqual(['org_2']);
471+
expect(entriesOf(driver).map((e) => e.organization_id)).toEqual(['org_2']);
472+
});
473+
});
474+
420475
describe('cascadeMembersInOrder', () => {
421476
it('lists the root first, then breadth-first along the cascading edges, then any member no edge reached', () => {
422477
const set: CascadeDeleteSet = {

‎packages/objectql/src/recycle-bin/capture.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,14 @@
2828
*
2929
* ## Which deletes enter the bin (v1, seat ruling on #30237 Q6)
3030
*
31-
* A by-id delete of a business object (a name outside `sys_`) that is the
32-
* ROOT of its cascade. Not: a delete by predicate (`multi: true`, a lifecycle
33-
* reap), a child the cascade deletes (it is a row of its root's entry), and a
34-
* `sys_*` object. A `sys_*` row the cascade reaches is left out of the
35-
* snapshot too.
31+
* A by-id delete of a business object that is the ROOT of its cascade. A
32+
* business object is a name outside the platform namespaces `sys_`, `cloud_`
33+
* and `ai_` (`hasPlatformObjectPrefix`, the tenancy census's population; seat
34+
* ruling on the contract review's question 7). Not: a delete by predicate
35+
* (`multi: true`, which every lifecycle reap is, even though it addresses each
36+
* reaped row by id), a child the cascade deletes (it is a row of its root's
37+
* entry), and a platform object. A platform row the cascade reaches is left
38+
* out of the snapshot too.
3639
*
3740
* ## Why raw, and not `engine.insert`
3841
*
@@ -51,6 +54,7 @@ import {
5154
type RecycleBinSnapshotRow,
5255
} from '@objectstack/spec/data';
5356
import type { ExecutionContext } from '@objectstack/spec/kernel';
57+
import { hasPlatformObjectPrefix } from '@objectstack/spec/system';
5458
import type { Logger } from '@objectstack/core';
5559
import { redactBoundStatement } from '@objectstack/types';
5660
import { cascadeMemberKey, cascadeSetHas, type CascadeDeleteSet } from '../engine-top-level.js';
@@ -61,11 +65,12 @@ import { recycleBinPurgeAfter, resolveRecycleBinRetentionDays, type RecycleBinRe
6165

6266
/**
6367
* Does a delete of `object` enter the bin at all? The v1 reach: every object
64-
* outside the `sys_` namespace. The by-id and root-of-cascade conditions are
65-
* the caller's ({@link openRecycleBinCapture}).
68+
* outside the platform namespaces (`sys_`, `cloud_`, `ai_`). The by-id,
69+
* not-a-predicate and root-of-cascade conditions are the caller's
70+
* ({@link openRecycleBinCapture}).
6671
*/
6772
export function recycleBinTakesObject(object: string): boolean {
68-
return !object.startsWith('sys_');
73+
return !hasPlatformObjectPrefix(object);
6974
}
7075

7176
/** The notice that the composition registers no bin, given once per engine. */
@@ -308,14 +313,20 @@ export class RecycleBinCapture {
308313
* the delete does not enter the bin. Throws the retention refusal when the
309314
* host's resolver or `OS_RECYCLE_BIN_RETENTION_DAYS` holds a defect, before
310315
* the delete has written anything.
316+
*
317+
* `predicate` is the caller's own `multi: true`. The engine routes a delete by
318+
* its id, not by that flag (#5574, #11009), so a predicate delete that names
319+
* one row by id, as the lifecycle sweep's per-row reap does, arrives here on
320+
* the by-id path and is told apart only by the flag it was asked with.
311321
*/
312322
export function openRecycleBinCapture(
313323
this: RecycleBinCaptureHost,
314324
object: string,
315325
id: string | number,
316326
context: ExecutionContext | undefined,
327+
predicate: boolean,
317328
): RecycleBinCapture | undefined {
318-
if (!recycleBinTakesObject(object)) return undefined;
329+
if (predicate || !recycleBinTakesObject(object)) return undefined;
319330
// A child the cascade deletes is a row of its root's entry, never an entry.
320331
const inherited = this.cascadeDeleteSets.getStore();
321332
if (inherited && cascadeSetHas(inherited.members, object, id)) return undefined;

‎packages/platform-objects/src/system/sys-recycle-bin.object.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ import { ObjectSchema, Field, RECYCLE_BIN_ENTRY_FIELDS } from '@objectstack/spec
2626
* writers. The entry is written raw through this object's driver, inside the
2727
* delete's own unit of work (`@objectstack/objectql`, `recycle-bin/capture.ts`),
2828
* never through `engine.insert`, so no insert hook, audit mirror or activity
29-
* row fires for the bookkeeping of a delete the audit already records.
29+
* row fires for the bookkeeping of a delete the audit already records. The
30+
* later writes the engine makes through its own paths (the sweep's reap, the
31+
* `set_null` of `deleted_by`, an organization delete's cascade) are kept out
32+
* of the ledger by `@objectstack/plugin-audit`'s `SKIP_OBJECTS`.
3033
*
3134
* ⛔ No generic data-API method (`apiEnabled: false`, `apiMethods: []`): the
3235
* snapshot holds every field of the deleted rows, so a listing must apply the

‎packages/plugins/plugin-audit/src/audit-writers.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,69 @@ describe('audit writers — chunked upload sessions are excluded (#5202, ADR-005
525525
});
526526
});
527527

528+
describe('audit writers — recycle-bin entries are excluded (ADR-0148 D4, ADR-0057 §3.3)', () => {
529+
// An entry as the engine writes it: `snapshot` holds every declared column of
530+
// the deleted rows, `internal: true` ones included. Nothing here may reach
531+
// the ledger through the generic writer.
532+
const SCHEMA = {
533+
sys_audit_log: SINGLE_TENANT.sys_audit_log,
534+
sys_activity: SINGLE_TENANT.sys_activity,
535+
sys_recycle_bin: ['id', 'object_name', 'record_id', 'record_count', 'snapshot', 'deleted_by', 'deleted_at', 'retention_days', 'purge_after', 'organization_id'],
536+
crm_lead: ['id', 'name'],
537+
};
538+
const entry = (deletedBy: string | null) => ({
539+
id: 'rb-1',
540+
object_name: 'crm_lead',
541+
record_id: 'lead-1',
542+
record_count: 1,
543+
snapshot: { rows: [{ object: 'crm_lead', id: 'lead-1', values: { id: 'lead-1', name: 'Acme', scoring_notes: 'internal only' } }], clearedReferences: [] },
544+
deleted_by: deletedBy,
545+
deleted_at: '2026-11-06T00:00:00.000Z',
546+
retention_days: 30,
547+
purge_after: '2026-12-06T00:00:00.000Z',
548+
organization_id: 'org-1',
549+
});
550+
551+
it('writes NO audit/activity row for the lifecycle reap of an entry', async () => {
552+
const { engine, fire, created } = makeEngine(SCHEMA);
553+
installAuditWriters(engine as any, 'test.audit');
554+
await fire('afterDelete', {
555+
object: 'sys_recycle_bin',
556+
input: { id: 'rb-1' },
557+
previous: entry('user-1'),
558+
result: { id: 'rb-1' },
559+
session: { isSystem: true },
560+
});
561+
expect(created).toEqual([]);
562+
});
563+
564+
it("writes NO audit/activity row when a user's delete clears an entry's deleted_by", async () => {
565+
const { engine, fire, created } = makeEngine(SCHEMA);
566+
installAuditWriters(engine as any, 'test.audit');
567+
await fire('afterUpdate', {
568+
object: 'sys_recycle_bin',
569+
input: { id: 'rb-1', deleted_by: null },
570+
previous: entry('user-1'),
571+
result: entry(null),
572+
session: { userId: 'user-admin' },
573+
});
574+
expect(created).toEqual([]);
575+
});
576+
577+
it('still audits the business delete the entry was taken for (the skip stays narrow)', async () => {
578+
const { engine, fire, created } = makeEngine(SCHEMA);
579+
installAuditWriters(engine as any, 'test.audit');
580+
await fire('afterDelete', {
581+
object: 'crm_lead',
582+
input: { id: 'lead-1' },
583+
previous: { id: 'lead-1', name: 'Acme' },
584+
result: { id: 'lead-1' },
585+
session: { userId: 'user-1' },
586+
});
587+
expect(created.map((c) => c.object)).toEqual(['sys_audit_log', 'sys_activity']);
588+
});
589+
});
590+
528591
describe('audit writers — declarative trackHistory activity (ADR-0052 §5b)', () => {
529592
// crm_opportunity with a tracked select field (Stage) carrying option labels.
530593
const SCHEMA = {

0 commit comments

Comments
 (0)