Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/34412-before-hook-side-write-unit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/objectql': minor
---

fix(objectql)!: a write refused after its `before*` hook wrote through `ctx.api` no longer keeps that hook's write

Clause-②: no (narrowing)
Metadata-protocol: semantic

<!-- adr-0087: not-required (no-migration-prescription) No metadata moves: no spec key, authorable spelling, export or stored shape is removed, renamed or re-shaped, so there is nothing for `objectstack migrate meta` to rewrite. A hook that loaded before keeps its authored shape. What changes is the meaning of a declared `before*` hook: the write door now opens its unit of work for it, so the hook's `ctx.api` writes roll back with a refused write and the rules of any unit apply on more objects. The other categories are closed on facts: the package publishes (not unpublished); no ADR-0087 id is named or touched (not registered or already-registered); and no exported declaration is removed or narrowed (not runtime-interface-only or type-surface-only). -->

**BREAKING** stored-outcome narrowing, shipped as `minor` under the launch-window convention for breaking changes.

- **FROM:** `insert` / `update` / `delete` (REST `createData` / `updateData` / `deleteData`, `ctx.api`, the engine door, single and predicate writes) on an object whose `before*` hook for that verb is bound from metadata, and that has no `after*` hook able to abort. The write door opened no unit of work. A `before*` hook that wrote another record through `ctx.api` committed that write at once, so when the write was refused later in the same call (a declared validation, a later `before*` hook, a driver constraint), the caller was refused and the hook's record stayed stored. Example: a `beforeInsert` hook on a time entry creates the week's timesheet, the entry is refused by `hours > 24`, and an empty timesheet remains.
- **TO:** a `beforeInsert`, `beforeUpdate` or `beforeDelete` hook bound from metadata opens the write door's unit for writes of its verb, whatever its `onError`. A refusal anywhere in that write rolls back the row and every `ctx.api` write the hook chain made. The caller is refused exactly as before. Hook count and order are unchanged.
- **A `before*` write meant to survive a refusal now rolls back.** There is no per-hook opt-out: `onError: 'log'` decides only whether the hook's own throw refuses the write, not whether its writes survive a refusal elsewhere. The one exception is an append-only ledger on another datasource (an object whose `lifecycle.class` is `audit`, `telemetry` or `event`), which is written outside the unit and survives the rollback, as in any unit. **Fix, if you relied on it:** record the attempt from an `after*` hook with `async: true` (it runs only after a commit), or record it where the write is made.
- **Inside the new unit, the rules of any unit apply,** so writes that were accepted are now refused on objects carrying such a hook:
- A `before*` hook whose body writes a business row to an object on another datasource has that write refused with `CrossDatasourceTransactionWriteError`, and the outer write is refused with it. **Fix:** keep the objects the hook writes on the default datasource.
- A MongoDB default store needs a replica set for this unit, as it does for `transaction()` and for the `after*` unit already (read in the driver's code: it always opens a session transaction; not measured on a standalone server). **Fix:** run MongoDB as a replica set.
- A `ctx.api.transaction(...)` a `before*` hook opens joins the door's unit instead of committing on its own, and an `async: true` `after*` hook on the same write starts after the unit commits.
- On PostgreSQL a statement that fails at the database aborts the whole unit (`25P02`, "current transaction is aborted"), and the unit takes no savepoint around a hook's `ctx.api` write. So a `before*` hook whose `ctx.api` statement fails there (a constraint, a type error) now refuses the outer write even when the hook body catches the error, `onError: 'log'` swallows it, or its `retryPolicy` re-runs it; that write was stored before. Read in the driver's code, not measured on PostgreSQL; the measurement is carried on #34563. **Fix:** check the condition before the hook writes, or make that write from an `after*` hook with `async: true`.
- **Unchanged:** a write already inside a unit (a caller's `transaction()`, an atomic batch or cascade) joins it, and that unit's owner still decides. No unit is opened for a hook registered in code with `registerHook` (the platform's own audit stamps among them), a write with `skipAutomations`, an object whose datasource is not the default one, or a default driver with no transactions (ADR-0119 D1, such as a libSQL remote transport). On those a `before*` hook's writes stay stored after a refusal, as the refusal's message says.
- **Cost:** one transaction per write on objects that carry such a hook. On SQLite the write lock is held through the whole `before*` chain, including awaited work inside the hooks. Objects without such a hook pay one map lookup.
2 changes: 1 addition & 1 deletion content/docs/api/data-flow.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ The lifecycle events are defined by the `HookEvent` enum (8 events). Reads fire

| Hook | Phase | Can Modify? | Can Abort? |
|:---|:---|:---|:---|
| `beforeInsert/Update/Delete` | Pre-persist | ✅ Yes (mutate `input`) | ✅ Yes (throw with `onError: 'abort'`) |
| `beforeInsert/Update/Delete` | Pre-persist, inside the write's unit of work when the hook is declared in metadata | ✅ Yes (mutate `input`) | ✅ Yes (throw with `onError: 'abort'`): the write is refused, and every `ctx.api` write the `before*` hooks made rolls back with it, as it does on any later refusal in the same write. On an object outside the default datasource, or on a driver with no transactions, those writes stay stored — see [After hooks run inside the unit of work](/docs/automation/hooks#after-hooks-run-inside-the-unit-of-work) |
| `afterInsert/Update/Delete` | Post-persist, before the unit of work commits | ✅ Yes (mutate `result`) | ✅ Yes (a blocking hook that throws with `onError: 'abort'`, the default): the write is refused and rolled back. On an object outside the default datasource, or on a driver with no transactions, the caller is refused but the row stays stored — see [After hooks run inside the unit of work](/docs/automation/hooks#after-hooks-run-inside-the-unit-of-work) |

<Callout type="tip">
Expand Down
23 changes: 21 additions & 2 deletions content/docs/automation/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -309,11 +309,12 @@ hook, the default. An `async: true` hook is dispatched there too, but does not
run there: see [`async: true` after hooks run after the
commit](#async-true-after-hooks-run-after-the-commit).

Four ordinary operations put a write inside such a unit:
Five ordinary operations put a write inside such a unit:

| Operation | What is inside the transaction |
| :--- | :--- |
| Any write to an object with an `after*` hook that can abort it: a blocking one whose `onError` is `abort` (the default), or one carrying a `condition`, whatever its `onError` and `async` (a condition that cannot be evaluated aborts the write) | The write and every `after*` hook it dispatches, so that hook's abort rolls the row back. Not opened on an object outside the default datasource, or on a driver with no transactions: there the row stays stored after an abort |
| Any write to an object with a `before*` hook on the same verb (`beforeInsert` for an insert, `beforeUpdate` for an update, `beforeDelete` for a delete), declared in metadata, whatever its `onError` | The write, its `before*` hooks and every `ctx.api` write they make, so a refusal later in the same write (a declared validation, a later `before*` hook, a driver constraint) rolls those writes back with it. Not opened on an object outside the default datasource, or on a driver with no transactions: there a `before*` hook's writes stay stored after a refusal. A hook registered in code with `registerHook` opens no unit |
| A by-id `delete()` that cascades to dependent records | Each **cascaded child's** `afterDelete`. The parent's own `afterDelete` runs after that unit closes, unless the row above opened one around the whole delete |
| `batchData` / `deleteManyData` with `atomic: true` | Every member's `after*` — the batch aborts and rolls back on the first failure |
| Any write you wrapped yourself in `ctx.api.transaction(...)` or `engine.transaction(...)` | Everything in the callback |
Expand All @@ -332,7 +333,25 @@ What this means when you write a blocking handler:
event on its own.

Before hooks carry no such caveat: they run before the write is issued, and
throwing from one refuses the operation outright.
throwing from one refuses the operation outright. A `before*` hook's own
`ctx.api` writes are inside the unit its row of the table above opens, so they
follow the same rules: a refusal anywhere in the write rolls them back, with no
per-hook opt-out, and a write to an object on another datasource is refused
with `CrossDatasourceTransactionWriteError`. The one exception is an
append-only ledger on another datasource (an object whose `lifecycle.class` is
`audit`, `telemetry` or `event`): it is written outside the unit and survives
the rollback. Keep the objects a `before*` hook
writes on the default datasource; on MongoDB, run it as a replica set, which
any unit needs.

On PostgreSQL a statement that fails at the database aborts the whole unit
(`25P02`, "current transaction is aborted"), and the unit takes no savepoint
around a hook's `ctx.api` write. A `before*` hook whose `ctx.api` statement
fails there therefore refuses the write it belongs to, even when the hook body
catches the error, `onError: 'log'` swallows it, or its `retryPolicy` re-runs
it. Check the condition before writing, or make that write from an `after*`
hook with `async: true` (not yet measured on PostgreSQL; tracked in
[#34563](https://github.com/objectstack-ai/objectstack/issues/34563)).

<Callout type="info">
For a blocking hook this is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)),
Expand Down
91 changes: 87 additions & 4 deletions packages/objectql/src/engine-after-hook-abort-unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
* Before this, a plain write opened no unit of work, so a throwing
* `afterInsert` refused the caller while the row, and the `ctx.api` write an
* earlier hook made, stayed stored. The write door now opens a unit for exactly
* that case (`inAfterAbortUnit`); every other write opens none, which the
* `begun` ledger below measures.
* that case (`inAfterAbortUnit`), and since #34412 for a metadata-bound
* `before*` hook too (the last describe); every other write opens none, which
* the `begun` ledger below measures.
*
* The driver rolls back for real (a snapshot per transaction): a stub whose
* `rollback()` is a no-op cannot tell "wrapped" from "not wrapped".
Expand Down Expand Up @@ -120,11 +121,11 @@ describe('#22782 — an aborting after* hook rolls its write back', () => {
expect(driver.begun).toHaveLength(0);
});

it('CONTROL a throwing before* hook — refused, nothing stored, no unit opened', async () => {
it('a throwing before* hook — refused, nothing stored; the unit its chain opens rolls back (#34412)', async () => {
const { engine, driver } = await makeEngine([hook('veto', ['beforeInsert'], boom)]);
await expect(engine.insert('case', { name: 'c1' })).rejects.toThrow('refused by the hook');
expect(driver.rowsOf('case')).toEqual([]);
expect(driver.begun).toHaveLength(0);
expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 1]);
});

it('CONTROL inside a caller-opened transaction() — it joins (one unit), and the caller decides', async () => {
Expand Down Expand Up @@ -237,3 +238,85 @@ describe('#22856 — an after* hook carrying a condition rolls its write back wh
expect(driver.begun).toHaveLength(0);
});
});

/**
* #34412 — a `before*` hook that writes through `ctx.api` makes a write of its
* own before the outer row is stored. A refusal later in the same write (a
* declared validation, a later `before*` hook) used to leave that side write
* stored, because a single write opened no unit unless an aborting `after*`
* hook existed. A metadata-bound `before*` hook now opens the door's unit too,
* so the refusal rolls the side write back with the write.
*/
describe('#34412 — a refused write rolls back the ctx.api write its before* hook made', () => {
/** `case` with a declared validation that refuses `hours > 24` — the card's `crm_time_entry` rule. */
async function makeHoursEngine(hooks: Hook[], opts: { transactional?: boolean } = {}) {
const made = await makeEngine([], opts);
made.engine.registry.registerObject({
...obj('case', { hours: { name: 'hours', type: 'number' } }),
validations: [{ name: 'max_hours', type: 'script', condition: 'record.hours > 24', message: 'hours must be 24 or less', severity: 'error' }],
} as any, '__test__');
bindHooksToEngine(made.engine, hooks, { packageId: 'app:t', logger: { debug() {}, info() {}, warn() {}, error() {} } as any });
return made;
}
/** The card's hook: it creates a row on another object through `ctx.api`. */
const sideWriter = (events: string[]) =>
hook('side_writer', events, (ctx) => ctx.api.object('note').insert({ name: `from-${ctx.event}` }), { priority: 10 });
const refusal = (p: Promise<unknown>) => p.then(() => null, (e) => e);

it('beforeInsert writes a note, the declared validation refuses the row: the note is absent', async () => {
const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]);
expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' });
expect(driver.rowsOf('case')).toEqual([]);
expect(driver.rowsOf('note')).toEqual([]);
expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 1]);
});

it('beforeUpdate writes a note, the declared validation refuses the patch: the note is absent, the row unchanged', async () => {
const { engine, driver } = await makeHoursEngine([sideWriter(['beforeUpdate'])]);
const row = await engine.insert('case', { name: 'c1', hours: 3 });
expect(await refusal(engine.update('case', { hours: 30 }, { where: { id: row.id } } as any))).toMatchObject({ code: 'VALIDATION_FAILED' });
expect(driver.rowsOf('case')).toMatchObject([{ id: row.id, hours: 3 }]);
expect(driver.rowsOf('note')).toEqual([]);
});

it('beforeDelete writes a note, a later beforeDelete hook refuses: the note is absent, the row kept', async () => {
const { engine, driver } = await makeHoursEngine([sideWriter(['beforeDelete']), hook('veto', ['beforeDelete'], boom, { priority: 20 })]);
const row = await engine.insert('case', { name: 'c1', hours: 3 });
expect(await refusal(engine.delete('case', { where: { id: row.id } } as any))).toMatchObject({ message: expect.stringContaining('refused by the hook') });
expect(driver.rowsOf('case')).toMatchObject([{ id: row.id }]);
expect(driver.rowsOf('note')).toEqual([]);
});

it('CONTROL the write succeeds: the row and the note are both stored, the unit commits', async () => {
const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]);
await engine.insert('case', { name: 'c1', hours: 3 });
expect(driver.rowsOf('case')).toMatchObject([{ name: 'c1', hours: 3 }]);
expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]);
expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 0]);
});

it('CONTROL inside a caller-opened transaction() — it joins (one unit), and the caller decides', async () => {
const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]);
await engine.transaction(async (trx: any) => {
expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }, { context: trx }))).toMatchObject({ code: 'VALIDATION_FAILED' });
});
expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 0]);
expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]);
});

it('CONTROL a driver with no transactions keeps the side write, as hookStoppedRefusal says, and warns nothing', async () => {
const { engine, driver, warns } = await makeHoursEngine([sideWriter(['beforeInsert'])], { transactional: false });
expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' });
expect(driver.rowsOf('case')).toEqual([]);
expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]);
expect(warns.filter((w) => w.includes('transaction'))).toEqual([]);
});

it('CONTROL a code-registered beforeInsert opens no unit — the #22782 line', async () => {
const { engine, driver } = await makeHoursEngine([]);
engine.registerHook('beforeInsert', async (ctx: any) => { await ctx.api.object('note').insert({ name: 'from-code' }); }, { object: 'case' });
expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' });
expect(driver.begun).toHaveLength(0);
expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-code' }]);
});
});
3 changes: 2 additions & 1 deletion packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ 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> {
object = this.resolveObjectName(object);
// [#22782] An aborting `afterDelete` rolls this write back — see `opensAfterAbortUnit`.
// [#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));
}
Expand Down
Loading
Loading