diff --git a/.changeset/35028-trio-handle-owner.md b/.changeset/35028-trio-handle-owner.md new file mode 100644 index 00000000000..2f74f4b9acb --- /dev/null +++ b/.changeset/35028-trio-handle-owner.md @@ -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 + + + +**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. diff --git a/docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md b/docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md index 718c46619f8..28927db947f 100644 --- a/docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md +++ b/docs/adr/0119-plugin-reachable-transactions-and-honest-atomic-batch.md @@ -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 diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index d8a32b8fe23..135f4476944 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -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 diff --git a/packages/objectql/src/engine-execute-transactions.ts b/packages/objectql/src/engine-execute-transactions.ts index c8118c772e5..9ed8195b6c3 100644 --- a/packages/objectql/src/engine-execute-transactions.ts +++ b/packages/objectql/src/engine-execute-transactions.ts @@ -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(); + +/** [#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 @@ -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. */ @@ -247,15 +291,25 @@ export function warnTransactionUnsupported( * rolled-back write; the durable answer lives in ADR-0067/ADR-0119. */ export function enforceTransactionOrigin( - this: Pick, + this: Pick, 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; diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 0b8e11afbba..28efb7c3f95 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -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 diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index cb100e1df1d..7b383d120cf 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -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'; @@ -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 @@ -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; } diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index e2491e6e4ee..0a9faf17e63 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -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'; @@ -334,6 +335,17 @@ 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 }; } @@ -341,10 +353,15 @@ export class ScopedContextFacet { /** The body of `ScopedContext#commitTransaction`; the method's docblock there is its contract. */ static async commitTransaction(this: Pick, handle: unknown): Promise { 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); } @@ -352,10 +369,15 @@ export class ScopedContextFacet { static async rollbackTransaction(this: Pick, handle: unknown): Promise { 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. */ diff --git a/packages/objectql/src/engine-transaction-same-origin.test.ts b/packages/objectql/src/engine-transaction-same-origin.test.ts index 1e3fd3fc724..e77b8563d61 100644 --- a/packages/objectql/src/engine-transaction-same-origin.test.ts +++ b/packages/objectql/src/engine-transaction-same-origin.test.ts @@ -33,7 +33,9 @@ // row is lost exactly as before — only now with a different log line. import { describe, it, expect } from 'vitest'; +import type { Hook } from '@objectstack/spec/data'; import { ObjectQL, ScopedContext } from './engine.js'; +import { bindHooksToEngine } from './hook-binder.js'; import { CrossDatasourceTransactionWriteError } from './transaction-errors.js'; interface Recorded { @@ -558,14 +560,14 @@ describe('the same-origin gate declines to judge a handle it cannot attribute (# it('does NOT cover a foreign handle passed in from outside — declared, not overlooked', async () => { const { engine, ledgerDb } = await splitEngine(); - // The sandbox runner's discrete `beginTransaction`/`commit`/`rollback` trio - // threads its handle across `setImmediate` boundaries where - // AsyncLocalStorage does not survive, so it never populates txStore and the - // engine holds an opaque driver object with no back-reference to its owner. - // There is no honest comparison to make, and guessing would refuse - // legitimate single-datasource work. So the pre-#5351 behaviour stands on - // this path — pinned here so the limit is a recorded decision rather than a - // gap someone discovers. Closing it needs handle ownership to become + // A handle the engine never opened — not through `transaction()`, and not + // through `ScopedContext`'s discrete trio, whose handles it attributes by + // the owner recorded at `beginTransaction` (#35028, the describe below) — + // is an opaque driver object with no back-reference to its owner. There is + // no honest comparison to make, and guessing would refuse legitimate + // single-datasource work. So the pre-#5351 behaviour stands on this path — + // pinned here so the limit is a recorded decision rather than a gap + // someone discovers. Closing it needs handle ownership to become // discoverable on `IDataDriver`; filed separately. const foreign = { __trx: 'somebody elses handle' }; await engine.insert('ledger', { name: 'unattributed' }, { context: { transaction: foreign } } as any); @@ -574,3 +576,200 @@ describe('the same-origin gate declines to judge a handle it cannot attribute (# expect(ledgerDb.writes[0].transaction).toBe(foreign); }); }); + +// --------------------------------------------------------------------------- +// (f) The discrete trio — a handle the engine opened, attributed (#35028) +// --------------------------------------------------------------------------- + +describe('a handle the ScopedContext trio opened is attributed to its owner (#35028)', () => { + /** + * The sandbox runner's `ctx.api.transaction` drives `beginTransaction` / + * `commitTransaction` / `rollbackTransaction` and threads the handle into + * every op explicitly; it never reaches `txStore`. The owner is known at + * `beginTransaction`, so the gate judges the handle as it judges one + * `transaction()` opened. + */ + async function openTrio(engine: ObjectQL) { + const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext; + const opened = await scoped.beginTransaction(); + expect(opened, 'precondition: the default driver opens transactions').not.toBeNull(); + return { scoped, ctx: opened!.ctx as any, handle: opened!.handle }; + } + + /** The platform audit writer's shape: an `afterInsert` hook writing the ledger through `ctx.api.sudo()`. */ + function auditHook(engine: ObjectQL) { + const outcomes: string[] = []; + engine.registerHook('afterInsert', async (ctx: any) => { + if (ctx.object !== 'thing') return; + try { + await ctx.api.sudo().object('sys_audit_log').create({ action: 'create thing' }); + await ctx.api.sudo().object('sys_activity').create({ action: 'created' }); + outcomes.push('ok'); + } catch (e) { + outcomes.push(`FAILED ${String((e as Error)?.message)}`); + } + }, { packageId: '__test__' } as any); + return outcomes; + } + + it('lands the audit and activity rows on telemetry, outside the transaction, with no foreign handle', async () => { + const { engine, primary, telemetry } = await splitEngine(); + const outcomes = auditHook(engine); + const { scoped, ctx, handle } = await openTrio(engine); + + await ctx.object('thing').insert({ name: 'business row' }); + await scoped.commitTransaction(handle); + + expect(outcomes).toEqual(['ok']); + expect(telemetry.writes.map((w: RecordedWrite) => w.object)).toEqual(['sys_audit_log', 'sys_activity']); + // Before #35028 both rows were handed `primary`'s handle — on a real SQL + // driver, a statement on the primary connection that has no such table. + expect(telemetry.writes.every((w: RecordedWrite) => w.transaction === undefined)).toBe(true); + // The business write still rides the trio's own handle. + expect(primary.writes).toHaveLength(1); + expect(primary.writes[0]).toMatchObject({ object: 'thing', op: 'create' }); + expect(primary.writes[0].transaction).toBe(handle); + }); + + it('keeps the ledger rows when the trio rolls back — the decided orphan row', async () => { + const { engine, telemetry, primary } = await splitEngine(); + let rolledBack: unknown; + primary.rollback = async (h: unknown) => { rolledBack = h; }; + auditHook(engine); + const { scoped, ctx, handle } = await openTrio(engine); + + await ctx.object('thing').insert({ name: 'doomed' }); + await scoped.rollbackTransaction(handle); + + expect(rolledBack).toBe(handle); + expect(telemetry.writes.map((w: RecordedWrite) => w.object)).toEqual(['sys_audit_log', 'sys_activity']); + expect(telemetry.writes.every((w: RecordedWrite) => w.transaction === undefined)).toBe(true); + }); + + it('notes the carve-out at debug, once per trio transaction per datasource', async () => { + const { engine, carveOutNotes } = await splitEngine(); + auditHook(engine); + const { scoped, ctx, handle } = await openTrio(engine); + + await ctx.object('thing').insert({ name: 'a' }); + await ctx.object('thing').insert({ name: 'b' }); + await scoped.commitTransaction(handle); + + const notes = carveOutNotes(); + expect(notes).toHaveLength(1); + expect(meta(notes[0])).toMatchObject({ datasource: 'telemetry', transactionDatasource: 'primary' }); + }); + + it('refuses a cross-datasource business write under the trio handle, naming both datasources', async () => { + const { engine, ledgerDb } = await splitEngine(); + const { scoped, ctx, handle } = await openTrio(engine); + + const err = await rejection(ctx.object('ledger').insert({ name: 'NOT covered' })); + await scoped.rollbackTransaction(handle); + + expect(err).toBeInstanceOf(CrossDatasourceTransactionWriteError); + expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE'); + expect(err).toMatchObject({ object: 'ledger', operation: 'insert', datasource: 'ledger_db', transactionDatasource: 'primary' }); + // Refused before any driver ran: nothing on the other datasource, and no + // statement on the wrong connection. + expect(ledgerDb.writes).toHaveLength(0); + }); + + it('refuses update and delete under the trio handle too', async () => { + const { engine, ledgerDb } = await splitEngine(); + const seeded = await engine.insert('ledger', { name: 'outside' }); + const { scoped, ctx, handle } = await openTrio(engine); + + await expect(ctx.object('ledger').update(seeded.id, { name: 'x' })).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError); + await expect(ctx.object('ledger').delete(seeded.id)).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError); + await scoped.rollbackTransaction(handle); + expect(ledgerDb.writes.map((w: RecordedWrite) => w.op)).toEqual(['create']); + }); + + it('forgets the owner once the trio commits — the record does not outlive the handle', async () => { + const { engine, ledgerDb } = await splitEngine(); + const { scoped, handle } = await openTrio(engine); + await scoped.commitTransaction(handle); + + // A closed handle threaded back in is no open trio transaction: it is + // judged as any unattributed handle is (the declared limit above). + await engine.insert('ledger', { name: 'after commit' }, { context: { transaction: handle } } as any); + expect(ledgerDb.writes).toHaveLength(1); + }); + + it('forgets the owner once the trio rolls back, too', async () => { + const { engine, ledgerDb } = await splitEngine(); + const { scoped, handle } = await openTrio(engine); + await scoped.rollbackTransaction(handle); + + await engine.insert('ledger', { name: 'after rollback' }, { context: { transaction: handle } } as any); + expect(ledgerDb.writes).toHaveLength(1); + }); + + it('lets an async afterFind run, detached from the open trio handle, write a business object on another datasource', async () => { + const { engine, ledgerDb } = await splitEngine(); + // An `async: true` `afterFind` run starts at dispatch, outside every unit + // open then (`unit-detach.ts`): its `ctx.api` still carries the trio + // handle, and the engine treats that handle as closed for the run + // (`isClosedUnitHandle`). So its write is outside any transaction, as + // under `transaction(cb)`: it lands, on its own connection, and the gate + // does not judge it against the trio record. + let report!: (outcome: string) => void; + const outcome = new Promise((r) => { report = r; }); + bindHooksToEngine(engine, [{ + name: 'mirror_read', object: 'thing', events: ['afterFind'], async: true, onError: 'log', + handler: async (ctx: any) => { + try { + await ctx.api.object('ledger').insert({ name: 'from a detached read hook' }); + report('stored'); + } catch (e) { + report(`FAILED ${(e as Error)?.name}: ${(e as Error)?.message}`); + } + }, + } as unknown as Hook], { packageId: 'app:t' }); + const { scoped, ctx, handle } = await openTrio(engine); + + await ctx.object('thing').find({}); + // The trio is still open while the detached run writes. + expect(await outcome).toBe('stored'); + await scoped.commitTransaction(handle); + + expect(ledgerDb.writes).toHaveLength(1); + expect(ledgerDb.writes[0]).toMatchObject({ object: 'ledger', op: 'create' }); + expect(ledgerDb.writes[0].transaction).toBeUndefined(); + }); + + describe('single datasource: the trio still rides one handle (#35028 regression guard)', () => { + async function singleEngine() { + const engine = new ObjectQL({ logger: recordingLogger().logger } as any); + const primary = makeDriver('primary'); + engine.registerDriver(primary, true); + await engine.init(); + engine.registry.registerObject({ name: 'thing', fields: { name: { type: 'text' } } }, '__test__'); + for (const [name, cls] of [['sys_audit_log', 'audit'], ['sys_activity', 'telemetry']] as const) { + engine.registry.registerObject({ + name, + lifecycle: { class: cls, retention: { maxAge: '90d' } }, + fields: { action: { type: 'text' } }, + } as any, '__test__'); + } + return { engine, primary }; + } + + it('writes the business and ledger rows on the trio handle, and rolls them back together', async () => { + const { engine, primary } = await singleEngine(); + const outcomes = auditHook(engine); + let rolledBack: unknown; + primary.rollback = async (h: unknown) => { rolledBack = h; }; + const { scoped, ctx, handle } = await openTrio(engine); + + await ctx.object('thing').insert({ name: 'a' }); + await scoped.rollbackTransaction(handle); + + expect(outcomes).toEqual(['ok']); + expect(primary.writes.map((w: RecordedWrite) => w.object)).toEqual(['thing', 'sys_audit_log', 'sys_activity']); + expect(primary.writes.every((w: RecordedWrite) => w.transaction === handle)).toBe(true); + expect(rolledBack).toBe(handle); + }); + }); +}); diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index dc1d73922a4..71476062daa 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -170,7 +170,7 @@ export class UpdateFacet { // [#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, 'update'); + this.enforceTransactionOrigin(object, driver, 'update', options?.context?.transaction); // Fold the `filter` alias into `where` FIRST (#4346): everything below — // token resolution, the by-id fast path, the #2982 AST seeding — reads diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index a347fdd116a..1706979cbc9 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5475,6 +5475,7 @@ export class ObjectQL implements IObjectQLEngine { objectName: string, driver: IDataDriver, operation: 'insert' | 'update' | 'delete', + explicitTransaction?: unknown, ): void { // [#25522 cut 7] The body moved to `engine-execute-transactions.ts`, its docblock with it (see `ExecuteTransactionsHost`). const readTxStore = () => this.txStore; @@ -5483,9 +5484,10 @@ export class ObjectQL implements IObjectQLEngine { get txStore() { return readTxStore(); }, datasourceNameOf: (...a) => this.datasourceNameOf(...a), isSystemLedgerObject: (...a) => this.isSystemLedgerObject(...a), + isClosedUnitHandle: (...a) => this.isClosedUnitHandle(...a), get logger() { return readLogger(); }, }; - return enforceTransactionOrigin.call(host, objectName, driver, operation); + return enforceTransactionOrigin.call(host, objectName, driver, operation, explicitTransaction); } // ============================================ diff --git a/packages/qa/dogfood/test/action-body-transaction-audit-split.dogfood.test.ts b/packages/qa/dogfood/test/action-body-transaction-audit-split.dogfood.test.ts new file mode 100644 index 00000000000..fd94b903614 --- /dev/null +++ b/packages/qa/dogfood/test/action-body-transaction-audit-split.dogfood.test.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#35028] An action body's write inside `ctx.api.transaction` keeps its +// compliance rows when the deployment carries a `telemetry` datasource — on a +// real boot, every half composed. +// +// ## The composition +// +// `bootStack` with the real `AuditPlugin` and a second, file-backed SQLite +// driver named `telemetry`, adopted the way `os dev` / `os serve` adopt the +// sibling telemetry database (a `DriverPlugin` whose driver is named +// `telemetry`). ADR-0057 §3.6 then routes the lifecycle-classed ledgers +// (`sys_audit_log`, `sys_activity`) to it, and the business objects stay on the +// primary. The actions are sandboxed bodies posted through the real `/actions` +// door, so the body's `ctx.api.transaction` drives `ScopedContext`'s discrete +// begin/commit/rollback trio, and plugin-audit's `afterInsert` writer runs +// under the body's transaction handle. +// +// ## What was broken +// +// The trio never publishes into the engine's `txStore`, so the same-origin gate +// had no owner for its handle and stepped aside: plugin-audit's ledger insert +// was handed the PRIMARY's handle while routed to the telemetry driver, ran on +// the primary connection — which has no `sys_audit_log` — and was lost. The +// API answered 200 and one `Audit write FAILED` line was the only trace. +// +// ## What is asserted +// +// - Two inserts inside the body's transaction each keep their `sys_audit_log` +// row and their `sys_activity` row. +// - A body transaction that throws leaves no business row; its ledger rows are +// the decided orphan rows of the #5351 carve-out (written outside the +// transaction, on telemetry's own connection). +// - A BUSINESS write inside the body's transaction to an object on the other +// datasource is refused, by name, and nothing is written. +// +// `@objectstack/objectql`, `@objectstack/runtime` and +// `@objectstack/plugin-audit` resolve through their BUILT output here, so a +// verdict on a change to any of them is a verdict on its last build. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { DriverPlugin } from '@objectstack/runtime'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +const ITEM = 'abx_item'; +const REMOTE = 'abx_remote'; +const SYS = { context: { isSystem: true } } as const; +const TX_CAPS = ['api.write', 'api.transaction']; + +const TX_INSERT = ` + const ids = []; + await ctx.api.transaction(async () => { + ids.push((await ctx.api.object('${ITEM}').insert({ title: 'tx-1' })).id); + ids.push((await ctx.api.object('${ITEM}').insert({ title: 'tx-2' })).id); + }); + return { ids };`; + +const TX_ROLLBACK = ` + let id; + try { + await ctx.api.transaction(async () => { + id = (await ctx.api.object('${ITEM}').insert({ title: 'tx-doomed' })).id; + throw new Error('the body gives up'); + }); + } catch (e) { + return { rolledBack: true, id }; + } + return { rolledBack: false, id };`; + +const TX_REMOTE = ` + await ctx.api.transaction(async () => { + await ctx.api.object('${REMOTE}').insert({ title: 'across datasources' }); + }); + return { wrote: true };`; + +const fixtureStack = defineStack({ + manifest: { + id: 'com.dogfood.action-body-transaction-audit-split', + namespace: 'abx', + version: '0.0.0', + type: 'app', + name: 'Action Body Transaction Audit Split Fixture', + description: 'Sandboxed action bodies writing inside ctx.api.transaction on a deployment with a telemetry datasource.', + }, + objects: [ + ObjectSchema.create({ name: ITEM, label: 'Item', fields: { title: Field.text({ label: 'Title', required: true }) } }), + // A BUSINESS object bound to the other datasource: no lifecycle class, so + // it is no system ledger and the carve-out does not apply to it. + ObjectSchema.create({ name: REMOTE, label: 'Remote', datasource: 'telemetry', fields: { title: Field.text({ label: 'Title' }) } } as any), + ], + actions: [ + { name: 'abx_tx_insert', label: 'Insert two in a transaction', objectName: ITEM, type: 'script', body: { language: 'js', source: TX_INSERT, capabilities: TX_CAPS } }, + { name: 'abx_tx_rollback', label: 'Insert then roll back', objectName: ITEM, type: 'script', body: { language: 'js', source: TX_ROLLBACK, capabilities: TX_CAPS } }, + { name: 'abx_tx_remote', label: 'Write across datasources', objectName: ITEM, type: 'script', body: { language: 'js', source: TX_REMOTE, capabilities: TX_CAPS } }, + ], +} as any); + +type Row = Record; + +describe('[#35028] an action body\'s write inside ctx.api.transaction keeps its ledger rows beside a telemetry datasource', () => { + let stack: VerifyStack; + let ql: any; + let token = ''; + let dir = ''; + + const ledgerRows = async (object: 'sys_audit_log' | 'sys_activity', recordId: string): Promise => + (await ql.find(object, { where: { object_name: ITEM, record_id: recordId }, ...SYS })) as Row[]; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'os-abx-35028-')); + const telemetry = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'telemetry.sqlite') }, useNullAsDefault: true }); + Object.defineProperty(telemetry, 'name', { value: 'telemetry' }); + stack = await bootStack(fixtureStack as unknown as Parameters[0], { + extraPlugins: [new DriverPlugin(telemetry), new AuditPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + token = await stack.signIn(); + // Precondition: the split is real — the ledger and the business object + // resolve to different drivers. + expect(ql.getDriver('sys_audit_log')).toBe(telemetry); + expect(ql.getDriver('sys_activity')).toBe(telemetry); + expect(ql.getDriver(ITEM)).not.toBe(telemetry); + }, 180_000); + + afterAll(async () => { + await stack?.stop(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it('two inserts inside the body\'s transaction each keep their sys_audit_log and sys_activity rows', async () => { + const r = await stack.apiAs(token, 'POST', `/actions/${ITEM}/abx_tx_insert`, {}); + const body = (await r.json()) as any; + expect(r.status, JSON.stringify(body)).toBe(200); + const ids: string[] = body.data?.ids ?? body.ids; + expect(ids).toHaveLength(2); + for (const id of ids) { + expect(await ql.findOne(ITEM, { where: { id }, ...SYS }), `business row ${id}`).toBeTruthy(); + const audit = await ledgerRows('sys_audit_log', id); + expect(audit.map((a) => a.action), `sys_audit_log for ${id}`).toEqual(['create']); + expect((await ledgerRows('sys_activity', id)).length, `sys_activity for ${id}`).toBe(1); + } + }); + + it('a body transaction that throws leaves no business row; its ledger row is the decided orphan', async () => { + const r = await stack.apiAs(token, 'POST', `/actions/${ITEM}/abx_tx_rollback`, {}); + const body = (await r.json()) as any; + expect(r.status, JSON.stringify(body)).toBe(200); + const out = body.data ?? body; + expect(out.rolledBack).toBe(true); + expect(await ql.findOne(ITEM, { where: { id: out.id }, ...SYS })).toBeFalsy(); + // Written outside the transaction, on telemetry's own connection: it + // survives the rollback (ADR-0119, the #5351 carve-out). + expect((await ledgerRows('sys_audit_log', out.id)).map((a) => a.action)).toEqual(['create']); + }); + + it('a business write inside the body\'s transaction to the other datasource is refused, by name', async () => { + const r = await stack.apiAs(token, 'POST', `/actions/${ITEM}/abx_tx_remote`, {}); + const body = (await r.json()) as any; + expect(r.status, JSON.stringify(body)).toBe(400); + expect(body.error?.code, JSON.stringify(body)).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE'); + expect(body.error?.message).toContain(`insert of '${REMOTE}'`); + expect(await ql.find(REMOTE, SYS)).toHaveLength(0); + }); +}); diff --git a/packages/runtime/src/sandbox/action-body-transaction-rollup-child.integration.test.ts b/packages/runtime/src/sandbox/action-body-transaction-rollup-child.integration.test.ts new file mode 100644 index 00000000000..fb0525772e6 --- /dev/null +++ b/packages/runtime/src/sandbox/action-body-transaction-rollup-child.integration.test.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An action body's `ctx.api.transaction` that inserts a master-detail child + * whose parent carries a roll-up completes on SQLite, well inside the sandbox + * wall clock — with the platform's audit-shaped ledger write riding along, on + * one datasource and beside a `telemetry` one. + * + * Measured broken in a published release (the #34998 reading): the first child + * insert inside the body's transaction never settled, the body hit the 30 s + * wall-clock ceiling, and the door answered `500`. `main` already passes. This + * file guards it, and guards the #35028 change beside it: the ledger write that + * now leaves the body's transaction for the `telemetry` datasource must not + * reintroduce a wait on SQLite's one connection. + * + * Measured in composition: a real `ObjectQL` on a real better-sqlite3 + * `SqlDriver` (the `os dev` primary), the real `QuickJSScriptRunner` and + * action-body factory, and the real `/actions` door + * (`HttpDispatcher.handleActions`), whose engine double only hands the door's + * action context to the bound handler, as `ObjectQL.executeAction` does. The + * ledger writer is a stand-in with plugin-audit's shape: an `afterInsert` hook + * writing `sys_audit_log` and `sys_activity` through `ctx.api.sudo()`, under + * the handle the write carries. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +// Paid at collection, not inside a clocked case (`pnpm check:test-source-alias`). +import '@objectstack/metadata'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { actionBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import { installDefaultOrganization } from '../default-organization.testkit.js'; + +const CLAIM = { + name: 'rux_claim', + fields: { + name: { type: 'text', name: 'name' }, + total_amount: { type: 'summary', name: 'total_amount', summaryOperations: { object: 'rux_line', function: 'sum', field: 'amount' } }, + }, +}; +const LINE = { + name: 'rux_line', + fields: { + claim: { type: 'master_detail', name: 'claim', reference: 'rux_claim', deleteBehavior: 'cascade' }, + amount: { type: 'number', name: 'amount' }, + }, +}; +const AUDIT = { name: 'sys_audit_log', lifecycle: { class: 'audit', retention: { maxAge: '90d' } }, fields: { action: { type: 'text', name: 'action' }, record_id: { type: 'text', name: 'record_id' } } }; +const ACTIVITY = { name: 'sys_activity', lifecycle: { class: 'telemetry', retention: { maxAge: '14d' } }, fields: { action: { type: 'text', name: 'action' }, record_id: { type: 'text', name: 'record_id' } } }; + +/** The body: a claim, then two lines inside one transaction — the travel-expense shape. */ +const SOURCE = ` + const claim = await ctx.api.object('rux_claim').insert({ name: 'C-1' }); + await ctx.api.transaction(async () => { + await ctx.api.object('rux_line').insert({ claim: claim.id, amount: 860 }); + await ctx.api.object('rux_line').insert({ claim: claim.id, amount: 345 }); + }); + return { claim: claim.id };`; + +/** + * The live Postgres cell runs only where a server is provisioned (the same + * variable `driver-sql`'s live dialect matrix reads); elsewhere it is skipped, + * by name. + */ +const PG_URL = process.env.OS_TEST_POSTGRES_URL; + +/** One insert inside the body's transaction: what COMMIT does with it is the question. */ +const ONE_LINE_SOURCE = ` + const claim = await ctx.api.object('rux_claim').insert({ name: 'C-2' }); + await ctx.api.transaction(async () => { + await ctx.api.object('rux_line').insert({ claim: claim.id, amount: 430 }); + }); + return { claim: claim.id };`; + +const SYS = { context: { isSystem: true } } as const; + +/** Far below the sandbox's 30 s wall clock: a stall cannot pass for a slow run. */ +const WALL_CLOCK_BOUND_MS = 10_000; + +describe('an action body transaction inserting a roll-up child completes on SQLite (#34998 regression, #35028)', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + if (pgSchema) { + const admin = new SqlDriver({ client: 'pg', connection: PG_URL } as any); + try { await admin.getKnex().raw('drop schema if exists ?? cascade', [pgSchema]); } finally { await admin.disconnect(); } + pgSchema = null; + } + }); + + /** A Postgres primary in a schema of its own, dropped after the case. */ + let pgSchema: string | null = null; + async function livePgPrimary(): Promise { + pgSchema = `rux_35028_${process.pid}_${Date.now()}`; + const admin = new SqlDriver({ client: 'pg', connection: PG_URL } as any); + try { await admin.getKnex().raw('create schema ??', [pgSchema]); } finally { await admin.disconnect(); } + return new SqlDriver({ client: 'pg', connection: PG_URL, searchPath: [pgSchema] } as any); + } + + async function boot(split: boolean, primaryOn: 'sqlite' | 'pg' = 'sqlite') { + dir = mkdtempSync(join(tmpdir(), 'os-rux-35028-')); + const sqlite = (file: string) => new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir!, file) }, useNullAsDefault: true }); + const primary = primaryOn === 'pg' ? await livePgPrimary() : sqlite('data.sqlite'); + const e = new ObjectQL(); + engine = e; + let telemetry: SqlDriver | undefined; + if (split) { + telemetry = sqlite('telemetry.sqlite'); + Object.defineProperty(telemetry, 'name', { value: ObjectQL.LIFECYCLE_DATASOURCE }); + e.registerDriver(telemetry as any); + } + e.registerDriver(primary as any, true); + const begins = { count: 0 }; + const begin = primary.beginTransaction.bind(primary); + (primary as any).beginTransaction = async (...a: unknown[]) => { begins.count += 1; return (begin as any)(...a); }; + await e.init(); + for (const o of [CLAIM, LINE, AUDIT, ACTIVITY]) e.registry.registerObject(o as any); + await installDefaultOrganization(e as any); + const ledger: string[] = []; + e.registerHook('afterInsert', async (ctx: any) => { + if (ctx.object !== 'rux_line' && ctx.object !== 'rux_claim') return; + try { + const sys = ctx.api.sudo(); + await sys.object('sys_audit_log').create({ action: 'create', record_id: String(ctx.result?.id) }); + await sys.object('sys_activity').create({ action: 'created', record_id: String(ctx.result?.id) }); + ledger.push('ok'); + } catch (err) { + ledger.push(`FAILED ${String((err as Error)?.message)}`); + } + }, { packageId: 'rux' } as any); + return { e, ledger, primary, telemetry, begins }; + } + + async function throughActionsDoor(e: ObjectQL, source = SOURCE) { + const action = { name: 'rux_file', objectName: 'rux_claim', type: 'script', body: { language: 'js', source, capabilities: ['api.write', 'api.transaction'] } }; + const handler = actionBodyRunnerFactory(new QuickJSScriptRunner(), { ql: e, appId: 'rux' })(action as any); + expect(handler, 'the action body must bind').toBeTypeOf('function'); + const objectDef = { name: 'rux_claim', actions: [action] }; + const ql: any = { + executeAction: vi.fn(async (_o: string, _a: string, ctx: any) => handler!(ctx)), + // The door builds the body's `ctx.api` from the engine's own scoped + // context (`buildActionApi`), as on a real boot, so the body's + // `ctx.api.transaction` drives the real begin/commit trio. + createContext: (ec: any) => e.createContext(ec), + getSchema: (n: string) => (n === objectDef.name ? objectDef : undefined), + registry: { getObject: (n: string) => (n === objectDef.name ? objectDef : undefined), getItem: () => undefined }, + find: vi.fn(async () => []), + insert: vi.fn(), update: vi.fn(), delete: vi.fn(), + }; + const metadata: any = { load: vi.fn(async () => null), listObjects: vi.fn(async () => [objectDef]), getObject: vi.fn(async () => objectDef) }; + const kernel: any = { context: { getService: (n: string) => (n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : null) } }; + const started = Date.now(); + const res: any = await new HttpDispatcher(kernel).handleActions( + '/rux_claim/rux_file', + 'POST', + {}, + { request: {}, environmentId: 'platform', executionContext: { userId: 'u1', systemPermissions: [] } } as any, + ); + return { response: res.response, elapsed: Date.now() - started }; + } + + for (const split of [false, true]) { + const layout = split ? 'beside a telemetry datasource' : 'on one datasource'; + it(`${layout}: the body answers 200 inside the bound, the lines and the roll-up land, and every ledger write succeeds`, async () => { + const { e, ledger, begins } = await boot(split); + const { response, elapsed } = await throughActionsDoor(e); + // Precondition: the body really opened a driver transaction. + expect(begins.count).toBe(1); + + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(elapsed).toBeLessThan(WALL_CLOCK_BOUND_MS); + const claimId = String(response.body?.data?.claim ?? response.body?.claim); + const lines = (await e.find('rux_line', { where: { claim: claimId }, ...SYS })) as any[]; + expect(lines.map((l) => Number(l.amount)).sort((a, b) => a - b)).toEqual([345, 860]); + const claim = (await e.findOne('rux_claim', { where: { id: claimId }, ...SYS })) as any; + expect(Number(claim?.total_amount)).toBe(1205); + // One claim and two lines, each with both ledger rows. + expect(ledger).toEqual(['ok', 'ok', 'ok']); + const audit = (await e.find('sys_audit_log', SYS)) as any[]; + expect(audit.map((a) => a.record_id).sort()).toEqual([claimId, ...lines.map((l) => String(l.id))].sort()); + }, 30_000); + } + + // [#35028] The Postgres face of the same defect, measured in-process by the + // reading: the ledger statement the trio's handle carried onto the primary + // connection failed there (42P01), which aborts a Postgres transaction — so + // a second insert failed (25P02), and a lone insert's COMMIT resolved as a + // ROLLBACK, with the action answering success. With the owner recorded, the + // ledger write runs on telemetry's own connection and touches neither. + describe.skipIf(!PG_URL)('a live Postgres primary beside a telemetry datasource (OS_TEST_POSTGRES_URL)', () => { + it('two inserts: the body answers 200, both lines and the roll-up are on disk, every ledger write succeeds', async () => { + const { e, ledger, begins } = await boot(true, 'pg'); + const { response } = await throughActionsDoor(e); + expect(begins.count).toBe(1); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const claimId = String(response.body?.data?.claim ?? response.body?.claim); + const lines = (await e.find('rux_line', { where: { claim: claimId }, ...SYS })) as any[]; + expect(lines.map((l) => Number(l.amount)).sort((a, b) => a - b)).toEqual([345, 860]); + expect(Number(((await e.findOne('rux_claim', { where: { id: claimId }, ...SYS })) as any)?.total_amount)).toBe(1205); + expect(ledger).toEqual(['ok', 'ok', 'ok']); + }, 30_000); + + it('one insert: COMMIT keeps it — the line is on disk after the action answers 200', async () => { + const { e, ledger } = await boot(true, 'pg'); + const { response } = await throughActionsDoor(e, ONE_LINE_SOURCE); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const claimId = String(response.body?.data?.claim ?? response.body?.claim); + const lines = (await e.find('rux_line', { where: { claim: claimId }, ...SYS })) as any[]; + expect(lines.map((l) => Number(l.amount))).toEqual([430]); + expect(ledger).toEqual(['ok', 'ok']); + }, 30_000); + }); +});