Skip to content
Merged
21 changes: 21 additions & 0 deletions .changeset/35142-claim-race-loser-409.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/objectql': patch
---

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 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 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.

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 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.
21 changes: 16 additions & 5 deletions packages/objectql/src/engine-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <T>(body: () => Promise<T>): (() => Promise<T>) =>
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2374,7 +2385,7 @@ export class UpdateFacet {
await this.releaseSecretHandles(object, writtenSecrets, opCtx.context, 'refused');
throw e;
}
});
}));

return opCtx.result;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// 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 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
* 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() {} };

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,
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.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 —
// 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);
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<string, unknown> = {
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<string, unknown>) =>
(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<unknown>): string =>
r.status === 'fulfilled' ? 'fulfilled' : `${(r.reason as any)?.code}/${(r.reason as any)?.status}`;

const HOOK_LABEL: Record<HookShape, string> = {
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<string, number> = {};
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', 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);
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', 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 });
const stored = await engine.findOne(CASE, { where: { id: 'case_theirs' } } as never, SYS);
expect((stored as any)?.owner_id).toBe(B);
});
});
Loading