Skip to content
19 changes: 19 additions & 0 deletions .changeset/35167-insert-delete-unit-inside-middleware.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/objectql': patch
---

fix(objectql): insert and delete open their own unit of work around the engine body, as update does

Clause-②: no
Metadata-protocol: none

An insert or delete opens its own unit of work when the object carries a metadata `before*` hook on that verb, or a blocking (`onError: abort`, the default) or conditioned metadata `after*` hook. The unit exists so that a refusal later in the write rolls back what the write's hooks wrote through `ctx.api`, the row included. Update moves that unit around the engine body only in this same release; insert and delete opened it around the whole write, the middleware chain included. All three verbs now follow one rule: the middleware chain, the authorization gate included, runs before the unit opens, and the hooks, the row write and the `after*` chain run inside it and still roll back together.

What changes for an insert or delete on such an object:

- On a single-connection store such as SQLite, a writer whose authorization gate or middleware is still running no longer holds the store's only connection, so other writers are no longer queued behind it.
- What a middleware does after `next()` now runs after the commit, as it already does for an update and for an insert or delete on an object with no such hook. A middleware that throws after `next()` no longer rolls the row back on a hooked object; it never did on any other object.

This patch does not address the answer the loser of two concurrent deletes of one row gets.

Nothing to change in an app.
18 changes: 12 additions & 6 deletions packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,19 @@ export interface DeleteAndAggregateHost {
/** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
export class DeleteAndAggregateFacet {
/** The body of `ObjectQL#delete`; the method's docblock there is its contract. */
static async delete(this: Pick<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'claimReferentialCascadeDelete' | 'delete' | '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> {
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> {
object = this.resolveObjectName(object);
// [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
if (this.opensAfterAbortUnit('afterDelete', object, options?.context)) {
return this.inAfterAbortUnit(() => this.delete(object, options));
}
//
// [#35167] As in `insert` and `update`: the unit opens around the ENGINE
// BODY (the executor below), never around the door, so the middleware
// chain — the authorization gate's reads, and whatever a middleware does
// after `next()` — runs outside it. Nothing between here and the executor
// writes; the cascade claim below is an in-memory marker.
const ownUnit = this.opensAfterAbortUnit('afterDelete', object, options?.context);
const inOwnUnit = <T>(body: () => Promise<T>): (() => Promise<T>) =>
ownUnit ? () => this.inAfterAbortUnit(body) : body;
this.logger.debug('Delete operation starting', { object });
this.assertWriteAllowed(object, 'delete');
// [#8844] See the insert face — deleting the install's only organization
Expand Down Expand Up @@ -225,7 +231,7 @@ export class DeleteAndAggregateFacet {
opCtx.ast = { object, ...(options?.where !== undefined ? { where: options.where } : {}) } as QueryAST;
}

await this.executeWithMiddleware(opCtx, async () => {
await this.executeWithMiddleware(opCtx, inOwnUnit(async () => {
// [ADR-0139 D1] As in `update`: a leaf the middleware chain wrote into a
// delete's predicate is refused at the executor's entry, before the
// pre-image reads reach the driver.
Expand Down Expand Up @@ -930,7 +936,7 @@ export class DeleteAndAggregateFacet {
);
throw e;
}
});
}));

return opCtx.result;
}
Expand Down
8 changes: 7 additions & 1 deletion packages/objectql/src/engine-hook-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,13 @@ export interface HookDispatchHost {
transaction: ObjectQL['transaction'];
}

/** [#22782] The unit {@link opensAfterAbortUnit} asked for; `write` re-enters the door, which joins it. */
/**
* [#22782] The unit {@link opensAfterAbortUnit} asked for. `write` is the write
* door's engine body — the executor `insert`, `update` and `delete` each hand
* the middleware chain (#35142, #35167) — so the chain, the authorization gate
* included, runs before the unit opens and after it closes, and the `before*`
* hooks' `ctx.api` writes, the row and the `after*` chain run inside it.
*/
export async function inAfterAbortUnit<T>(
this: Pick<HookDispatchHost, 'transaction'>,
write: () => Promise<T>,
Expand Down
19 changes: 13 additions & 6 deletions packages/objectql/src/engine-insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,13 +324,20 @@ export class InsertFacet {
}

/** The body of `ObjectQL#insert`; the method's docblock there is its contract. */
static async insert(this: Pick<InsertHost, '_registry' | 'admittedViolationSink' | 'applyAutonumbers' | 'applyFieldDefaults' | 'assertReferencesResolve' | 'assertWriteAllowed' | 'assignment' | 'autonumberCounters' | 'buildDriverOptions' | 'buildEvalUser' | 'buildHookApi' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'createWithAutonumberResync' | 'encryptSecretFields' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'formulaFaultSink' | 'formulaOptionLabels' | 'getDriver' | 'getSchema' | 'getSummaryDescriptors' | 'homeAmountServing' | 'inAfterAbortUnit' | 'initializeSummaryFields' | 'insert' | 'insertRecomputeListeners' | 'invalidateOrganizationProbe' | 'isIssuedAutonumberCollision' | 'logger' | 'mediaValueShapeStrictFor' | 'opensAfterAbortUnit' | 'permissionResolution' | 'persistSecretRows' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'refuseEmptyPasswordFields' | 'releaseSecretHandles' | 'resolveDefaultPermissions' | 'resolveFormulaPermissions' | 'resolveFormulaRelated' | 'resolveMasterDetailParents' | 'resolveObjectName' | 'resolveOptionPermissions' | 'resolvePredicateRelated' | 'resolveSystemInsertOrganization' | 'staticReadonlyCreateStrip' | 'triggerHooks' | 'validationMessageContext' | 'valueShapeStrictFor' | 'warnAutonumberReadersUnserved'>, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise<any> {
static async insert(this: Pick<InsertHost, '_registry' | 'admittedViolationSink' | 'applyAutonumbers' | 'applyFieldDefaults' | 'assertReferencesResolve' | 'assertWriteAllowed' | 'assignment' | 'autonumberCounters' | 'buildDriverOptions' | 'buildEvalUser' | 'buildHookApi' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'createWithAutonumberResync' | 'encryptSecretFields' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'formulaFaultSink' | 'formulaOptionLabels' | 'getDriver' | 'getSchema' | 'getSummaryDescriptors' | 'homeAmountServing' | 'inAfterAbortUnit' | 'initializeSummaryFields' | 'insertRecomputeListeners' | 'invalidateOrganizationProbe' | 'isIssuedAutonumberCollision' | 'logger' | 'mediaValueShapeStrictFor' | 'opensAfterAbortUnit' | 'permissionResolution' | 'persistSecretRows' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'refuseEmptyPasswordFields' | 'releaseSecretHandles' | 'resolveDefaultPermissions' | 'resolveFormulaPermissions' | 'resolveFormulaRelated' | 'resolveMasterDetailParents' | 'resolveObjectName' | 'resolveOptionPermissions' | 'resolvePredicateRelated' | 'resolveSystemInsertOrganization' | 'staticReadonlyCreateStrip' | 'triggerHooks' | 'validationMessageContext' | 'valueShapeStrictFor' | 'warnAutonumberReadersUnserved'>, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise<any> {
object = this.resolveObjectName(object);
// [#22782, #34412] An aborting `afterInsert`, or a refusal after a `beforeInsert` hook's
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
if (this.opensAfterAbortUnit('afterInsert', object, options?.context)) {
return this.inAfterAbortUnit(() => this.insert(object, data, options));
}
//
// [#35167] The unit opens around the ENGINE BODY (the executor below), as
// `update`'s does (#35142): the middleware chain runs first, outside it, as
// it does for an insert that opens no unit, so the authorization gate's
// reads do not hold a single-connection store's (SQLite) only connection
// while they run, and a middleware's work after `next()` runs after the
// commit on every object. Nothing between here and the executor writes.
const ownUnit = this.opensAfterAbortUnit('afterInsert', object, options?.context);
const inOwnUnit = <T>(body: () => Promise<T>): (() => Promise<T>) =>
ownUnit ? () => this.inAfterAbortUnit(body) : body;
this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) });
this.assertWriteAllowed(object, 'insert');
// [#8844] The organization set is about to change. Dropped BEFORE the write
Expand Down Expand Up @@ -366,7 +373,7 @@ export class InsertFacet {
context: options?.context,
};

await this.executeWithMiddleware(opCtx, async () => {
await this.executeWithMiddleware(opCtx, inOwnUnit(async () => {
// Resolve field `defaultValue`s (including the `current_user` and
// `NOW()` tokens)
// BEFORE the beforeInsert hook runs, so a hook that DERIVES one field
Expand Down Expand Up @@ -1742,7 +1749,7 @@ export class InsertFacet {
await this.releaseSecretHandles(object, writtenSecrets, opCtx.context, 'refused');
throw e;
}
});
}));

return opCtx.result;
}
Expand Down
10 changes: 5 additions & 5 deletions packages/objectql/src/engine-middleware-and-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,11 @@ export class MiddlewareAndContextFacet {
* contract, so a handler reads `ctx.referentialCascadeDelete === true`.
*
* Reads {@link cascadeIssuedDeletes}, not the envelope (that field says why),
* and CLAIMS the token it matches. Called once per `delete()`, below the
* `afterDelete` unit re-entry (`opensAfterAbortUnit`): a call that re-enters
* itself returns before reaching here, so the claim is made by the inner
* call, the one that dispatches the hooks, and nothing later inside it can
* match the same token again.
* and CLAIMS the token it matches. Called once per `delete()`, before the
* middleware chain; no `delete()` re-enters itself (its `afterDelete` unit
* opens around the executor, `opensAfterAbortUnit`), so the claim is made by
* the call that dispatches the hooks, and nothing later inside it can match
* the same token again.
*/
static claimReferentialCascadeDelete(this: Pick<MiddlewareAndContextHost, 'cascadeIssuedDeletes'>, object: string, id: unknown): true | undefined {
const issued = this.cascadeIssuedDeletes.getStore();
Expand Down
13 changes: 8 additions & 5 deletions packages/objectql/src/engine-top-level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,18 @@ export interface AdmittedValueShapeViolationTally {
* in, and an in-engine audit hook depends on landing inside it.
*
* Four ordinary paths open such a unit around the dispatch:
* - the write door itself, when the object has a metadata-bound `after*`
* hook that can abort — blocking with `onError` `abort`, or carrying a
* `condition` — so that abort rolls the row back as `HookSchema.onError`
* says (#22782, #22856, `opensAfterAbortUnit`);
* - the write's own engine body, when the object has a metadata-bound
* `after*` hook that can abort — blocking with `onError` `abort`, or
* carrying a `condition` — so that abort rolls the row back as
* `HookSchema.onError` says (#22782, #22856, `opensAfterAbortUnit`). One
* rule for `insert`, `update` and `delete`: the unit opens around the
* executor, inside the middleware chain, so a middleware's work before
* and after `next()` runs outside it (#35142, #35167);
* - a by-id {@link ObjectQL.delete} whose cascade is `'atomic'` — each
* dependent's own `afterDelete` fires inside the wrap the parent opened,
* and the parent's row removal can still refuse afterwards (#7413). The
* PARENT's `afterDelete` is outside that wrap by construction (inside the
* door's own unit when the first path opened one); the cascaded
* write's own unit when the first path opened one); the cascaded
* CHILDREN's are not;
* - `runAtomicBatch` in `@objectstack/metadata-protocol` —
* `batchData`/`deleteManyData` with `atomic: true` runs every member's
Expand Down
Loading
Loading