From 510e96a16cac29251061989b09cf0a1b2a33f402 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 08:06:18 +0000 Subject: [PATCH 1/7] test(plugin-security): pin the concurrent-claim race over SQLite (ADR-0142 D4) Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../src/ownership-claim-race-sqlite.test.ts | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts diff --git a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts new file mode 100644 index 00000000000..d3553124135 --- /dev/null +++ b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts @@ -0,0 +1,168 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0142 D4] Two members of one queue claim the same parked row at the same + * moment, over the REAL stack: `ObjectQL`, `SqlDriver` on better-sqlite3 + * `:memory:` (a single-connection pool), `SecurityPlugin` and + * `SharingService`. Exactly one claim lands; the loser answers + * `409 CONCURRENT_UPDATE`, never "not found" and never "forbidden" because it + * lost a race; the stored owner is the winner. + * + * The cells cross the two answers a lost race used to get with the two unit + * shapes the engine has: an object with no metadata `beforeUpdate` hook opens + * no unit of work for the write; one with such a hook opens the after-abort + * unit (`opensAfterAbortUnit`'s side-writing term). When that unit enclosed the + * middleware chain, the loser's whole write — the authorization gate's + * caller-scoped pre-image read included — waited on the single connection for + * the winner's commit, and then read a row it no longer owned: `private` + * answered 404 (it cannot see the row), `public_read` answered 403 (it can see + * it but not edit it). The unit now opens around the engine body only, so both + * gates read the parked row and the conditional write decides. + * + * The rest of the file is the non-regression half: a true not-found still + * answers 404, and a row the caller cannot read still answers as not found + * (no existence leak), on the hooked object whose writes open the unit. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingService, buildSharingMiddleware, SysRecordShare } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; +const CASE = 'cq_case'; +const ORG = 'org_cq'; +const QUEUE = 'cq_intake'; +const A = 'usr_cq_a'; +const B = 'usr_cq_b'; +/** Rounds per cell: the race is a scheduling fact, so one round proves little. */ +const ROUNDS = 25; +const SET = PermissionSetSchema.parse({ + name: 'cq_member', + objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}); +const SETS = [MEMBER_DEFAULT, SET]; +const memberOf = (userId: string) => ({ + userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER', +}); +const QUIET = { debug() {}, info() {}, warn() {}, error() {} }; + +async function boot(opts: { sharingModel: 'private' | 'public_read'; beforeHook: boolean }) { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.claim-race', name: 'claim race', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [SysRecordShare, SysUser, SysOrganization, SysMember, SysUserPosition, SysUserPermissionSet, { + name: CASE, label: 'Case', sharingModel: opts.sharingModel, tenancy: { enabled: false }, + fields: { id: { name: 'id', type: 'text', primaryKey: true }, name: { name: 'name', type: 'text' } }, + }], + } as never); + await engine.syncSchemas(); + if (opts.beforeHook) { + // A metadata-bound hook that does nothing: its presence alone is what + // makes the engine open the after-abort unit for this object's updates. + bindHooksToEngine(engine as never, [{ name: 'cq_touch', object: CASE, events: ['beforeUpdate'], handler: () => {} } as never], { + packageId: 'app:cq', logger: QUIET as never, + }); + } + await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@cq.test` })), SYS); + await engine.insert('sys_organization', [{ id: ORG, name: 'CQ', slug: 'cq' }], SYS); + let securityService: unknown; + let sharing: SharingService | undefined; + const queues = { + queuesOf: async (u: string) => ([A, B].includes(u) ? [QUEUE] : []), + isMember: async (u: string, q: string) => q === QUEUE && [A, B].includes(u), + }; + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null, + list: async () => SETS, + }, + get sharing() { return sharing; }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { if (name === 'security') securityService = svc; }, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + sharing = new SharingService({ engine: engine as never, securityService: () => securityService as never, ownershipQueues: () => queues as never }); + engine.registerMiddleware(buildSharingMiddleware(sharing, ctx.logger) as never, { object: '*' }); + return engine; +} + +/** Seed a row straight through the driver, below every gate. */ +const seed = (engine: ObjectQL, row: Record) => + (engine as any).getDriver(CASE).create(CASE, row); +const claim = (engine: ObjectQL, id: string, user: string) => + engine.update(CASE, { id, owner_id: user }, { where: { id }, context: memberOf(user) } as never); +const outcome = (r: PromiseSettledResult): string => + r.status === 'fulfilled' ? 'fulfilled' : `${(r.reason as any)?.code}/${(r.reason as any)?.status}`; + +for (const sharingModel of ['private', 'public_read'] as const) { + for (const beforeHook of [false, true]) { + describe(`[ADR-0142 D4] concurrent claims — ${sharingModel} OWD, ${beforeHook ? 'metadata beforeUpdate hook (the unit opens)' : 'no hook (no unit)'}`, () => { + it(`exactly one claim lands and every loser answers 409 CONCURRENT_UPDATE, over ${ROUNDS} rounds`, async () => { + const engine = await boot({ sharingModel, beforeHook }); + const losers: Record = {}; + for (let round = 0; round < ROUNDS; round++) { + const id = `case_${round}`; + await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); + const settled = await Promise.allSettled([claim(engine, id, A), claim(engine, id, B)]); + const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[A, B][i]] : [])); + expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(1); + for (const r of settled) { + if (r.status === 'rejected') { + const key = outcome(r); + losers[key] = (losers[key] ?? 0) + 1; + } + } + const stored = await engine.findOne(CASE, { where: { id } } as never, SYS); + expect((stored as any)?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0]); + } + expect(losers).toEqual({ 'CONCURRENT_UPDATE/409': ROUNDS }); + }); + }); + } +} + +describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusals — private OWD, hooked object', () => { + it('a row that is gone still answers 404 RECORD_NOT_FOUND', async () => { + const engine = await boot({ sharingModel: 'private', beforeHook: true }); + await seed(engine, { id: 'case_gone', name: 'parked', owner_id: null, queue: QUEUE }); + await engine.delete(CASE, { where: { id: 'case_gone' } } as never, SYS); + const err = await claim(engine, 'case_gone', A).then(() => undefined, (e: unknown) => e); + expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 }); + }); + + it('a row the caller cannot read answers as not found, never as forbidden', async () => { + const engine = await boot({ sharingModel: 'private', beforeHook: true }); + await seed(engine, { id: 'case_theirs', name: 'owned', owner_id: B, queue: null }); + const err = await claim(engine, 'case_theirs', A).then(() => undefined, (e: unknown) => e); + expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 }); + const stored = await engine.findOne(CASE, { where: { id: 'case_theirs' } } as never, SYS); + expect((stored as any)?.owner_id).toBe(B); + }); +}); From b65177e4882aa9d3902fb05ceb45dc19d699f478 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 08:16:26 +0000 Subject: [PATCH 2/7] fix(objectql): open the update's after-abort unit around the engine body, not the door The unit enclosed the middleware chain, so on a single-connection store the loser of a concurrent claim ran its authorization gate after the winner's commit and was refused as not found or forbidden instead of 409 CONCURRENT_UPDATE (ADR-0142 D4). Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- packages/objectql/src/engine-update.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index dc1d73922a4..b8273f91ecc 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -158,9 +158,20 @@ export class UpdateFacet { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. - if (this.opensAfterAbortUnit('afterUpdate', object, options?.context)) { - return this.inAfterAbortUnit(() => this.update(object, data, options)); - } + // + // [#35142] The unit opens around the ENGINE BODY (the executor below), not + // around the door: the middleware chain runs first, outside it, as it does + // for a write that opens no unit. Opened around the door, the unit enclosed + // the authorization gate's reads too, and on a single-connection store + // (SQLite) a second writer's whole write then waited for the first one's + // commit: the loser of a claim race (ADR-0142 D4) read the claimed row in + // its gate and was refused there as not found or forbidden, never reaching + // the conditional write whose 0-row answer is `ConcurrentUpdateError`. + // Everything the unit exists for — the `before*` hooks' `ctx.api` writes, + // the row, the `after*` chain — runs inside the executor. + const ownUnit = this.opensAfterAbortUnit('afterUpdate', object, options?.context); + const inOwnUnit = (body: () => Promise): (() => Promise) => + ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Update operation starting', { object }); this.assertWriteAllowed(object, 'update'); // [#8844] See the insert face — an organization row that changes identity @@ -461,7 +472,7 @@ export class UpdateFacet { throw new ReadonlyFieldRejectedError(object, fields, strictDrops); }; - await this.executeWithMiddleware(opCtx, async () => { + await this.executeWithMiddleware(opCtx, inOwnUnit(async () => { // [ADR-0139 D1] A write's predicate never carries a `ReadableIds` leaf. // The door refused the caller's; this refuses one the middleware chain // wrote — here, at the executor's entry, because the prior-row reads @@ -2374,7 +2385,7 @@ export class UpdateFacet { await this.releaseSecretHandles(object, writtenSecrets, opCtx.context, 'refused'); throw e; } - }); + })); return opCtx.result; } From 06f9b81ab8f9e2797248a761007f650a02fb0a60 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 08:20:37 +0000 Subject: [PATCH 3/7] test(plugin-security): the not-found pin deletes as the system Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .../plugin-security/src/ownership-claim-race-sqlite.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts index d3553124135..68c87c94384 100644 --- a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts +++ b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts @@ -152,7 +152,7 @@ describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusa it('a row that is gone still answers 404 RECORD_NOT_FOUND', async () => { const engine = await boot({ sharingModel: 'private', beforeHook: true }); await seed(engine, { id: 'case_gone', name: 'parked', owner_id: null, queue: QUEUE }); - await engine.delete(CASE, { where: { id: 'case_gone' } } as never, SYS); + await engine.delete(CASE, { where: { id: 'case_gone' }, context: { isSystem: true } } as never); const err = await claim(engine, 'case_gone', A).then(() => undefined, (e: unknown) => e); expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 }); }); From 70f270f57d572b7ca64abb09b76ee10b43d9a2e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 08:22:06 +0000 Subject: [PATCH 4/7] chore(changeset): objectql patch for the claim-race loser answer Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Co-authored-by: Claude --- .changeset/35142-claim-race-loser-409.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/35142-claim-race-loser-409.md diff --git a/.changeset/35142-claim-race-loser-409.md b/.changeset/35142-claim-race-loser-409.md new file mode 100644 index 00000000000..c912effc8f1 --- /dev/null +++ b/.changeset/35142-claim-race-loser-409.md @@ -0,0 +1,16 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): the loser of a concurrent update answers 409 CONCURRENT_UPDATE again on an object with a metadata `beforeUpdate` hook + +Clause-②: no +Metadata-protocol: none + +Two members of a queue claiming the same parked record at the same moment again get one success and one `409 CONCURRENT_UPDATE`, as ADR-0142 D4 says. Since 18.6.0, on a single-connection store such as SQLite, the loser got `404 RECORD_NOT_FOUND` (private sharing) or `403 PERMISSION_DENIED` (public read) whenever the object carried a metadata `beforeUpdate` hook. The stored owner was always right; only the loser's answer was wrong. + +The cause: a write on such an object opens its own unit of work, so that a refusal later in the write rolls back what a `beforeUpdate` hook wrote through `ctx.api`. That unit opened around the whole update, the authorization middleware included. On SQLite the second writer then waited for the first one's commit before its authorization gate read the record, and by then the record belonged to someone else. The unit now opens around the engine body only: the middleware runs before it, as it does for an update that opens no unit, and the hooks, the row write and the `after*` chain still run inside it and still roll back together. + +What a middleware does after `next()` on such an update now runs after the commit, as it does on an object with no metadata hook. + +Nothing to change in an app. From 415eefd791f215c90e0f85e3a80ed52a1d938aeb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:58:17 +0000 Subject: [PATCH 5/7] test(plugin-security): pin the claim race on an object whose only metadata hook is a blocking afterUpdate The after-abort unit opens for either term of opensAfterAbortUnit: a metadata beforeUpdate hook (side-writing) or a blocking / conditioned metadata afterUpdate hook (aborting). The fifth cell holds the aborting arm to 409 CONCURRENT_UPDATE too: private OWD, 25 rounds. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .../src/ownership-claim-race-sqlite.test.ts | 85 +++++++++++-------- 1 file changed, 51 insertions(+), 34 deletions(-) diff --git a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts index 68c87c94384..4fbe2233bd5 100644 --- a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts +++ b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts @@ -9,10 +9,11 @@ * lost a race; the stored owner is the winner. * * The cells cross the two answers a lost race used to get with the two unit - * shapes the engine has: an object with no metadata `beforeUpdate` hook opens - * no unit of work for the write; one with such a hook opens the after-abort - * unit (`opensAfterAbortUnit`'s side-writing term). When that unit enclosed the - * middleware chain, the loser's whole write — the authorization gate's + * shapes the engine has: an object with no metadata update hook opens no unit + * of work for the write; one with a metadata `beforeUpdate` hook opens the + * after-abort unit (`opensAfterAbortUnit`'s side-writing term), and so does one + * whose only metadata hook is a blocking `afterUpdate` (its aborting term, the + * fifth cell). When that unit enclosed the middleware chain, the loser's whole write — the authorization gate's * caller-scoped pre-image read included — waited on the single connection for * the winner's commit, and then read a row it no longer owned: `private` * answered 404 (it cannot see the row), `public_read` answered 403 (it can see @@ -55,7 +56,9 @@ const memberOf = (userId: string) => ({ }); const QUIET = { debug() {}, info() {}, warn() {}, error() {} }; -async function boot(opts: { sharingModel: 'private' | 'public_read'; beforeHook: boolean }) { +type HookShape = 'none' | 'beforeUpdate' | 'afterUpdate'; + +async function boot(opts: { sharingModel: 'private' | 'public_read'; hook: HookShape }) { const engine = new ObjectQL(); engine.registerDriver( new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, @@ -70,12 +73,15 @@ async function boot(opts: { sharingModel: 'private' | 'public_read'; beforeHook: }], } as never); await engine.syncSchemas(); - if (opts.beforeHook) { + if (opts.hook !== 'none') { // A metadata-bound hook that does nothing: its presence alone is what - // makes the engine open the after-abort unit for this object's updates. - bindHooksToEngine(engine as never, [{ name: 'cq_touch', object: CASE, events: ['beforeUpdate'], handler: () => {} } as never], { - packageId: 'app:cq', logger: QUIET as never, - }); + // makes the engine open the after-abort unit for this object's updates — + // any `beforeUpdate` (side-writing term), or a blocking `afterUpdate` whose + // `onError` is `abort` (aborting term). + const hook = opts.hook === 'afterUpdate' + ? { name: 'cq_after', object: CASE, events: ['afterUpdate'], onError: 'abort', handler: () => {} } + : { name: 'cq_touch', object: CASE, events: ['beforeUpdate'], handler: () => {} }; + bindHooksToEngine(engine as never, [hook as never], { packageId: 'app:cq', logger: QUIET as never }); } await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@cq.test` })), SYS); await engine.insert('sys_organization', [{ id: ORG, name: 'CQ', slug: 'cq' }], SYS); @@ -121,36 +127,47 @@ const claim = (engine: ObjectQL, id: string, user: string) => const outcome = (r: PromiseSettledResult): string => r.status === 'fulfilled' ? 'fulfilled' : `${(r.reason as any)?.code}/${(r.reason as any)?.status}`; -for (const sharingModel of ['private', 'public_read'] as const) { - for (const beforeHook of [false, true]) { - describe(`[ADR-0142 D4] concurrent claims — ${sharingModel} OWD, ${beforeHook ? 'metadata beforeUpdate hook (the unit opens)' : 'no hook (no unit)'}`, () => { - it(`exactly one claim lands and every loser answers 409 CONCURRENT_UPDATE, over ${ROUNDS} rounds`, async () => { - const engine = await boot({ sharingModel, beforeHook }); - const losers: Record = {}; - for (let round = 0; round < ROUNDS; round++) { - const id = `case_${round}`; - await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); - const settled = await Promise.allSettled([claim(engine, id, A), claim(engine, id, B)]); - const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[A, B][i]] : [])); - expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(1); - for (const r of settled) { - if (r.status === 'rejected') { - const key = outcome(r); - losers[key] = (losers[key] ?? 0) + 1; - } +const HOOK_LABEL: Record = { + none: 'no hook (no unit)', + beforeUpdate: 'metadata beforeUpdate hook (the unit opens)', + afterUpdate: 'only a blocking metadata afterUpdate hook (the unit opens)', +}; +const CELLS: ReadonlyArray<{ sharingModel: 'private' | 'public_read'; hook: HookShape }> = [ + { sharingModel: 'private', hook: 'none' }, + { sharingModel: 'private', hook: 'beforeUpdate' }, + { sharingModel: 'public_read', hook: 'none' }, + { sharingModel: 'public_read', hook: 'beforeUpdate' }, + { sharingModel: 'private', hook: 'afterUpdate' }, +]; + +for (const { sharingModel, hook } of CELLS) { + describe(`[ADR-0142 D4] concurrent claims — ${sharingModel} OWD, ${HOOK_LABEL[hook]}`, () => { + it(`exactly one claim lands and every loser answers 409 CONCURRENT_UPDATE, over ${ROUNDS} rounds`, async () => { + const engine = await boot({ sharingModel, hook }); + const losers: Record = {}; + for (let round = 0; round < ROUNDS; round++) { + const id = `case_${round}`; + await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); + const settled = await Promise.allSettled([claim(engine, id, A), claim(engine, id, B)]); + const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[A, B][i]] : [])); + expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(1); + for (const r of settled) { + if (r.status === 'rejected') { + const key = outcome(r); + losers[key] = (losers[key] ?? 0) + 1; } - const stored = await engine.findOne(CASE, { where: { id } } as never, SYS); - expect((stored as any)?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0]); } - expect(losers).toEqual({ 'CONCURRENT_UPDATE/409': ROUNDS }); - }); + const stored = await engine.findOne(CASE, { where: { id } } as never, SYS); + expect((stored as any)?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0]); + } + expect(losers).toEqual({ 'CONCURRENT_UPDATE/409': ROUNDS }); }); - } + }); } describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusals — private OWD, hooked object', () => { it('a row that is gone still answers 404 RECORD_NOT_FOUND', async () => { - const engine = await boot({ sharingModel: 'private', beforeHook: true }); + const engine = await boot({ sharingModel: 'private', hook: 'beforeUpdate' }); await seed(engine, { id: 'case_gone', name: 'parked', owner_id: null, queue: QUEUE }); await engine.delete(CASE, { where: { id: 'case_gone' }, context: { isSystem: true } } as never); const err = await claim(engine, 'case_gone', A).then(() => undefined, (e: unknown) => e); @@ -158,7 +175,7 @@ describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusa }); it('a row the caller cannot read answers as not found, never as forbidden', async () => { - const engine = await boot({ sharingModel: 'private', beforeHook: true }); + const engine = await boot({ sharingModel: 'private', hook: 'beforeUpdate' }); await seed(engine, { id: 'case_theirs', name: 'owned', owner_id: B, queue: null }); const err = await claim(engine, 'case_theirs', A).then(() => undefined, (e: unknown) => e); expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 }); From 99c200dbb1606c5ea262dabee408406b49b85498 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:58:17 +0000 Subject: [PATCH 6/7] chore(changeset): name both arms of the update's own unit in the claim-race note The unit opens for a metadata beforeUpdate hook (since 18.6.0) or a blocking / conditioned metadata afterUpdate hook (since before 18.5.0); the note now gives the loser's answer history for each and the post-next() timing for both. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .changeset/35142-claim-race-loser-409.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/.changeset/35142-claim-race-loser-409.md b/.changeset/35142-claim-race-loser-409.md index c912effc8f1..f919e47cb8b 100644 --- a/.changeset/35142-claim-race-loser-409.md +++ b/.changeset/35142-claim-race-loser-409.md @@ -2,15 +2,20 @@ '@objectstack/objectql': patch --- -fix(objectql): the loser of a concurrent update answers 409 CONCURRENT_UPDATE again on an object with a metadata `beforeUpdate` hook +fix(objectql): the loser of a concurrent update answers 409 CONCURRENT_UPDATE on any update that opens its own unit of work Clause-②: no Metadata-protocol: none -Two members of a queue claiming the same parked record at the same moment again get one success and one `409 CONCURRENT_UPDATE`, as ADR-0142 D4 says. Since 18.6.0, on a single-connection store such as SQLite, the loser got `404 RECORD_NOT_FOUND` (private sharing) or `403 PERMISSION_DENIED` (public read) whenever the object carried a metadata `beforeUpdate` hook. The stored owner was always right; only the loser's answer was wrong. +Two members of a queue claiming the same parked record at the same moment get one success and one `409 CONCURRENT_UPDATE`, as ADR-0142 D4 says, on every object. On a single-connection store such as SQLite, the loser got `404 RECORD_NOT_FOUND` (private sharing) or `403 PERMISSION_DENIED` (public read) instead whenever the update opened its own unit of work. An update does that in two cases, and the wrong answer has a different history in each: -The cause: a write on such an object opens its own unit of work, so that a refusal later in the write rolls back what a `beforeUpdate` hook wrote through `ctx.api`. That unit opened around the whole update, the authorization middleware included. On SQLite the second writer then waited for the first one's commit before its authorization gate read the record, and by then the record belonged to someone else. The unit now opens around the engine body only: the middleware runs before it, as it does for an update that opens no unit, and the hooks, the row write and the `after*` chain still run inside it and still roll back together. +- The object carries a metadata `beforeUpdate` hook. This case opens the unit since 18.6.0, so the loser answered 409 in 18.5.0 and 404 / 403 in 18.6.0. It answers 409 again. +- The object carries a blocking (`onError: abort`, the default) or conditioned metadata `afterUpdate` hook. This case already opened the unit in 18.5.0, so the loser answered 404 / 403 in 18.5.0 and 18.6.0. It now answers 409. -What a middleware does after `next()` on such an update now runs after the commit, as it does on an object with no metadata hook. +The stored owner was always right; only the loser's answer was wrong. + +The cause: the unit exists so that a refusal later in the write rolls back what the write's hooks wrote through `ctx.api`, the row included. That unit opened around the whole update, the authorization middleware included. On SQLite the second writer then waited for the first one's commit before its authorization gate read the record, and by then the record belonged to someone else. The unit now opens around the engine body only: the middleware runs before it, as it does for an update that opens no unit, and the hooks, the row write and the `after*` chain still run inside it and still roll back together. + +What a middleware does after `next()` on such an update now runs after the commit, as it does on an object with no metadata update hook. For the `beforeUpdate` case that is how 18.5.0 behaved. For the `afterUpdate` case it is a change from every earlier release, where that code ran inside the unit. Nothing to change in an app. From d9fe9175e7d7e9e702ffc21fe0dd6b7fd13bfdeb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:31:03 +0000 Subject: [PATCH 7/7] chore(changeset): the afterUpdate arm's post-next() timing is a change since 18.0.0, not since forever The door-level unit for a blocking or conditioned metadata afterUpdate hook first shipped in objectql 18.0.0 (17.7.0 has no opensAfterAbortUnit), so the note says 18.0.0 through 18.6.0 rather than every earlier release. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt --- .changeset/35142-claim-race-loser-409.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/35142-claim-race-loser-409.md b/.changeset/35142-claim-race-loser-409.md index f919e47cb8b..60966beb219 100644 --- a/.changeset/35142-claim-race-loser-409.md +++ b/.changeset/35142-claim-race-loser-409.md @@ -16,6 +16,6 @@ The stored owner was always right; only the loser's answer was wrong. The cause: the unit exists so that a refusal later in the write rolls back what the write's hooks wrote through `ctx.api`, the row included. That unit opened around the whole update, the authorization middleware included. On SQLite the second writer then waited for the first one's commit before its authorization gate read the record, and by then the record belonged to someone else. The unit now opens around the engine body only: the middleware runs before it, as it does for an update that opens no unit, and the hooks, the row write and the `after*` chain still run inside it and still roll back together. -What a middleware does after `next()` on such an update now runs after the commit, as it does on an object with no metadata update hook. For the `beforeUpdate` case that is how 18.5.0 behaved. For the `afterUpdate` case it is a change from every earlier release, where that code ran inside the unit. +What a middleware does after `next()` on such an update now runs after the commit, as it does on an object with no metadata update hook. For the `beforeUpdate` case that is how 18.5.0 behaved. For the `afterUpdate` case it is not a return to an earlier release: from 18.0.0, when that unit first shipped, through 18.6.0 that code ran inside the unit. Nothing to change in an app.