Skip to content

Commit d374cbe

Browse files
committed
feat(objectql,platform-objects): keep a by-id delete's rows in the recycle bin
ADR-0148, first slice: the sys_recycle_bin object, the snapshot on delete, the retention stamp and the TTL reap. - platform-objects registers sys_recycle_bin, built from the spec's RECYCLE_BIN_ENTRY_FIELDS: engine-owned, no generic data-API method, its tenant column cascades, ttl on purge_after. - objectql: a by-id delete of a business record writes one entry in its own unit of work, before the root row goes: the cascade set read raw before the walk (master first, secret columns left out), the set_null references the walk cleared, deleted_by/deleted_at, retention_days and purge_after. A removal that fails takes the entry with it. - retention: ObjectQLPlugin's recycleBinRetention { resolve, token }, else OS_RECYCLE_BIN_RETENTION_DAYS (read at init), else 30 days; a value that is not a positive whole number is refused. - spec: sys_recycle_bin joins PLATFORM_OBJECTS_BY_PACKAGE; cli: its organization-ownership inventory row. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4czFGLnXKQd6cQjv3Pr
1 parent 05a30e6 commit d374cbe

18 files changed

Lines changed: 1244 additions & 14 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/objectql': minor
3+
'@objectstack/platform-objects': minor
4+
'@objectstack/spec': minor
5+
'@objectstack/cli': minor
6+
---
7+
8+
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
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: added
12+
13+
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.
14+
15+
- **`@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.
16+
- **`@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.
17+
- **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()`.
18+
- **Which deletes do NOT enter the bin:**
19+
- a delete by predicate (`multi: true`), which includes the lifecycle sweep;
20+
- a child the cascade deletes, which is a row of its root's entry instead;
21+
- any `sys_*` object, whose rows are also left out of a business record's snapshot;
22+
- any delete on a composition that does not register `PlatformObjectsPlugin`, which logs one `info` line saying so.
23+
- **Forward-only:** records deleted before this release have no entry.
24+
- **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.
25+
- **`@objectstack/spec`:** `PLATFORM_OBJECTS_BY_PACKAGE['platform-objects']` lists `sys_recycle_bin`, so a reference to it lints as a real platform object.
26+
- **`@objectstack/cli`:** the organization-ownership inventory has a row for `sys_recycle_bin` (fate `attribution`).

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,11 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [
803803
// Exchange rates (`@objectstack/platform-objects`, #27185): an organization's
804804
// administrators author its own rate table; no parent row anchors a rate.
805805
{ object: 'sys_exchange_rate', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] },
806+
// The recycle bin (`@objectstack/platform-objects`, ADR-0148, #30237): the
807+
// 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.
810+
{ object: 'sys_recycle_bin', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] },
806811
// A reader's own named list views (`@objectstack/platform-objects`, ruling
807812
// 6570568131 on #28971): user data on the preference template, each row in
808813
// its owner's organization; no parent row anchors a view.

‎packages/objectql/src/engine-cascade-planning.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,8 +511,14 @@ export class CascadePlanningFacet {
511511
* A nested `delete()` the walk makes for a member joins the ambient set
512512
* ({@link cascadeDeleteSets}); any other delete reaching here — a hook's,
513513
* say — is the root of its own cascade, as before.
514+
*
515+
* [#30237, ADR-0148 D1] `onCollected` is the recycle bin's moment: called
516+
* once with the freshly collected set, after the #26718 restricts are judged
517+
* and before the walk deletes or clears anything, so the snapshot reads every
518+
* row as it stood. Never called for a member that joins a cascade already in
519+
* progress: such a row belongs to its root's entry.
514520
*/
515-
static async cascadeDeleteRelations(this: Pick<CascadePlanningHost, '_registry' | 'cascadeDeleteSets' | 'collectCascadeDeleteSet' | 'refuseRestrictsInsideOwnCascade' | 'walkReferencingRelations'>, object: string, ids: ReadonlyArray<string | number>, context?: ExecutionContext, depth = 0): Promise<void> {
521+
static async cascadeDeleteRelations(this: Pick<CascadePlanningHost, '_registry' | 'cascadeDeleteSets' | 'collectCascadeDeleteSet' | 'refuseRestrictsInsideOwnCascade' | 'walkReferencingRelations'>, object: string, ids: ReadonlyArray<string | number>, context?: ExecutionContext, depth = 0, onCollected?: (set: CascadeDeleteSet) => Promise<void>): Promise<void> {
516522
const roots: Array<string | number> = [];
517523
const seen = new Set<string>();
518524
for (const id of ids) {
@@ -555,6 +561,7 @@ export class CascadePlanningFacet {
555561
// [#26718] Every restrict a member's own cascade would override is judged
556562
// here, before the first write.
557563
await this.refuseRestrictsInsideOwnCascade(cascadeSet, fresh.map((id) => ({ object, id })), context, objects);
564+
if (onCollected) await onCollected(cascadeSet);
558565
await this.cascadeDeleteSets.run(cascadeSet, () =>
559566
this.walkReferencingRelations(object, fresh, context, objects, cascadeSet),
560567
);
@@ -1163,6 +1170,13 @@ export class CascadePlanningFacet {
11631170
} else {
11641171
await this.update(childName, { id: depId, [fieldName]: null }, { context: referentialCtx } as any);
11651172
}
1173+
// [#30237, ADR-0148 D2] The reference a restore re-links while
1174+
// the field still lacks it: the live row, the field, and the id
1175+
// this delete removed from it. Only a delete that enters the
1176+
// recycle bin carries the list.
1177+
cascadeSet.clearedReferences?.push({
1178+
object: childName, id: String(depId), field: fieldName, value: String(id),
1179+
});
11661180
}
11671181
}
11681182
// [#27004] Every row outside the set has had `id` cleared from it.

‎packages/objectql/src/engine-top-level.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
// importer of `./engine.js` reads what it read.
1313

1414
import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_TYPES, FullTextSearchSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED, REFERENCE_VALUE_TYPES, RPC_QUERY_ALIAS_SLOTS, VALID_AST_OPERATORS, foldQueryAliasSlots, isFilterAST, isMultiValueField, lowerFilterCondition, normalizeFilterComparandTypes, parseFilterAST, readAutonumberCounter, referenceCarrierOf, referenceTargetOf, resolveInjectedColumnProvenance } from '@objectstack/spec/data';
15-
import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, ServiceObject } from '@objectstack/spec/data';
15+
import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, RecycleBinClearedReference, ServiceObject } from '@objectstack/spec/data';
1616
import type { EngineFilterJudgement, ISecurityService } from '@objectstack/spec/contracts';
1717
import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js';
1818
import { assertResolvedTemporalTokensInRange, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js';
@@ -4372,6 +4372,16 @@ export interface CascadeDeleteSet {
43724372
* one has removed from it; the remainder written leaves those out too.
43734373
*/
43744374
readonly cleared: Map<string, Set<string>>;
4375+
/**
4376+
* [#30237, ADR-0148 D2] Every `set_null` reference the walk cleared, one per
4377+
* live row, field and removed id: the referencing row, the field, and the id
4378+
* the field held (a row this delete removes). Present only on the set of a
4379+
* delete that enters the recycle bin, which assigns it when the set is
4380+
* collected; the walk appends to it, nested deletes of the same cascade
4381+
* included, and the entry keeps it so a restore can re-link what is still
4382+
* empty.
4383+
*/
4384+
clearedReferences?: RecycleBinClearedReference[];
43754385
}
43764386

43774387
/** [#26718] One member of a {@link CascadeDeleteSet}, as a single key. */

‎packages/objectql/src/engine.ts‎

Lines changed: 71 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,10 @@ import {
8181
type SecretHandleSlot,
8282
type StoredRowsReader,
8383
} from './engine-secret-internal-fields.js';
84+
// [#30237, ADR-0148] The recycle bin's write side: the capture body, and the
85+
// retention seam the host hands over (`RecycleBinCaptureHost`).
86+
import { openRecycleBinCapture, type RecycleBinCapture } from './recycle-bin/capture.js';
87+
import type { RecycleBinRetentionSettings } from './recycle-bin/retention.js';
8488
// [#25522 cut 6] The predicate-write hook dispatch bodies; the methods of the
8589
// same names below hand each body the members it reads (`HookDispatchHost`).
8690
import {
@@ -9019,9 +9023,54 @@ export class ObjectQL implements IObjectQLEngine {
90199023
ids: ReadonlyArray<string | number>,
90209024
context?: ExecutionContext,
90219025
depth = 0,
9026+
onCollected?: (set: CascadeDeleteSet) => Promise<void>,
90229027
): Promise<void> {
90239028
// [#29986 codemod] The body moved to `engine-cascade-planning.ts`, its docblock with it (see `CascadePlanningHost`).
9024-
return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth);
9029+
return CascadePlanningFacet.cascadeDeleteRelations.call(cascadePlanningHost.of(this), object, ids, context, depth, onCollected);
9030+
}
9031+
9032+
/**
9033+
* [#30237, ADR-0148 D3] What the host handed over for the recycle bin's
9034+
* retention: its resolver and the token to call it with. `undefined` until
9035+
* {@link setRecycleBinRetention}: `OS_RECYCLE_BIN_RETENTION_DAYS`, else 30.
9036+
*/
9037+
private recycleBinRetention: RecycleBinRetentionSettings | undefined;
9038+
9039+
/** [#30237] The recycle bin's once-per-engine notices already given. */
9040+
private readonly recycleBinNotices = new Set<string>();
9041+
9042+
/**
9043+
* [#30237, ADR-0148 D3] Install the host's retention resolver and the opaque
9044+
* token it is called with (the one its `resolveFeatures` receives). The
9045+
* engine asks once per delete operation that enters the bin and stamps the
9046+
* answer on the entry; `ObjectQLPlugin` calls this from its
9047+
* `recycleBinRetention` option.
9048+
*/
9049+
setRecycleBinRetention(settings: RecycleBinRetentionSettings | undefined): void {
9050+
this.recycleBinRetention = settings;
9051+
}
9052+
9053+
private openRecycleBinCapture(
9054+
object: string,
9055+
id: string | number,
9056+
context: ExecutionContext | undefined,
9057+
): RecycleBinCapture | undefined {
9058+
// [#30237] The body lives in `recycle-bin/capture.ts`, its docblock with it (see `RecycleBinCaptureHost`).
9059+
const readRegistry = () => this._registry;
9060+
const readLogger = () => this.logger;
9061+
const readCascadeDeleteSets = () => this.cascadeDeleteSets;
9062+
const readRetention = () => this.recycleBinRetention;
9063+
const readNotices = () => this.recycleBinNotices;
9064+
const host: ThisParameterType<typeof openRecycleBinCapture> = {
9065+
get _registry() { return readRegistry(); },
9066+
get logger() { return readLogger(); },
9067+
get cascadeDeleteSets() { return readCascadeDeleteSets(); },
9068+
get recycleBinRetention() { return readRetention(); },
9069+
get recycleBinNotices() { return readNotices(); },
9070+
getDriver: (...a) => this.getDriver(...a),
9071+
buildDriverOptions: (...a) => this.buildDriverOptions(...a),
9072+
};
9073+
return openRecycleBinCapture.call(host, object, id, context);
90259074
}
90269075

90279076
/**
@@ -9689,14 +9738,29 @@ export class ObjectQL implements IObjectQLEngine {
96899738
// A dependent's stale-roll-up refusal stops the walk before this
96909739
// row is removed, so it is not this delete's answer:
96919740
// `cascadeStoppedRefusal` says what it is instead.
9741+
//
9742+
// [#30237, ADR-0148 D1] The recycle bin rides the same unit: the
9743+
// capture opens before the cascade (a retention defect refuses
9744+
// here, before any write), reads the collected set before the
9745+
// walk touches it, and writes the one entry after the walk and
9746+
// before this row goes. A removal that throws takes the entry
9747+
// with it: the transaction's rollback when one covers the bin,
9748+
// the capture's compensation otherwise.
96929749
const runByIdDelete = async (writeContext?: ExecutionContext) => {
9693-
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext)
9750+
const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext);
9751+
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected)
96949752
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
9695-
return await driver.delete(
9696-
object,
9697-
hookContext.input.id as string,
9698-
this.buildDriverOptions(object, writeContext, hookContext.input.options as any),
9699-
);
9753+
const entry = await bin?.write();
9754+
try {
9755+
return await driver.delete(
9756+
object,
9757+
hookContext.input.id as string,
9758+
this.buildDriverOptions(object, writeContext, hookContext.input.options as any),
9759+
);
9760+
} catch (e) {
9761+
await entry?.compensate();
9762+
throw e;
9763+
}
97009764
};
97019765
// WHEN to open one is `planCascadeAtomicity`'s call — see there.
97029766
// `'none'` (nothing references this object) keeps the pre-#7413

‎packages/objectql/src/federated-injected-column-readers.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,11 @@ const READERS: Record<string, Row> = {
309309
disposition: 'row-value',
310310
why: 'reads the tenant column off the written row; a federated row has none, so the event omits it',
311311
},
312+
// [#30237] A recycle-bin entry belongs to the organization of the record it holds.
313+
'recycle-bin/capture.ts#organizationOf :: resolveTenantFieldName()': {
314+
disposition: 'row-value',
315+
why: "reads the tenant column off the snapshotted root row; a federated row has none, so the entry takes the deleting context's organization",
316+
},
312317
'relation-filter-lowering.ts#admitRelationCondition :: referenceTargetOf()': {
313318
disposition: 'caller-predicate',
314319
why: "lowers a relation condition the caller wrote; it names an injected column only when the caller did",

‎packages/objectql/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,8 @@ export type {
628628
LifecycleFloorViolation,
629629
} from './lifecycle/lifecycle-service.js';
630630
export { parseLifecycleDuration } from './lifecycle/duration.js';
631+
// [#30237, ADR-0148 D3] What a host hands `ObjectQLPlugin`'s `recycleBinRetention`.
632+
export type { RecycleBinRetentionSettings } from './recycle-bin/retention.js';
631633
export { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js';
632634

633635
// [#4551] Read-only referential-integrity audit — the reporting half of the

‎packages/objectql/src/plugin.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { isFederatedObject } from './federated-object.js';
3636
import { wrapDeclarativeHook } from './hook-wrappers.js';
3737
import { announceStoredExpressionHoles } from './stored-expression-backfill.js';
3838
import { LifecycleService } from './lifecycle/lifecycle-service.js';
39+
import { readRecycleBinRetentionEnv, type RecycleBinRetentionSettings } from './recycle-bin/retention.js';
3940
import { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js';
4041
import type { DanglingReferenceAuditOptions } from './integrity/dangling-reference-audit.js';
4142
import {
@@ -395,6 +396,19 @@ export interface ObjectQLPluginOptions {
395396
initialDelayMs?: number;
396397
referenceAudit?: Omit<DanglingReferenceAuditOptions, 'signal'> & { enabled?: boolean };
397398
};
399+
/**
400+
* [#30237, ADR-0148 D3] The recycle bin's retention seam: the host's
401+
* retention resolver (`RecycleBinRetentionResolver`, `@objectstack/spec/data`)
402+
* and the opaque token to call it with, the same one the host's
403+
* `resolveFeatures` receives. One kernel serves one environment, so the
404+
* token is fixed at boot; the engine never reads it.
405+
*
406+
* Absent, or a resolver answering `undefined`: `OS_RECYCLE_BIN_RETENTION_DAYS`,
407+
* else 30 days. That variable is read once in `init()` as well, so a value
408+
* that is not a positive whole number of days stops the boot with the
409+
* refusal rather than the first delete.
410+
*/
411+
recycleBinRetention?: RecycleBinRetentionSettings;
398412
}
399413

400414
/**
@@ -537,6 +551,8 @@ export class ObjectQLPlugin implements Plugin {
537551
/** ADR-0057 lifecycle enforcement (Reaper/Rotator/Archiver). */
538552
private lifecycleService: LifecycleService | undefined;
539553
private lifecycleOptions: ObjectQLPluginOptions['lifecycle'];
554+
/** [#30237] The host's recycle-bin retention seam, handed to the engine in `init()`. */
555+
private recycleBinRetention: ObjectQLPluginOptions['recycleBinRetention'];
540556

541557
constructor(qlOrOptions?: ObjectQL | ObjectQLPluginOptions, hostContext?: Record<string, any>) {
542558
// Back-compat: legacy callers passed `(ObjectQL, hostContext)` positionally.
@@ -564,6 +580,7 @@ export class ObjectQLPlugin implements Plugin {
564580
this.hydrateMetadataFromDb = opts.hydrateMetadataFromDb === true;
565581
this.registerProtocol = opts.registerProtocol !== false;
566582
this.lifecycleOptions = opts.lifecycle;
583+
this.recycleBinRetention = opts.recycleBinRetention;
567584
}
568585

569586
/**
@@ -796,6 +813,14 @@ export class ObjectQLPlugin implements Plugin {
796813
// plugins read it — see SKIP_SCHEMA_SYNC_ENGINE_KEY.
797814
(this.ql as unknown as Record<string, unknown>)[SKIP_SCHEMA_SYNC_ENGINE_KEY] = this.skipSchemaSync;
798815

816+
// [#30237, ADR-0148 D3] The recycle bin's retention: the variable is read
817+
// now, so a defect in it stops the boot with the refusal instead of
818+
// refusing the first delete, and the host's resolver is handed over. The
819+
// resolver itself is asked per delete: its answer may change with the
820+
// host's plan, and each entry keeps the one it was given.
821+
readRecycleBinRetentionEnv();
822+
if (this.recycleBinRetention) this.ql.setRecycleBinRetention(this.recycleBinRetention);
823+
799824
// [ADR-0139 D2] The engine composes a `ReadableIds` leaf from the
800825
// registered `security` service. Handed over as a SOURCE in the engine's
801826
// slot (`SECURITY_SERVICE_SOURCE_SLOT`, not public surface), read at use and

0 commit comments

Comments
 (0)