Skip to content

Commit ac14915

Browse files
committed
fix(objectql): an organization delete removes its units of measure
The organization delete's own cascade removes the organization's sys_unit rows, retired ones included, once the delete is admitted: the one exemption from the sys_unit delete refusal (ruling 7035627429, option B). The exemption is the engine's own cascade token, issued only by the removal and claimed by the delete it names, so every other unit delete is still refused 405 ERR_UNIT_DELETE_REFUSED, for a user, a system writer and an automation run, by id and batched, a hook's delete during the removal included. Units no longer count as records that keep an organization from being deleted. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvMi1U7R2kBd3JbTPu
1 parent 4609c48 commit ac14915

9 files changed

Lines changed: 336 additions & 31 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): deleting an organization also deletes its units of measure, the one exemption from the `sys_unit` delete refusal
6+
7+
Clause-②: yes
8+
Metadata-protocol: none
9+
10+
An organization that had ever created a unit of measure could not be deleted: the delete was refused with 409 `DELETE_RESTRICTED` naming `sys_unit`, and the units could not be removed first, because the engine refuses every delete of a unit (405 `ERR_UNIT_DELETE_REFUSED`). Now the organization delete's own cascade removes that organization's `sys_unit` rows, retired ones included, through the engine's delete path, after the delete has been admitted, so no unit row is left naming a deleted organization. `organizationOwnedRowCounts` (the question plugin-auth's organization delete asks first) and the engine's own refusal no longer count units as records the organization still owns.
11+
12+
**Declared behaviour change.** A delete door widens, in one place only. A delete of an organization that holds units and no other record now succeeds and removes the units; before, it was refused. An organization that owns any other record is still refused, and none of its units is removed. Every other delete of a unit is still refused with 405 `ERR_UNIT_DELETE_REFUSED`, by id and batched, for a user, a system writer and an automation run, including a delete issued by a hook while the organization's delete is running: the exemption is recognised from the engine's own cascade, never from anything a caller passes. Retire a unit (`retired: true`) to stop its use, as before.

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

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
} from './engine-top-level.js';
5757
import type { ReferentialClearOption } from './engine-top-level.js';
5858
import { isExternalDriverFloor } from './external-driver-floor.js';
59+
import { ORGANIZATION_UNIT_OBJECT } from './validation/unit-code-membership.js';
5960
import { forgetCollectedProbes, takeCollectedProbe } from './engine-delete-cascade.js';
6061
import type { CascadeDeleteSet } from './engine-top-level.js';
6162
import { ObjectQLStatics as ObjectQL } from './engine.js';
@@ -1213,6 +1214,13 @@ export class CascadePlanningFacet {
12131214
}
12141215
}
12151216
}
1217+
// [ruling 7035627429, option B] An organization's delete removes its units,
1218+
// the one exemption from the `sys_unit` delete refusal. Last, once
1219+
// `refuseOrganizationDeleteWhileOwned` above has admitted the delete and
1220+
// every relation has been judged, so a refused delete removes no unit.
1221+
if (object === ORGANIZATION_OBJECT) {
1222+
for (const id of ids) await removeOrganizationUnits(this, id, context, objects, cascadeSet);
1223+
}
12161224
}
12171225

12181226
/**
@@ -1348,7 +1356,9 @@ export class CascadePlanningFacet {
13481356
/**
13491357
* [#24948] The engine half of organization delete: refuse while any row
13501358
* outside the cascade set still names the organization in its tenant column,
1351-
* a row that outlives the organization excepted ({@link outlivesOrganization}).
1359+
* a row that outlives the organization excepted ({@link outlivesOrganization}),
1360+
* and so is a unit of measure, which the walk removes with the organization
1361+
* once this admits the delete (`removeOrganizationUnits`).
13521362
*
13531363
* Runs before the walk touches the first relation, and reads every tenant
13541364
* relation before it throws, so the one refusal names every table that holds
@@ -1373,6 +1383,9 @@ export class CascadePlanningFacet {
13731383
const fields = (child as any)?.fields as Record<string, any> | undefined;
13741384
// An append-only or engine-owned object's rows outlive the organization: not counted, kept as they are.
13751385
if (!childName || !fields || ObjectQL.outlivesOrganization(child)) continue;
1386+
// [ruling 7035627429, option B] The organization's units are not counted:
1387+
// the walk removes them with it (`removeOrganizationUnits`).
1388+
if (childName === ORGANIZATION_UNIT_OBJECT) continue;
13761389
for (const [fieldName, fdef] of Object.entries(fields)) {
13771390
const behavior = this.cascadeRelationBehavior(ORGANIZATION_OBJECT, child, fieldName, fdef);
13781391
if (!this.isTenantColumnSetNull(ORGANIZATION_OBJECT, child, fieldName, behavior)) continue;
@@ -1415,6 +1428,8 @@ export class CascadePlanningFacet {
14151428
const childName = (child as any)?.name as string | undefined;
14161429
const fields = (child as any)?.fields as Record<string, any> | undefined;
14171430
if (!childName || !fields || exclude.has(childName) || ObjectQL.outlivesOrganization(child)) continue;
1431+
// [ruling 7035627429, option B] The organization's units go with its delete, as in the engine's refusal.
1432+
if (childName === ORGANIZATION_UNIT_OBJECT) continue;
14181433
const tenantField = resolveTenantFieldName(child);
14191434
if (!tenantField || !fields[tenantField]) continue;
14201435
const fdef = fields[tenantField];
@@ -1517,6 +1532,79 @@ async function deleteCascadedChildren(host: Pick<CascadePlanningHost, 'cascadeIs
15171532
}
15181533
}
15191534

1535+
/**
1536+
* The tokens {@link removeOrganizationUnits} issued, and no other: the
1537+
* provenance `delete()` reads ({@link isOrganizationUnitRemoval}) to admit an
1538+
* organization's unit delete. Module-private, so nothing outside this module
1539+
* can enter a token into it, a holder of the engine's own `cascadeIssuedDeletes`
1540+
* store included.
1541+
*/
1542+
const organizationUnitRemovals = new WeakSet<object>();
1543+
1544+
/**
1545+
* [ruling 7035627429, option B] Is `token`, the cascade token a `delete()` has
1546+
* just claimed, one an organization's delete issued to remove one of its
1547+
* units? The one exemption from `refuseOrganizationUnitDelete`
1548+
* (`validation/unit-code-membership.ts`): `delete()` asks it only for the token
1549+
* it claimed itself, so the answer reaches that one delete and no other.
1550+
*/
1551+
export function isOrganizationUnitRemoval(token: unknown): boolean {
1552+
return typeof token === 'object' && token !== null && organizationUnitRemovals.has(token);
1553+
}
1554+
1555+
/**
1556+
* [ruling 7035627429, option B; ADR-0158 Open item 11] Remove the units of
1557+
* the organization `organizationId`, whose delete {@link
1558+
* CascadePlanningFacet.walkReferencingRelations} has admitted: a deleted
1559+
* organization can never create a code again, so its units, retired ones
1560+
* included, go with it and no `sys_unit` row is left naming it.
1561+
*
1562+
* The organization is named explicitly, twice, as the unit-code membership
1563+
* read names it (`organizationUnitRowsOf`): the read's predicate on the tenant
1564+
* column, and the `tenantId` of the context both the read and the deletes run
1565+
* under. That context is `sudo()`-shaped ({@link
1566+
* CascadePlanningFacet.referenceCheckContext}): the caller's transaction and
1567+
* user ride along, so the deletes join the organization delete's unit of work
1568+
* and the audit ledger records who triggered them, and system identity
1569+
* authorizes them, because no permission set grants a unit delete to anyone.
1570+
* The read is filed as a reference-check elevation, as the refusal's counts
1571+
* are.
1572+
*
1573+
* Each unit goes through the public `delete()` by id, inside a cascade token
1574+
* naming exactly that unit (as {@link deleteCascadedChildren} issues one per
1575+
* child), so its hooks run with `referentialCascadeDelete` set and its audit
1576+
* and events are a cascade child's. The token is recorded in
1577+
* {@link organizationUnitRemovals}, which is what admits the delete past the
1578+
* `sys_unit` refusal; a delete that does not claim it (a hook's own, another
1579+
* request's) is refused. A table never provisioned holds no unit.
1580+
*/
1581+
async function removeOrganizationUnits(host: Pick<CascadePlanningHost, 'cascadeIssuedDeletes' | 'delete' | 'fileReferenceCheckElevation' | 'find'>, organizationId: string | number, context: ExecutionContext | undefined, objects: ServiceObject[], cascadeSet: CascadeDeleteSet): Promise<void> {
1582+
const unit = objects.find((o) => (o as { name?: unknown })?.name === ORGANIZATION_UNIT_OBJECT);
1583+
const tenantField = unit ? resolveTenantFieldName(unit) : null;
1584+
if (!unit || !tenantField) return;
1585+
host.fileReferenceCheckElevation(cascadeSet, ORGANIZATION_OBJECT, organizationId, ORGANIZATION_UNIT_OBJECT, tenantField, context);
1586+
const unitContext = { ...ObjectQL.referenceCheckContext(context), tenantId: String(organizationId) } as ExecutionContext;
1587+
let rows: unknown;
1588+
try {
1589+
rows = await host.find(ORGANIZATION_UNIT_OBJECT, {
1590+
where: { [tenantField]: organizationId },
1591+
fields: ['id'],
1592+
context: unitContext,
1593+
});
1594+
} catch (error) {
1595+
if (isMissingTableError(error, ORGANIZATION_UNIT_OBJECT)) return;
1596+
throw error;
1597+
}
1598+
for (const row of Array.isArray(rows) ? (rows as Array<{ id?: unknown }>) : []) {
1599+
const token = { object: ORGANIZATION_UNIT_OBJECT, id: String(row.id), claimed: false };
1600+
organizationUnitRemovals.add(token);
1601+
await host.cascadeIssuedDeletes.run(
1602+
token,
1603+
() => host.delete(ORGANIZATION_UNIT_OBJECT, { where: { id: row.id }, context: unitContext } as any),
1604+
);
1605+
}
1606+
}
1607+
15201608
/**
15211609
* [ruling 6893104201 point 2] Does the caller's READ door return every child
15221610
* of the chunk? Asked through the public `find()` under the walk's context,

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ import {
9797
import { ObjectQLStatics as ObjectQL } from './engine.js';
9898
import type { ObjectQL as ObjectQLClass } from './engine.js';
9999
import { refuseOrganizationUnitDelete } from './validation/unit-code-membership.js';
100+
import { isOrganizationUnitRemoval } from './engine-cascade-planning.js';
100101

101102
/**
102103
* The `ObjectQL` members the bodies of {@link DeleteAndAggregateFacet} read — every one of
@@ -116,6 +117,7 @@ export interface DeleteAndAggregateHost {
116117
buildSession: ObjectQLClass['buildSession'];
117118
buildUser: ObjectQLClass['buildUser'];
118119
cascadeDeleteRelations: ObjectQLClass['cascadeDeleteRelations'];
120+
readonly cascadeIssuedDeletes: ObjectQLClass['cascadeIssuedDeletes'];
119121
claimReferentialCascadeDelete: ObjectQLClass['claimReferentialCascadeDelete'];
120122
composeReadableIdsAtBoundary: ObjectQLClass['composeReadableIdsAtBoundary'];
121123
delete: ObjectQLClass['delete'];
@@ -155,7 +157,7 @@ export interface DeleteAndAggregateHost {
155157
/** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
156158
export class DeleteAndAggregateFacet {
157159
/** The body of `ObjectQL#delete`; the method's docblock there is its contract. */
158-
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
160+
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'cascadeIssuedDeletes' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
159161
object = this.resolveObjectName(object);
160162
// [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's
161163
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
@@ -170,10 +172,6 @@ export class DeleteAndAggregateFacet {
170172
ownUnit ? () => this.inAfterAbortUnit(body) : body;
171173
this.logger.debug('Delete operation starting', { object });
172174
this.assertWriteAllowed(object, 'delete');
173-
// [ADR-0158 Open item 11] A unit of measure is retired, never deleted:
174-
// refused here, before any middleware or hook, so the refusal holds for a
175-
// system writer and an automation run as for a user, single and batched.
176-
refuseOrganizationUnitDelete(object);
177175
// [#8844] See the insert face — deleting the install's only organization
178176
// must not leave the memo answering with it.
179177
if (object === ORGANIZATION_OBJECT) this.invalidateOrganizationProbe();
@@ -223,6 +221,16 @@ export class DeleteAndAggregateFacet {
223221
// [ruling 6893661036, F1] A predicate delete hands its `where` instead: a
224222
// cascade batch is claimed by the exact id set it names.
225223
const referentialCascadeDelete = this.claimReferentialCascadeDelete(object, id ?? options?.where);
224+
// [ADR-0158 Open item 11] A unit of measure is retired, never deleted on its
225+
// own: refused here, before any middleware or hook, so the refusal holds for
226+
// a system writer and an automation run as for a user, single and batched.
227+
// [ruling 7035627429, option B] The one exemption is the organization
228+
// delete's own removal of its units, recognised by the cascade token THIS
229+
// call just claimed, never by anything the caller hands in.
230+
refuseOrganizationUnitDelete(
231+
object,
232+
referentialCascadeDelete === true && isOrganizationUnitRemoval(this.cascadeIssuedDeletes.getStore()),
233+
);
226234

227235
const opCtx: OperationContext = {
228236
object,

0 commit comments

Comments
 (0)