Skip to content

Commit a6cf988

Browse files
fix(objectql)!: an action body's write inside ctx.api.transaction keeps its audit rows beside a telemetry datasource (#35102)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ Fixes #35028 Clause-②: yes (narrowing) — inside a transaction opened by `ScopedContext`'s discrete begin/commit/rollback trio (the sandbox's `ctx.api.transaction`), a business write to an object on another datasource is now refused with `CrossDatasourceTransactionWriteError` (`ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, 400 at the action door). Before, it ran on the transaction's connection, the wrong one. Metadata-protocol: none Skills-docs: follow-up #35117 (the `api.transaction` row: one datasource per body transaction; a write to an object on another datasource is refused) > **BREAKING** for an action, hook or job body whose `ctx.api.transaction` writes an object bound to a non-default datasource. That write is now refused, naming both datasources, and the body's transaction rolls back. Fix: keep every object written inside one `ctx.api.transaction` on one datasource, or split the work per datasource. Single-datasource deployments see no change. ADR-0087 disposition (in the changeset): not-required (no-migration-prescription). ## 维护者速读 - 改了什么:沙箱 `ctx.api.transaction` 打开的事务句柄,现在在开启时记下归属的驱动;同源闸门据此判断,审计/动态行写到 telemetry 库自己的连接,跨库业务写被拒。 - 为什么改:有 telemetry 数据源时(每个 `os dev`、带 `OS_TELEMETRY_DB` 的 `os serve`),动作体事务里的写入丢失审计行和动态行,接口仍回 200。 - 风险与回滚:动作体事务里写另一个数据源上的业务对象,从"写错连接"变为 400 拒绝;单数据源不变。回滚即 revert 本 PR。 - 先看:`packages/objectql/src/engine-scoped-context.ts`(beginTransaction 记录、commit/rollback 清除)、`packages/objectql/src/engine-execute-transactions.ts`(记录表与 enforceTransactionOrigin)、`packages/objectql/src/engine-middleware-and-context.ts`(transactionCoversDriverFor)。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-transaction-same-origin.test.ts`,预期 29 个用例全绿。 - 需要你做的:Tier H(改了 `docs/adr/**`),需 os-zhuang 在当前 head 上 APPROVED 审核。 ## What changes - `ScopedContext.beginTransaction` records the opened handle's owner (the same `TransactionScope` that `transaction(cb)` publishes), keyed by handle in a WeakMap. `commitTransaction` and `rollbackTransaction` drop it, also when the driver call throws. - When `txStore` holds no scope for the handle, `transactionCoversDriverFor` and `enforceTransactionOrigin` read that record. So ledger rows (`sys_audit_log`, `sys_activity`) take the existing #5351 carve-out: written on `telemetry`, outside the body transaction, on their own connection. A cross-datasource business write is refused before any hook runs. - `enforceTransactionOrigin` takes the write's explicit handle (`options.context.transaction`) as a fourth argument. That puts four one-line call-site edits outside the claim's file surface: `engine.ts` (the private wrapper), `engine-insert.ts`, `engine-update.ts` and `engine-delete-and-aggregate.ts`. Route A needs them, because the gate cannot otherwise see the handle. - ADR-0119: an add-only dated note under "The declared LIMIT of the same-origin gate". It narrows the limit to handles the engine never opened. The existing paragraph is not rewritten. - The optional plugin-audit fix-text change was not made. With this fix, the platform's own trio no longer produces that third cause. - No `IDataDriver` or `packages/spec` change. The sudo() `'action'` elevation-mark defect (#35052) is not touched. - Contract review S1 (fix round): `enforceTransactionOrigin` now discards an explicit handle the current run was detached from before it reads the trio record, with the same predicate the structural half uses (`isClosedUnitHandle`, `engine-driver-options.ts`). An `async: true` `afterFind` run starts outside every open unit while its `ctx.api` still carries the trio handle; before this, its cross-datasource business write was refused although `buildDriverOptions` ran it outside any transaction. It now lands on its own connection, as it does under `transaction(cb)`. The ADR-0119 note gains an add-only paragraph bounding "exactly the 2026-08-06 answers" (the detached run, and review nit N1: a primitive handle stays unattributed); the changeset gains one sentence. Nit N2 (a closed trio handle reverts to unattributed rather than closed) is unchanged here; the seat files its follow-up. ## Why Reading 6964984927 measured this on `origin/main`. The trio never publishes into `txStore`, so both same-origin gates stepped aside. plugin-audit's `api.sudo()` insert carried the body's primary handle to the telemetry driver, and the statement ran on the primary connection, which has no `sys_audit_log`. On a Postgres primary, the refused statement turned COMMIT into a rollback. ## Tests Pins (seat ruling) and their ablations, each run through `scripts/ablation-replace.mjs`. Every ablation landed (anchor 1 to 0, blob changed) and was restored (blob equals HEAD, `git diff HEAD` empty). The dist legs were proved with `ablation-dist-preflight.mjs` (`--absent` on mutate, present after the restore rebuild). | Pin | Where | Ablation | Result | |---|---|---|---| | 1 engine: trio ledger rows land on telemetry with no foreign handle; carve-out noted once; rollback keeps the orphan row | `engine-transaction-same-origin.test.ts`, new describe "a handle the ScopedContext trio opened is attributed to its owner (#35028)" | A: drop the `recordTrioTransactionScope` call | 5 red of 28 | | 1 runtime: action-body write in tx with plugin-audit on a split engine keeps sys_audit_log + sys_activity | `packages/qa/dogfood/test/action-body-transaction-audit-split.dogfood.test.ts` (bootStack + real AuditPlugin + `telemetry` DriverPlugin, real `/actions` door) | A on dist (objectql rebuilt) | 3 of 3 red | | 1 runtime (knex better-sqlite3, os dev primary) | `packages/runtime/src/sandbox/action-body-transaction-rollup-child.integration.test.ts`, split case | A on dist | split case red | | 2 single datasource: trio rides one handle, audit rolls back with it | new nested describe in the same objectql file; existing :558 case kept, comment reworded (title unchanged) | C: record a foreign owner | the single-datasource trio case red (plus 4 split cases) | | forget on commit / rollback | objectql file | B1 / B2: drop the forget in commit / rollback | 1 red each | | 3 cross-datasource business write refused, named | objectql file (insert, update, delete) + dogfood (`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, message names the object) | A | red | | 4 #34998 stall regression: body tx inserting a roll-up master-detail child completes inside the wall clock on SQLite | runtime file, single + split, bound 10 s | D: `transactionCoversDriverFor` returns false (business writes leave the handle and wait on SQLite's one connection) | both red at 30 s, with the #34998 signature: "exceeded wall-clock ceiling of 30000ms while awaiting host calls (after 3597 pump iterations)" | | S1 detached `async` `afterFind` run: its cross-datasource business write under an open trio handle lands, with no handle | objectql file, "lets an async afterFind run, detached from the open trio handle, write a business object on another datasource" | E: replace `!this.isClosedUnitHandle(explicitTransaction)` with `true` | 1 red of 29: `CrossDatasourceTransactionWriteError` received instead of `stored` | | 5 live pg: an off-origin ledger write neither aborts the business tx nor rolls back on commit | runtime file, `describe.skipIf(!OS_TEST_POSTGRES_URL)`, pg primary + SQLite telemetry | A on dist | both red: 25P02 "current transaction is aborted" for two inserts; one insert answered 200 with 0 lines on disk (silent rollback) | S1 was measured before it was fixed: the new pin, run on `1ea3deab98` with no code change, failed 1 of 29 with `FAILED CrossDatasourceTransactionWriteError: insert of 'ledger' inside transaction() resolves to datasource 'ledger_db', but the transaction is open on 'primary'`. With the guard (`fe13609b7b`) the file passes 29 of 29. Ablation E ran through `ablation-replace.mjs` (anchor 1 to 0, blob `9ed8195b6c32` to `c224861e208a`), went red as above, and was restored (blob equals HEAD, `git diff HEAD` empty). A first attempt with a replacement that was a substring of the anchor was refused by the tool before any test ran. The objectql tests import the source, so no dist leg applies. Fix-round suites on head `91960c4f5a`: - objectql `test`: 610 files / 13733 tests passed (`VERDICT command-exit 0`). - objectql `typecheck`: exit 0. Package suites on head `1ea3deab98` (previous round), all run in one locked chain: - objectql `test`: 610 files / 13732 tests passed (exit 0). - objectql `typecheck`: exit 0. - runtime `typecheck`: exit 0. - Runtime pins plus the two neighbouring transaction suites, with live pg: 3 files / 16 tests passed (exit 0). ## Live probe (re-run of the reader's probe, `os dev --fresh` on a probe app) "Before" is origin/main's objectql source (`1282a464e9`) rebuilt. "After" is this branch. | Layout | tx-1 / tx-2 audit | sys_audit_log rows | sys_activity rows | `Audit write FAILED` lines | |---|---|---|---|---| | before, split (default) | NO AUDIT ROW / NO AUDIT ROW | 5 | 2 | 1 | | after, split | create / create (+ rollback orphan row) | 8 | 4 | 0 | | before, `OS_TELEMETRY_DB=0` | create / create | 7 | 4 | 0 | | after, `OS_TELEMETRY_DB=0` | create / create (rollback leaves none) | 7 | 4 | 0 | ## Acceptance notes - After the fix, the split layout keeps the rolled-back body transaction's audit row as an orphan row. This is the 2026-08-06 carve-out ruling applied to the trio; the single-datasource layout still rolls it back. - Four mechanical call-site edits are outside the claim's file surface (listed under What changes). - The test surface of the query-options erasure ratchet stays at 236: the new runtime file types its read options instead of using `as any`. ## Verification Fix-round readings, all taken on head `91960c4f5a` (the final head). Verified by repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt. No merge from `main`: `overlap-check` before each push merged cleanly against `origin/main` and the four PRs sharing files (#35124, #34978, #34817, #34709), and `main` is not red. Full build: `pnpm build --concurrency=2` under `os-verify-lock`, 120 of 120 tasks successful, `VERDICT command-exit 0`. Full dogfood battery (owed: `!` title + `(narrowing)` arm), no shard, no path filter: <details><summary>pnpm --filter @objectstack/dogfood test · exit 0 · 480 files / 4075 tests passed</summary> ```text Test Files 480 passed | 3 skipped (483) Tests 4075 passed | 68 skipped (4143) os-verify-lock: VERDICT command-exit 0 · held the lock 1777s (29m37s) · waited 0s ``` </details> <details><summary>pnpm --filter @objectstack/dogfood typecheck · exit 0</summary> ```text > tsc --noEmit os-verify-lock: VERDICT command-exit 0 · held the lock 26s ``` </details> Derived gate families (`node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`, run after the full build): <details><summary>82 derived · 82 run · 82 exit 0 · 0 NOT MEASURED</summary> ```text Run reconciliation — 82 derived, 82 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 82 derived famil(ies) accounted for — 82 run, 0 NOT-MEASURED (a DERIVED zero — all 82 recorded an exit code and none of them is 3). ``` The derivation warned that the local `origin/main` ref was 17 commits ahead of the merge base and that `scripts/check-skills-token-ratchet.mjs` changed in that range; that script is not one of this diff's families. </details> <details><summary>check-governed-merges --pr 35102 · exit 3 (GOVERNED, the expected answer)</summary> ```text governed-surface predicate: 1 of 12 path(s) hit the register (13 surfaces govern objectstack). GOVERNED · landing tier: H — the maintainer's hand, or an authorized APPROVED review (GOVERNED_APPROVERS) and then the owning seat lands it. docs/adr/** ×1 — docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md size: 793 changed line(s) (+758 / -35) ≤ 3000 — under the human-merge threshold. ``` </details> CI on head `91960c4f5a`: `Lint & Repo Gates`, `TypeScript Type Check`, `Build Core`, `Governed Surface Queue Guard`, `Live E2E UI`, `Test UI`, `Dogfood Regression Gate` and `Check Changeset` concluded `success`; `Test Core` 9 of 10 shards `success`. `Test Core (7/10)` failed on one test this diff does not reach: `plugin-security` `src/org-admin-assignment-boundary.posture.test.ts:1153` (orgAdminAuditorDelegate, posture 'isolated'), "Test timed out in 5000ms", the known flake signature tracked on #35111; no plugin-security path is in this diff. The `Lint & Repo Gates` and `TypeScript Type Check` reds on `fe13609b7b` were cancellation aggregates: that run was cancelled at 06:20Z when `91960c4f5a` was pushed, and every sub-lane reads `cancelled`. ## Still owed (seat) - The delta review of the S1 fix (contract review 6969574094 asked for one). - The follow-up card for review nit N2 (a closed trio handle reverts to unattributed rather than closed). - Tier H: os-zhuang's APPROVED review on the current head. No seat readies, queues or arms this PR before it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzfrh8TiPJf1i2kMSoa <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 99a0e4f commit a6cf988

12 files changed

Lines changed: 758 additions & 35 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
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
6+
7+
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.
8+
Metadata-protocol: none
9+
10+
<!-- 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. -->
11+
12+
**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.
13+
14+
**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.
15+
16+
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.

‎docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,38 @@ on that path, is pinned as such in
310310
requires handle ownership to become discoverable on `IDataDriver` — a
311311
driver-contract change, tracked separately.
312312

313+
**Note (2026-11-18, #35028) — the limit narrows to truly foreign handles.** The
314+
trio half of the paragraph above no longer holds. A handle the trio opened is no
315+
opaque object: `beginTransaction` takes it from the default driver, so its owner
316+
is known at that moment. The trio now records the same `TransactionScope`
317+
`transaction()` publishes, keyed by the handle and dropped when
318+
`commitTransaction` or `rollbackTransaction` closes it
319+
(`packages/objectql/src/engine-execute-transactions.ts#trioTransactionScopeOf`),
320+
and both halves of the gate read that record for an explicitly-threaded handle
321+
the store holds no scope for. So a trio handle gets exactly the 2026-08-06
322+
answers: a cross-datasource business write is refused with
323+
`CrossDatasourceTransactionWriteError`, and an append-only system ledger is
324+
carved out — written outside the transaction, on its own connection. Measured
325+
before it: an action body's write inside `ctx.api.transaction`, the sandbox's
326+
face of the trio, lost its `sys_audit_log` and `sys_activity` rows on every
327+
deployment with a `telemetry` datasource (`os dev`, and `os serve` with
328+
`OS_TELEMETRY_DB`), because plugin-audit's ledger insert was handed the
329+
primary's handle and ran on the primary connection, which has no such table. On
330+
a Postgres primary the refused statement also turned the business transaction's
331+
COMMIT into a rollback. What stays declared and unjudged is a handle the engine
332+
never opened — one an outside caller obtained elsewhere and passed in as
333+
`execCtx.transaction`. No `IDataDriver` change is needed for the trio, and the
334+
driver-contract change above is still the only way to close the rest.
335+
336+
Two bounds on "exactly the 2026-08-06 answers". A handle the current run was
337+
detached from is no open trio handle for that run: an `async: true` hook's run
338+
starts outside every unit open at its dispatch while its `ctx.api` still
339+
carries the handle (`packages/objectql/src/unit-detach.ts`), so the gate reads
340+
that handle as `buildDriverOptions` does (`isClosedUnitHandle`) and judges the
341+
run's writes as writes outside any transaction, which land. And the record is
342+
keyed by the handle object, so a driver whose `beginTransaction` returned a
343+
primitive handle would leave it unattributed; no in-tree driver does.
344+
313345
### Consumer impact
314346

315347
Single-datasource deployments — the overwhelming majority — see no change of any

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ export class DeleteAndAggregateFacet {
161161
// [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write,
162162
// carve an append-only system ledger out of the transaction. Before any
163163
// hook, default or validation runs, so a refusal costs nothing.
164-
this.enforceTransactionOrigin(object, driver, 'delete');
164+
this.enforceTransactionOrigin(object, driver, 'delete', options?.context?.transaction);
165165

166166
// Fold the `filter` alias into `where` first — same reasoning as update()
167167
// above (#4346): unfolded, a `multi: true` delete with `{ filter }` had no

‎packages/objectql/src/engine-execute-transactions.ts‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,51 @@ import type { IDataDriver } from '@objectstack/core';
5252
import { redactPropagatedDriverFault } from '@objectstack/types';
5353
import { CrossDatasourceTransactionWriteError } from './transaction-errors.js';
5454
import { pickDeclaredDriverOptions } from './engine-driver-options.js';
55+
import type { TransactionScope } from './engine-top-level.js';
5556
import type { ObjectQL } from './engine.js';
5657

58+
/**
59+
* [#35028] The owner of every transaction `ScopedContext`'s discrete
60+
* `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio opened
61+
* and has not yet closed, keyed by the handle.
62+
*
63+
* The trio cannot publish into the engine's `txStore`: its caller (the sandbox
64+
* runner's `ctx.api.transaction`) threads the handle across event-loop turns
65+
* that `AsyncLocalStorage` does not survive. But `beginTransaction` is the one
66+
* place the owning driver IS known, so it records the same
67+
* {@link TransactionScope} `runOpenedUnit` publishes, here, and the same-origin
68+
* gate (`enforceTransactionOrigin`, `transactionCoversDriverFor`) reads it for
69+
* an explicitly-threaded handle when the store holds no scope for it. Without
70+
* it, a trio handle reached a driver that does not own it: a ledger row routed
71+
* to the `telemetry` datasource ran on the primary's connection and was lost,
72+
* and a cross-datasource business write ran on the wrong connection.
73+
*
74+
* Weak, so a handle that is never closed is never kept alive. Module-level
75+
* because a handle is one driver connection's object, owned by one engine;
76+
* the scope it maps to names that engine's driver and datasource.
77+
*/
78+
const trioTransactionScopes = new WeakMap<object, TransactionScope>();
79+
80+
/** [#35028] Record the owner of a handle the trio just opened. A primitive handle cannot key it and stays unattributed. */
81+
export function recordTrioTransactionScope(handle: unknown, scope: TransactionScope): void {
82+
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
83+
trioTransactionScopes.set(handle, scope);
84+
}
85+
}
86+
87+
/** [#35028] Forget a trio handle's owner: its commit or rollback closed it. */
88+
export function forgetTrioTransactionScope(handle: unknown): void {
89+
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
90+
trioTransactionScopes.delete(handle);
91+
}
92+
}
93+
94+
/** [#35028] The owner of an open trio handle, or `undefined` for any other handle. */
95+
export function trioTransactionScopeOf(handle: unknown): TransactionScope | undefined {
96+
if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return undefined;
97+
return trioTransactionScopes.get(handle);
98+
}
99+
57100
/**
58101
* The `ObjectQL` members the functions below read — every one of them, and no
59102
* other; each function's `this` is the `Pick` of the members IT reads. Each is
@@ -71,6 +114,7 @@ export interface ExecuteTransactionsHost {
71114
getDriver: ObjectQL['getDriver'];
72115
datasourceNameOf: ObjectQL['datasourceNameOf'];
73116
isSystemLedgerObject: ObjectQL['isSystemLedgerObject'];
117+
isClosedUnitHandle: ObjectQL['isClosedUnitHandle'];
74118
}
75119

76120
/** The body of `ObjectQL#execute`; the method's docblock there is its contract. */
@@ -247,15 +291,25 @@ export function warnTransactionUnsupported(
247291
* rolled-back write; the durable answer lives in ADR-0067/ADR-0119.
248292
*/
249293
export function enforceTransactionOrigin(
250-
this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'logger'>,
294+
this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'isClosedUnitHandle' | 'logger'>,
251295
objectName: string,
252296
driver: IDataDriver,
253297
operation: 'insert' | 'update' | 'delete',
298+
explicitTransaction?: unknown,
254299
): void {
255-
const scope = this.txStore.getStore()?.scope;
256-
// No engine-owned transaction in scope (or a handle threaded explicitly by
257-
// the sandbox trio, which this store never sees) — nothing to be outside
258-
// of. See `transactionCoversDriverFor` for why that limit is declared.
300+
// [#35028] The store holds no scope for a handle the `ScopedContext` trio
301+
// opened (it threads the handle explicitly, across turns the store does not
302+
// survive), so the trio's own record of the owner answers for it. A handle
303+
// the current run was detached from (an `async` hook's run, `unit-detach.ts`)
304+
// is no handle, exactly as `buildDriverOptions` reads it: the write runs
305+
// outside any transaction, on its own connection, and is not judged.
306+
const explicit = explicitTransaction !== undefined && !this.isClosedUnitHandle(explicitTransaction)
307+
? explicitTransaction
308+
: undefined;
309+
const scope = this.txStore.getStore()?.scope ?? trioTransactionScopeOf(explicit);
310+
// No engine-owned transaction in scope (or a handle the engine never opened
311+
// and cannot attribute) — nothing to be outside of. See
312+
// `transactionCoversDriverFor` for why that limit is declared.
259313
if (!scope) return;
260314
// Identity, not name: this is about riding the same connection.
261315
if (driver === scope.driver) return;

‎packages/objectql/src/engine-insert.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ export class InsertFacet {
341341
// [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write,
342342
// carve an append-only system ledger out of the transaction. Before any
343343
// hook, default or validation runs, so a refusal costs nothing.
344-
this.enforceTransactionOrigin(object, driver, 'insert');
344+
this.enforceTransactionOrigin(object, driver, 'insert', options?.context?.transaction);
345345

346346
// [#20308] A blank on a non-string-typed column is `null` from here on —
347347
// before the middleware, the caller snapshot, the defaults, the hooks and

‎packages/objectql/src/engine-middleware-and-context.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import type { IPubSub } from '@objectstack/spec/contracts';
3838
import { redactPropagatedDriverFault } from '@objectstack/types';
3939
import type { ExecutionContext } from '@objectstack/spec/kernel';
4040
import { isWriteEpochOperation } from './write-epoch.js';
41+
import { trioTransactionScopeOf } from './engine-execute-transactions.js';
4142
import { READABLE_IDS_WRITE_IN_FLIGHT } from './engine-readable-ids-permission-formula.js';
4243
import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js';
4344
import { isMissingTableError } from '@objectstack/metadata/errors';
@@ -415,16 +416,17 @@ export class MiddlewareAndContextFacet {
415416
* `TransactionScope` (#5724) records the owner for every transaction the
416417
* engine opens, and `transaction()` also threads that same handle down as
417418
* `execCtx.transaction`, so the dominant explicit-threading path is covered
418-
* by identity-matching the handle back to the store entry. What is NOT
419-
* covered:
419+
* by identity-matching the handle back to the store entry.
420+
* `ScopedContext`'s discrete `beginTransaction`/`commit`/`rollback` trio
421+
* threads its handle across `setImmediate` boundaries where
422+
* AsyncLocalStorage does not survive, and so never populates txStore; but
423+
* the trio knows the owning driver at `beginTransaction`, and records it
424+
* until the handle closes (`trioTransactionScopeOf`, #35028), so its
425+
* handles are attributed by that record instead. What is NOT covered is
426+
* any handle an outside caller obtained elsewhere and passed in as
427+
* `execCtx.transaction`.
420428
*
421-
* - `ScopedContext`'s discrete `beginTransaction`/`commit`/`rollback` trio,
422-
* which threads the handle across `setImmediate` boundaries where
423-
* AsyncLocalStorage does not survive, and so never populates txStore;
424-
* - any handle an outside caller obtained elsewhere and passed in as
425-
* `execCtx.transaction`.
426-
*
427-
* For those the engine holds an opaque driver object with no back-reference
429+
* For that one the engine holds an opaque driver object with no back-reference
428430
* to its driver, so there is no honest comparison to make. Guessing — say,
429431
* assuming an unattributed handle belongs to the default driver — would
430432
* refuse legitimate single-datasource work on one side and carve out writes
@@ -437,7 +439,10 @@ export class MiddlewareAndContextFacet {
437439
const store = this.txStore.getStore();
438440
// The scope describes the handle in the store. An explicitly-threaded
439441
// handle is covered by it only when it IS that handle.
440-
const scope = store !== undefined && tx === store.transaction ? store.scope : undefined;
442+
// [#35028] Any other handle is attributed by the record `ScopedContext`'s
443+
// discrete trio keeps for the handles it opened (its owner is known at
444+
// `beginTransaction`); a handle it never opened stays unattributed.
445+
const scope = store !== undefined && tx === store.transaction ? store.scope : trioTransactionScopeOf(tx);
441446
if (!scope) return true;
442447
return this.getDriver(object) === scope.driver;
443448
}

‎packages/objectql/src/engine-scoped-context.ts‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import { appAutomationElevationOf, markAppAutomationElevation, resolveUserAuthzG
4444
import type { EngineTransactionInfo, EngineTransactionOptions } from '@objectstack/core';
4545
import { rolledBackRefusal } from './summary-errors.js';
4646
import { TransactionUnsupportedError } from './transaction-errors.js';
47+
import { forgetTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js';
4748
import { redactPropagatedDriverFault } from '@objectstack/types';
4849
import { UnscopedHookApi } from './hook-run-as.js';
4950
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
@@ -334,28 +335,49 @@ export class ScopedContextFacet {
334335
// [#33760] The `async` after-hooks dispatched in this unit wait for the
335336
// trio's own commit, or are dropped by its rollback (`unit-detach.ts`).
336337
openTrioCommitQueue(trx);
338+
// [#35028] The trio never publishes into `txStore`, so record here which
339+
// driver owns the handle — the same scope `runOpenedUnit` publishes — for
340+
// the same-origin gate to read when the handle comes back explicitly. A
341+
// ledger row routed to another datasource then runs outside this
342+
// transaction on its own connection, and a business write routed there is
343+
// refused, exactly as inside `transaction(cb)`. Reached the same `as any`
344+
// way as `runOpenedUnit`.
345+
const engine = this.engine as any;
346+
if (typeof engine?.newTransactionScope === 'function') {
347+
recordTrioTransactionScope(trx, engine.newTransactionScope(driver));
348+
}
337349
const ctx = this.derive({ ...this.executionContext, transaction: trx });
338350
return { ctx, handle: trx, owned: true };
339351
}
340352

341353
/** The body of `ScopedContext#commitTransaction`; the method's docblock there is its contract. */
342354
static async commitTransaction(this: Pick<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
343355
if (this.releaseJoinedHandle(handle)) return;
344-
const driver = this.txDriver();
345-
if (!driver) return;
346-
if (driver.commit) await driver.commit(handle);
347-
else if (driver.commitTransaction) await driver.commitTransaction(handle);
356+
// [#35028] Closed either way: a handle whose commit threw is no open unit.
357+
try {
358+
const driver = this.txDriver();
359+
if (!driver) return;
360+
if (driver.commit) await driver.commit(handle);
361+
else if (driver.commitTransaction) await driver.commitTransaction(handle);
362+
} finally {
363+
forgetTrioTransactionScope(handle);
364+
}
348365
settleTrioCommitQueue(handle, true);
349366
}
350367

351368
/** The body of `ScopedContext#rollbackTransaction`; the method's docblock there is its contract. */
352369
static async rollbackTransaction(this: Pick<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
353370
if (this.releaseJoinedHandle(handle)) return;
354371
settleTrioCommitQueue(handle, false);
355-
const driver = this.txDriver();
356-
if (!driver) return;
357-
if (driver.rollback) await driver.rollback(handle);
358-
else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle);
372+
// [#35028] Closed either way, as on the commit face.
373+
try {
374+
const driver = this.txDriver();
375+
if (!driver) return;
376+
if (driver.rollback) await driver.rollback(handle);
377+
else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle);
378+
} finally {
379+
forgetTrioTransactionScope(handle);
380+
}
359381
}
360382

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

0 commit comments

Comments
 (0)