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
16 changes: 16 additions & 0 deletions .changeset/35028-trio-handle-owner.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/objectql': patch
---

fix(objectql)!: an action body's write inside `ctx.api.transaction` keeps its audit and activity rows beside a `telemetry` datasource, and a write it makes to an object on another datasource is refused

Clause-②: yes (narrowing) — narrowed: inside a transaction opened by `ScopedContext`'s discrete `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio (the sandbox's `ctx.api.transaction`), an `insert` / `update` / `delete` of a business object that resolves to a datasource other than the transaction's is now refused with `CrossDatasourceTransactionWriteError` (`ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, answered `400` at the action door) before anything runs; it used to run on the transaction's connection, the wrong one. The same write inside `transaction(cb)` was already refused.
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is whether a write under a trio-opened transaction handle may reach a driver that does not own that handle. The one-line fix for a refused write is in the body: keep every object written inside one ctx.api.transaction on one datasource, or split the work into one transaction per datasource. -->

**BREAKING** for an action, hook or job body whose `ctx.api.transaction` writes an object bound to a datasource other than the default one (an object `datasource:` binding or a `datasourceMapping` rule). That write is now refused, naming both datasources, and the body's transaction rolls back. Before, it ran on the default datasource's connection: on SQLite it failed with `no such table`, and on Postgres the failed statement turned the whole transaction's COMMIT into a rollback while the action answered success. The fix: keep every object written inside one `ctx.api.transaction` on one datasource, or split the work into one transaction per datasource and reconcile them yourself. A deployment with one datasource sees no change.

**The compliance rows.** On every deployment with a `telemetry` datasource — each `os dev` boot (the sibling SQLite file) and `os serve` with `OS_TELEMETRY_DB` — an action body's write inside `ctx.api.transaction` committed but lost its `sys_audit_log` and `sys_activity` rows: plugin-audit's ledger insert was handed the default datasource's transaction handle while routed to `telemetry`, and ran on the connection that has no such table. The API answered `200` and one `Audit write FAILED on sys_audit_log` line was the only trace. The rows now land, written on the `telemetry` datasource's own connection outside the body's transaction, exactly as they already were inside `transaction(cb)` (ADR-0119, amended 2026-08-06): a body transaction that rolls back keeps its ledger rows, the decided direction of error for an append-only ledger. The workaround `OS_TELEMETRY_DB=0` is no longer needed.

The trio records which driver owns each handle it opens, keyed by the handle and dropped at commit or rollback, and the same-origin gate reads that record for a handle the engine's ambient transaction store does not hold. An `async: true` hook's run, detached from the units open at its dispatch, is not judged against that record: its writes run outside any transaction, as they do under `transaction(cb)`. A handle the engine never opened, passed in as `execCtx.transaction`, is still unattributed and unjudged (ADR-0119's declared limit, narrowed by the 2026-11-18 note). No `IDataDriver` change.
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,38 @@ on that path, is pinned as such in
requires handle ownership to become discoverable on `IDataDriver` — a
driver-contract change, tracked separately.

**Note (2026-11-18, #35028) — the limit narrows to truly foreign handles.** The
trio half of the paragraph above no longer holds. A handle the trio opened is no
opaque object: `beginTransaction` takes it from the default driver, so its owner
is known at that moment. The trio now records the same `TransactionScope`
`transaction()` publishes, keyed by the handle and dropped when
`commitTransaction` or `rollbackTransaction` closes it
(`packages/objectql/src/engine-execute-transactions.ts#trioTransactionScopeOf`),
and both halves of the gate read that record for an explicitly-threaded handle
the store holds no scope for. So a trio handle gets exactly the 2026-08-06
answers: a cross-datasource business write is refused with
`CrossDatasourceTransactionWriteError`, and an append-only system ledger is
carved out — written outside the transaction, on its own connection. Measured
before it: an action body's write inside `ctx.api.transaction`, the sandbox's
face of the trio, lost its `sys_audit_log` and `sys_activity` rows on every
deployment with a `telemetry` datasource (`os dev`, and `os serve` with
`OS_TELEMETRY_DB`), because plugin-audit's ledger insert was handed the
primary's handle and ran on the primary connection, which has no such table. On
a Postgres primary the refused statement also turned the business transaction's
COMMIT into a rollback. What stays declared and unjudged is a handle the engine
never opened — one an outside caller obtained elsewhere and passed in as
`execCtx.transaction`. No `IDataDriver` change is needed for the trio, and the
driver-contract change above is still the only way to close the rest.

Two bounds on "exactly the 2026-08-06 answers". A handle the current run was
detached from is no open trio handle for that run: an `async: true` hook's run
starts outside every unit open at its dispatch while its `ctx.api` still
carries the handle (`packages/objectql/src/unit-detach.ts`), so the gate reads
that handle as `buildDriverOptions` does (`isClosedUnitHandle`) and judges the
run's writes as writes outside any transaction, which land. And the record is
keyed by the handle object, so a driver whose `beginTransaction` returned a
primitive handle would leave it unattributed; no in-tree driver does.

### Consumer impact

Single-datasource deployments — the overwhelming majority — see no change of any
Expand Down
2 changes: 1 addition & 1 deletion packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export class DeleteAndAggregateFacet {
// [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write,
// carve an append-only system ledger out of the transaction. Before any
// hook, default or validation runs, so a refusal costs nothing.
this.enforceTransactionOrigin(object, driver, 'delete');
this.enforceTransactionOrigin(object, driver, 'delete', options?.context?.transaction);

// Fold the `filter` alias into `where` first — same reasoning as update()
// above (#4346): unfolded, a `multi: true` delete with `{ filter }` had no
Expand Down
64 changes: 59 additions & 5 deletions packages/objectql/src/engine-execute-transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,51 @@ import type { IDataDriver } from '@objectstack/core';
import { redactPropagatedDriverFault } from '@objectstack/types';
import { CrossDatasourceTransactionWriteError } from './transaction-errors.js';
import { pickDeclaredDriverOptions } from './engine-driver-options.js';
import type { TransactionScope } from './engine-top-level.js';
import type { ObjectQL } from './engine.js';

/**
* [#35028] The owner of every transaction `ScopedContext`'s discrete
* `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio opened
* and has not yet closed, keyed by the handle.
*
* The trio cannot publish into the engine's `txStore`: its caller (the sandbox
* runner's `ctx.api.transaction`) threads the handle across event-loop turns
* that `AsyncLocalStorage` does not survive. But `beginTransaction` is the one
* place the owning driver IS known, so it records the same
* {@link TransactionScope} `runOpenedUnit` publishes, here, and the same-origin
* gate (`enforceTransactionOrigin`, `transactionCoversDriverFor`) reads it for
* an explicitly-threaded handle when the store holds no scope for it. Without
* it, a trio handle reached a driver that does not own it: a ledger row routed
* to the `telemetry` datasource ran on the primary's connection and was lost,
* and a cross-datasource business write ran on the wrong connection.
*
* Weak, so a handle that is never closed is never kept alive. Module-level
* because a handle is one driver connection's object, owned by one engine;
* the scope it maps to names that engine's driver and datasource.
*/
const trioTransactionScopes = new WeakMap<object, TransactionScope>();

/** [#35028] Record the owner of a handle the trio just opened. A primitive handle cannot key it and stays unattributed. */
export function recordTrioTransactionScope(handle: unknown, scope: TransactionScope): void {
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
trioTransactionScopes.set(handle, scope);
}
}

/** [#35028] Forget a trio handle's owner: its commit or rollback closed it. */
export function forgetTrioTransactionScope(handle: unknown): void {
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
trioTransactionScopes.delete(handle);
}
}

/** [#35028] The owner of an open trio handle, or `undefined` for any other handle. */
export function trioTransactionScopeOf(handle: unknown): TransactionScope | undefined {
if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return undefined;
return trioTransactionScopes.get(handle);
}

/**
* The `ObjectQL` members the functions below read — every one of them, and no
* other; each function's `this` is the `Pick` of the members IT reads. Each is
Expand All @@ -71,6 +114,7 @@ export interface ExecuteTransactionsHost {
getDriver: ObjectQL['getDriver'];
datasourceNameOf: ObjectQL['datasourceNameOf'];
isSystemLedgerObject: ObjectQL['isSystemLedgerObject'];
isClosedUnitHandle: ObjectQL['isClosedUnitHandle'];
}

/** The body of `ObjectQL#execute`; the method's docblock there is its contract. */
Expand Down Expand Up @@ -247,15 +291,25 @@ export function warnTransactionUnsupported(
* rolled-back write; the durable answer lives in ADR-0067/ADR-0119.
*/
export function enforceTransactionOrigin(
this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'logger'>,
this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'isClosedUnitHandle' | 'logger'>,
objectName: string,
driver: IDataDriver,
operation: 'insert' | 'update' | 'delete',
explicitTransaction?: unknown,
): void {
const scope = this.txStore.getStore()?.scope;
// No engine-owned transaction in scope (or a handle threaded explicitly by
// the sandbox trio, which this store never sees) — nothing to be outside
// of. See `transactionCoversDriverFor` for why that limit is declared.
// [#35028] The store holds no scope for a handle the `ScopedContext` trio
// opened (it threads the handle explicitly, across turns the store does not
// survive), so the trio's own record of the owner answers for it. A handle
// the current run was detached from (an `async` hook's run, `unit-detach.ts`)
// is no handle, exactly as `buildDriverOptions` reads it: the write runs
// outside any transaction, on its own connection, and is not judged.
const explicit = explicitTransaction !== undefined && !this.isClosedUnitHandle(explicitTransaction)
? explicitTransaction
: undefined;
const scope = this.txStore.getStore()?.scope ?? trioTransactionScopeOf(explicit);
// No engine-owned transaction in scope (or a handle the engine never opened
// and cannot attribute) — nothing to be outside of. See
// `transactionCoversDriverFor` for why that limit is declared.
if (!scope) return;
// Identity, not name: this is about riding the same connection.
if (driver === scope.driver) return;
Expand Down
2 changes: 1 addition & 1 deletion packages/objectql/src/engine-insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ export class InsertFacet {
// [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write,
// carve an append-only system ledger out of the transaction. Before any
// hook, default or validation runs, so a refusal costs nothing.
this.enforceTransactionOrigin(object, driver, 'insert');
this.enforceTransactionOrigin(object, driver, 'insert', options?.context?.transaction);

// [#20308] A blank on a non-string-typed column is `null` from here on —
// before the middleware, the caller snapshot, the defaults, the hooks and
Expand Down
25 changes: 15 additions & 10 deletions packages/objectql/src/engine-middleware-and-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import type { IPubSub } from '@objectstack/spec/contracts';
import { redactPropagatedDriverFault } from '@objectstack/types';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { isWriteEpochOperation } from './write-epoch.js';
import { trioTransactionScopeOf } from './engine-execute-transactions.js';
import { READABLE_IDS_WRITE_IN_FLIGHT } from './engine-readable-ids-permission-formula.js';
import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js';
import { isMissingTableError } from '@objectstack/metadata/errors';
Expand Down Expand Up @@ -415,16 +416,17 @@ export class MiddlewareAndContextFacet {
* `TransactionScope` (#5724) records the owner for every transaction the
* engine opens, and `transaction()` also threads that same handle down as
* `execCtx.transaction`, so the dominant explicit-threading path is covered
* by identity-matching the handle back to the store entry. What is NOT
* covered:
* by identity-matching the handle back to the store entry.
* `ScopedContext`'s discrete `beginTransaction`/`commit`/`rollback` trio
* threads its handle across `setImmediate` boundaries where
* AsyncLocalStorage does not survive, and so never populates txStore; but
* the trio knows the owning driver at `beginTransaction`, and records it
* until the handle closes (`trioTransactionScopeOf`, #35028), so its
* handles are attributed by that record instead. What is NOT covered is
* any handle an outside caller obtained elsewhere and passed in as
* `execCtx.transaction`.
*
* - `ScopedContext`'s discrete `beginTransaction`/`commit`/`rollback` trio,
* which threads the handle across `setImmediate` boundaries where
* AsyncLocalStorage does not survive, and so never populates txStore;
* - any handle an outside caller obtained elsewhere and passed in as
* `execCtx.transaction`.
*
* For those the engine holds an opaque driver object with no back-reference
* For that one the engine holds an opaque driver object with no back-reference
* to its driver, so there is no honest comparison to make. Guessing — say,
* assuming an unattributed handle belongs to the default driver — would
* refuse legitimate single-datasource work on one side and carve out writes
Expand All @@ -437,7 +439,10 @@ export class MiddlewareAndContextFacet {
const store = this.txStore.getStore();
// The scope describes the handle in the store. An explicitly-threaded
// handle is covered by it only when it IS that handle.
const scope = store !== undefined && tx === store.transaction ? store.scope : undefined;
// [#35028] Any other handle is attributed by the record `ScopedContext`'s
// discrete trio keeps for the handles it opened (its owner is known at
// `beginTransaction`); a handle it never opened stays unattributed.
const scope = store !== undefined && tx === store.transaction ? store.scope : trioTransactionScopeOf(tx);
if (!scope) return true;
return this.getDriver(object) === scope.driver;
}
Expand Down
38 changes: 30 additions & 8 deletions packages/objectql/src/engine-scoped-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { appAutomationElevationOf, markAppAutomationElevation, resolveUserAuthzG
import type { EngineTransactionInfo, EngineTransactionOptions } from '@objectstack/core';
import { rolledBackRefusal } from './summary-errors.js';
import { TransactionUnsupportedError } from './transaction-errors.js';
import { forgetTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js';
import { redactPropagatedDriverFault } from '@objectstack/types';
import { UnscopedHookApi } from './hook-run-as.js';
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
Expand Down Expand Up @@ -334,28 +335,49 @@ export class ScopedContextFacet {
// [#33760] The `async` after-hooks dispatched in this unit wait for the
// trio's own commit, or are dropped by its rollback (`unit-detach.ts`).
openTrioCommitQueue(trx);
// [#35028] The trio never publishes into `txStore`, so record here which
// driver owns the handle — the same scope `runOpenedUnit` publishes — for
// the same-origin gate to read when the handle comes back explicitly. A
// ledger row routed to another datasource then runs outside this
// transaction on its own connection, and a business write routed there is
// refused, exactly as inside `transaction(cb)`. Reached the same `as any`
// way as `runOpenedUnit`.
const engine = this.engine as any;
if (typeof engine?.newTransactionScope === 'function') {
recordTrioTransactionScope(trx, engine.newTransactionScope(driver));
}
const ctx = this.derive({ ...this.executionContext, transaction: trx });
return { ctx, handle: trx, owned: true };
}

/** The body of `ScopedContext#commitTransaction`; the method's docblock there is its contract. */
static async commitTransaction(this: Pick<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
if (this.releaseJoinedHandle(handle)) return;
const driver = this.txDriver();
if (!driver) return;
if (driver.commit) await driver.commit(handle);
else if (driver.commitTransaction) await driver.commitTransaction(handle);
// [#35028] Closed either way: a handle whose commit threw is no open unit.
try {
const driver = this.txDriver();
if (!driver) return;
if (driver.commit) await driver.commit(handle);
else if (driver.commitTransaction) await driver.commitTransaction(handle);
} finally {
forgetTrioTransactionScope(handle);
}
settleTrioCommitQueue(handle, true);
}

/** The body of `ScopedContext#rollbackTransaction`; the method's docblock there is its contract. */
static async rollbackTransaction(this: Pick<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
if (this.releaseJoinedHandle(handle)) return;
settleTrioCommitQueue(handle, false);
const driver = this.txDriver();
if (!driver) return;
if (driver.rollback) await driver.rollback(handle);
else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle);
// [#35028] Closed either way, as on the commit face.
try {
const driver = this.txDriver();
if (!driver) return;
if (driver.rollback) await driver.rollback(handle);
else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle);
} finally {
forgetTrioTransactionScope(handle);
}
}

/** The body of `ScopedContext#serveFormulaField`; the method's docblock there is its contract. */
Expand Down
Loading
Loading