Skip to content

Commit c480f33

Browse files
fix(objectql): the loser of a concurrent update answers 409 again on an object with a metadata beforeUpdate hook (#35165)
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt Fixes #35142 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:凡是自开事务单元的 update(对象带元数据 `beforeUpdate` 钩子,或带阻断式 / 带条件的元数据 `afterUpdate` 钩子),「after-abort 事务单元」原先包住整个写入(含授权中间件),现在只包住引擎本体(钩子、写行、after 链);中间件在事务开启之前运行,与无钩子对象一致。 - **为什么改**:在 SQLite(单连接)上两人同时认领同一条记录时,输家等赢家提交后才做授权读,被拒为 404(private)或 403(public_read),而不是 ADR-0142 D4 承诺的 `409 CONCURRENT_UPDATE`。`beforeUpdate` 钩子一支自 18.6.0 起出错(18.5.0 为 409);阻断式 `afterUpdate` 钩子一支在 18.5.0 已是 404/403。HotCRM 的 18.6.0 升级被它挡住。 - **风险与回滚**:风险在于中间件 `next()` 之后的代码对这类 update 改为在提交之后运行,与无钩子对象一致;`beforeUpdate` 一支等于回到 18.5.0,阻断式 `afterUpdate` 一支则是新变化(18.0.0 至 18.6.0 都在事务内运行)。钩子侧写回滚(#34503 的目的)不变。回滚 = revert 本 PR 的 `engine-update.ts` 一处改动。 - **先看**:`packages/objectql/src/engine-update.ts`(门入口 `ownUnit`/`inOwnUnit` 与 `executeWithMiddleware(opCtx, inOwnUnit(...))` 两处);`packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts`。 - **两分钟验证**:`cd packages/plugins/plugin-security && pnpm exec vitest run src/ownership-claim-race-sqlite.test.ts`,预期 7/7 通过;五格各 25 轮,输家全部为 `CONCURRENT_UPDATE/409`。 - **需要你做的**:无,席位落地。 ## What changes `UpdateFacet.update` no longer re-enters itself inside `inAfterAbortUnit` at the door. It decides at the door whether the write needs its own unit (`opensAfterAbortUnit`, unchanged), and wraps only the executor it hands to `executeWithMiddleware` in that unit. So the middleware chain (the authorization gate's caller-scoped pre-image read among it) runs before `BEGIN`, the way it does for an update that opens no unit, and everything the unit exists for (the `before*` hooks and their `ctx.api` side writes, the row write, the `after*` chain) still runs inside it and rolls back together. The change applies to any update that opens its own unit, which is `opensAfterAbortUnit`'s whole answer, and that predicate has two arms: - **`sideWriting`: a metadata `beforeUpdate` hook.** `a8e09bbc31` (#34503) added this term (traced in the card's trace comment), new in 18.6.0. Race answer: `409` in 18.5.0, `404` / `403` in 18.6.0, `409` again here. - **`aborting`: a blocking (`onError` `abort`, the default) or conditioned metadata `afterUpdate` hook (#22782).** Its door-level unit already shipped in `@objectstack/objectql@18.5.0`: `engine-update.ts:151-153` at tag `@objectstack/objectql@18.5.0` (`b914e7247f`) reads `if (this.opensAfterAbortUnit('afterUpdate', object, options?.context)) { return this.inAfterAbortUnit(() => this.update(object, data, options)); }`, and that tag's `opensAfterAbortUnit` has the `aborting` term and no `sideWriting` term. Race answer: `404` / `403` already in 18.5.0 and in 18.6.0 (the new fifth cell reads `RECORD_NOT_FOUND/404` x25 on main's `engine-update.ts`), `409` here for the first time. With the unit around the whole door, the SQLite driver's single connection made the loser's whole write, gate included, wait for the winner's commit. The gate then read a row owned by the winner and refused: 404 under `private`, 403 under `public_read`. The conditional write whose 0-row answer is `ConcurrentUpdateError` was never reached. Insert and delete keep their door-level unit. Measured with the same rig, 20 rounds per cell, `private` and `public_read`, with and without a metadata `before*` hook on the verb: - Concurrent insert of one id: the loser answers `DUPLICATE_RECORD/409` in all four cells. No race-shaped defect, so no change. - Concurrent delete of one row: with no hook the loser's `delete` resolves `false`; with a hook it answers `RECORD_NOT_FOUND/404`. Both say the row is gone, which it is. D4 governs updates, and the 404 is not a lie about a readable row. So it stays out of this PR's scope (see Acceptance notes). What a middleware does after `next()` on an update that opens its own unit now runs after the commit, as it does on every update that opens no unit. For the `beforeUpdate` arm that is how 18.5.0 behaved. For the `afterUpdate` arm it is a change, not a return: in every release from 18.0.0 (the first `@objectstack/objectql` tag whose source calls `opensAfterAbortUnit`; 17.7.0 has 0 hits) through 18.6.0, that code ran inside the row's unit on an object with a blocking or conditioned metadata `afterUpdate` hook. The post-`next()` code that runs on an update in this tree: - plugin-security authz: the `postHookWriteImageCheck` honoured-flag assertion (it fails closed if the engine never ran the seam; the engine always runs it inside the executor), then field-level masking of the result (no write). - plugin-security start hooks: the platform-admin bootstrap replay (`shouldReplayBootstrapFor`) and the `sys_member` org-admin grant reconcile (writes, `sys_member` only). - organizations, plugin-auth, runtime app-plugin, plugin-sharing: post-`next()` branches that act on insert/create only. On a `sys_member` update that opens its own unit, the org-admin grant reconcile is no longer in the same unit as the row. With a metadata `beforeUpdate` hook that matches 18.5.0; with a blocking or conditioned metadata `afterUpdate` hook it is new. Either way it matches every unhooked object. ## Tests New pin `packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts`: the real `ObjectQL`, `SqlDriver` on better-sqlite3 `:memory:`, `SecurityPlugin` and `SharingService`. It has five cells, 25 rounds each: `private`/`public_read`, each with and without a metadata `beforeUpdate` hook, plus `private` on an object whose only metadata hook is a blocking `afterUpdate` (`onError: 'abort'`), which holds the predicate's other arm. Every round asserts that exactly one claim fulfils, that the loser's `{code}/{status}` is `CONCURRENT_UPDATE/409`, and that the stored owner is the winner. Two non-regression cases run on the hooked `private` object: a deleted row answers `RECORD_NOT_FOUND/404`, and a row owned by someone else answers as not found, never as forbidden (no existence leak). <details><summary>Red on main: test commit with origin/main's engine-update.ts (blob dc1d739)</summary> ``` × exactly one claim lands ... (private, hooked) AssertionError: expected { 'RECORD_NOT_FOUND/404': 25 } to deeply equal { 'CONCURRENT_UPDATE/409': 25 } × exactly one claim lands ... (public_read, hooked) AssertionError: expected { 'PERMISSION_DENIED/403': 25 } to deeply equal { 'CONCURRENT_UPDATE/409': 25 } unhooked cells and the no-leak case: green ``` Fifth cell (blocking `afterUpdate` only), commit `415eefd791` with origin/main `7d8dcf693a`'s `engine-update.ts` (blob `71476062da`, door re-entry line present x1), swapped in a script with an EXIT/INT/TERM trap: ``` FAIL ... private OWD, metadata beforeUpdate hook (the unit opens) FAIL ... private OWD, only a blocking metadata afterUpdate hook (the unit opens) AssertionError: expected { 'RECORD_NOT_FOUND/404': 25 } to deeply equal { 'CONCURRENT_UPDATE/409': 25 } FAIL ... public_read OWD, metadata beforeUpdate hook (the unit opens) AssertionError: expected { 'PERMISSION_DENIED/403': 25 } to deeply equal { 'CONCURRENT_UPDATE/409': 25 } Tests 3 failed | 4 passed (7) restore: blob b8273f9 == HEAD, git diff HEAD empty ``` (A third red in that run came from the not-found case's own setup, which deleted without a principal. Commit `06f9b81ab8` fixed the setup; the case is green on main and on the fix.) </details> <details><summary>Green on the fix: 4 runs x 25 rounds per cell (four cells), then 2 runs with the fifth cell</summary> ``` Test Files 1 passed (1) Tests 6 passed (6) (run 1, then 3 more runs: 6/6 each) five cells, at 415eefd and again at 99c200d (same test and engine bytes as head d9fe917): Test Files 1 passed (1) Tests 7 passed (7) typecheck @objectstack/plugin-security (tsc + check:test-typecheck): exit 0 ``` </details> <details><summary>Ablation: the door-level re-entry restored through scripts/ablation-replace.mjs</summary> ``` anchor x1 -> x0, blob b8273f9 -> d59167c32afe × private, hooked: { 'RECORD_NOT_FOUND/404': 25 } × public_read, hooked: { 'PERMISSION_DENIED/403': 25 } Tests 2 failed | 4 passed (6) restore: blob == HEAD (b8273f9) and git diff HEAD is empty ``` `@objectstack/objectql` resolves to `src/` in this suite (the plugin-security vitest alias), so the mutation reaches the run with no `dist/` leg. </details> <details><summary>After-abort unit pins (#34412 / #34503) and the objectql suite</summary> ``` engine-after-hook-abort-unit.test.ts, engine-hook-stale-summary-refusal.test.ts, ownership-queue.test.ts: 3 files, 74 tests passed @objectstack/objectql (vitest --project local): Test Files 611 passed (611), Tests 13791 passed (13791) typecheck @objectstack/objectql, @objectstack/plugin-security: exit 0 ``` </details> ## Acceptance notes - Concurrent delete answers the loser differently by unit shape: `false` with no metadata `beforeDelete` hook, `RECORD_NOT_FOUND/404` with one. No declared contract picks between them, and neither misreports a readable row. Noted, not filed. - Insert and delete keep their door-level unit, so their middleware's post-`next()` work stays inside it while update's does not. Whether they should move the same way is carried by #35167. - overlap-check at `d9fe9175e7`: origin/main and #34978 (shares `engine-update.ts`) both merge cleanly. ## Verification On head `d9fe9175e7` (merge base `99a0e4fbf`; overlap-check against origin/main and #34978: merges cleanly, so main is not merged in again), `node scripts/pm/dispatch-gates.mjs --commands` derived 70 families, and all 70 exit 0 (`check:dual-build-cjs-loads` and `check:i18n` found their dists this time and measured). `check:query-options-erasure` and `check:type-check-debt` each outran a 240 s per-gate runner timeout and exited 0 when rerun alone. `--ran` reconciliation with exit codes: 70 derived, 70 run, 0 NOT-MEASURED, 0 UNRUN. Between `99c200dbb1` and `d9fe9175e7` only the changeset text moved, so the race-test runs above (7/7 at `99c200dbb1`) read the same test and engine bytes. `test:repo` and the plugin-security suite outside the new file are left to CI (Test Core). The objectql public surface is byte-unchanged. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c9b3f7a commit c480f33

3 files changed

Lines changed: 222 additions & 5 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): the loser of a concurrent update answers 409 CONCURRENT_UPDATE on any update that opens its own unit of work
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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:
11+
12+
- 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.
13+
- 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.
14+
15+
The stored owner was always right; only the loser's answer was wrong.
16+
17+
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.
18+
19+
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.
20+
21+
Nothing to change in an app.

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

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,20 @@ export class UpdateFacet {
158158
object = this.resolveObjectName(object);
159159
// [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's
160160
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
161-
if (this.opensAfterAbortUnit('afterUpdate', object, options?.context)) {
162-
return this.inAfterAbortUnit(() => this.update(object, data, options));
163-
}
161+
//
162+
// [#35142] The unit opens around the ENGINE BODY (the executor below), not
163+
// around the door: the middleware chain runs first, outside it, as it does
164+
// for a write that opens no unit. Opened around the door, the unit enclosed
165+
// the authorization gate's reads too, and on a single-connection store
166+
// (SQLite) a second writer's whole write then waited for the first one's
167+
// commit: the loser of a claim race (ADR-0142 D4) read the claimed row in
168+
// its gate and was refused there as not found or forbidden, never reaching
169+
// the conditional write whose 0-row answer is `ConcurrentUpdateError`.
170+
// Everything the unit exists for — the `before*` hooks' `ctx.api` writes,
171+
// the row, the `after*` chain — runs inside the executor.
172+
const ownUnit = this.opensAfterAbortUnit('afterUpdate', object, options?.context);
173+
const inOwnUnit = <T>(body: () => Promise<T>): (() => Promise<T>) =>
174+
ownUnit ? () => this.inAfterAbortUnit(body) : body;
164175
this.logger.debug('Update operation starting', { object });
165176
this.assertWriteAllowed(object, 'update');
166177
// [#8844] See the insert face — an organization row that changes identity
@@ -461,7 +472,7 @@ export class UpdateFacet {
461472
throw new ReadonlyFieldRejectedError(object, fields, strictDrops);
462473
};
463474

464-
await this.executeWithMiddleware(opCtx, async () => {
475+
await this.executeWithMiddleware(opCtx, inOwnUnit(async () => {
465476
// [ADR-0139 D1] A write's predicate never carries a `ReadableIds` leaf.
466477
// The door refused the caller's; this refuses one the middleware chain
467478
// wrote — here, at the executor's entry, because the prior-row reads
@@ -2374,7 +2385,7 @@ export class UpdateFacet {
23742385
await this.releaseSecretHandles(object, writtenSecrets, opCtx.context, 'refused');
23752386
throw e;
23762387
}
2377-
});
2388+
}));
23782389

23792390
return opCtx.result;
23802391
}
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0142 D4] Two members of one queue claim the same parked row at the same
5+
* moment, over the REAL stack: `ObjectQL`, `SqlDriver` on better-sqlite3
6+
* `:memory:` (a single-connection pool), `SecurityPlugin` and
7+
* `SharingService`. Exactly one claim lands; the loser answers
8+
* `409 CONCURRENT_UPDATE`, never "not found" and never "forbidden" because it
9+
* lost a race; the stored owner is the winner.
10+
*
11+
* The cells cross the two answers a lost race used to get with the two unit
12+
* shapes the engine has: an object with no metadata update hook opens no unit
13+
* of work for the write; one with a metadata `beforeUpdate` hook opens the
14+
* after-abort unit (`opensAfterAbortUnit`'s side-writing term), and so does one
15+
* whose only metadata hook is a blocking `afterUpdate` (its aborting term, the
16+
* fifth cell). When that unit enclosed the middleware chain, the loser's whole write — the authorization gate's
17+
* caller-scoped pre-image read included — waited on the single connection for
18+
* the winner's commit, and then read a row it no longer owned: `private`
19+
* answered 404 (it cannot see the row), `public_read` answered 403 (it can see
20+
* it but not edit it). The unit now opens around the engine body only, so both
21+
* gates read the parked row and the conditional write decides.
22+
*
23+
* The rest of the file is the non-regression half: a true not-found still
24+
* answers 404, and a row the caller cannot read still answers as not found
25+
* (no existence leak), on the hooked object whose writes open the unit.
26+
*/
27+
28+
import { describe, it, expect, vi } from 'vitest';
29+
import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql';
30+
import { SqlDriver } from '@objectstack/driver-sql';
31+
import { SharingService, buildSharingMiddleware, SysRecordShare } from '@objectstack/plugin-sharing';
32+
import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity';
33+
import { PermissionSetSchema } from '@objectstack/spec/security';
34+
import { SecurityPlugin } from './security-plugin.js';
35+
import { defaultPermissionSets } from './objects/default-permission-sets.js';
36+
import { SysUserPosition } from './objects/sys-user-position.object.js';
37+
import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js';
38+
import { wireEngineSecuritySource } from './engine-security-source.testkit.js';
39+
40+
const SYS = { context: { isSystem: true } } as never;
41+
const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!;
42+
const CASE = 'cq_case';
43+
const ORG = 'org_cq';
44+
const QUEUE = 'cq_intake';
45+
const A = 'usr_cq_a';
46+
const B = 'usr_cq_b';
47+
/** Rounds per cell: the race is a scheduling fact, so one round proves little. */
48+
const ROUNDS = 25;
49+
const SET = PermissionSetSchema.parse({
50+
name: 'cq_member',
51+
objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
52+
});
53+
const SETS = [MEMBER_DEFAULT, SET];
54+
const memberOf = (userId: string) => ({
55+
userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER',
56+
});
57+
const QUIET = { debug() {}, info() {}, warn() {}, error() {} };
58+
59+
type HookShape = 'none' | 'beforeUpdate' | 'afterUpdate';
60+
61+
async function boot(opts: { sharingModel: 'private' | 'public_read'; hook: HookShape }) {
62+
const engine = new ObjectQL();
63+
engine.registerDriver(
64+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never,
65+
true,
66+
);
67+
await engine.init();
68+
engine.registerApp({
69+
id: 'com.objectstack.qa.claim-race', name: 'claim race', version: '1.0.0', type: 'plugin', scope: 'system',
70+
objects: [SysRecordShare, SysUser, SysOrganization, SysMember, SysUserPosition, SysUserPermissionSet, {
71+
name: CASE, label: 'Case', sharingModel: opts.sharingModel, tenancy: { enabled: false },
72+
fields: { id: { name: 'id', type: 'text', primaryKey: true }, name: { name: 'name', type: 'text' } },
73+
}],
74+
} as never);
75+
await engine.syncSchemas();
76+
if (opts.hook !== 'none') {
77+
// A metadata-bound hook that does nothing: its presence alone is what
78+
// makes the engine open the after-abort unit for this object's updates —
79+
// any `beforeUpdate` (side-writing term), or a blocking `afterUpdate` whose
80+
// `onError` is `abort` (aborting term).
81+
const hook = opts.hook === 'afterUpdate'
82+
? { name: 'cq_after', object: CASE, events: ['afterUpdate'], onError: 'abort', handler: () => {} }
83+
: { name: 'cq_touch', object: CASE, events: ['beforeUpdate'], handler: () => {} };
84+
bindHooksToEngine(engine as never, [hook as never], { packageId: 'app:cq', logger: QUIET as never });
85+
}
86+
await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@cq.test` })), SYS);
87+
await engine.insert('sys_organization', [{ id: ORG, name: 'CQ', slug: 'cq' }], SYS);
88+
let securityService: unknown;
89+
let sharing: SharingService | undefined;
90+
const queues = {
91+
queuesOf: async (u: string) => ([A, B].includes(u) ? [QUEUE] : []),
92+
isMember: async (u: string, q: string) => q === QUEUE && [A, B].includes(u),
93+
};
94+
const services: Record<string, unknown> = {
95+
manifest: { register: vi.fn() },
96+
objectql: engine,
97+
metadata: {
98+
get: async (type: string, name: string) =>
99+
type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null,
100+
list: async () => SETS,
101+
},
102+
get sharing() { return sharing; },
103+
};
104+
const ctx = {
105+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
106+
registerService: (name: string, svc: unknown) => { if (name === 'security') securityService = svc; },
107+
hook: () => undefined,
108+
getService: (name: string) => {
109+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
110+
return services[name];
111+
},
112+
};
113+
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
114+
await plugin.init(ctx as never);
115+
await plugin.start(ctx as never);
116+
wireEngineSecuritySource(engine, () => plugin);
117+
sharing = new SharingService({ engine: engine as never, securityService: () => securityService as never, ownershipQueues: () => queues as never });
118+
engine.registerMiddleware(buildSharingMiddleware(sharing, ctx.logger) as never, { object: '*' });
119+
return engine;
120+
}
121+
122+
/** Seed a row straight through the driver, below every gate. */
123+
const seed = (engine: ObjectQL, row: Record<string, unknown>) =>
124+
(engine as any).getDriver(CASE).create(CASE, row);
125+
const claim = (engine: ObjectQL, id: string, user: string) =>
126+
engine.update(CASE, { id, owner_id: user }, { where: { id }, context: memberOf(user) } as never);
127+
const outcome = (r: PromiseSettledResult<unknown>): string =>
128+
r.status === 'fulfilled' ? 'fulfilled' : `${(r.reason as any)?.code}/${(r.reason as any)?.status}`;
129+
130+
const HOOK_LABEL: Record<HookShape, string> = {
131+
none: 'no hook (no unit)',
132+
beforeUpdate: 'metadata beforeUpdate hook (the unit opens)',
133+
afterUpdate: 'only a blocking metadata afterUpdate hook (the unit opens)',
134+
};
135+
const CELLS: ReadonlyArray<{ sharingModel: 'private' | 'public_read'; hook: HookShape }> = [
136+
{ sharingModel: 'private', hook: 'none' },
137+
{ sharingModel: 'private', hook: 'beforeUpdate' },
138+
{ sharingModel: 'public_read', hook: 'none' },
139+
{ sharingModel: 'public_read', hook: 'beforeUpdate' },
140+
{ sharingModel: 'private', hook: 'afterUpdate' },
141+
];
142+
143+
for (const { sharingModel, hook } of CELLS) {
144+
describe(`[ADR-0142 D4] concurrent claims — ${sharingModel} OWD, ${HOOK_LABEL[hook]}`, () => {
145+
it(`exactly one claim lands and every loser answers 409 CONCURRENT_UPDATE, over ${ROUNDS} rounds`, async () => {
146+
const engine = await boot({ sharingModel, hook });
147+
const losers: Record<string, number> = {};
148+
for (let round = 0; round < ROUNDS; round++) {
149+
const id = `case_${round}`;
150+
await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE });
151+
const settled = await Promise.allSettled([claim(engine, id, A), claim(engine, id, B)]);
152+
const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[A, B][i]] : []));
153+
expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(1);
154+
for (const r of settled) {
155+
if (r.status === 'rejected') {
156+
const key = outcome(r);
157+
losers[key] = (losers[key] ?? 0) + 1;
158+
}
159+
}
160+
const stored = await engine.findOne(CASE, { where: { id } } as never, SYS);
161+
expect((stored as any)?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0]);
162+
}
163+
expect(losers).toEqual({ 'CONCURRENT_UPDATE/409': ROUNDS });
164+
});
165+
});
166+
}
167+
168+
describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusals — private OWD, hooked object', () => {
169+
it('a row that is gone still answers 404 RECORD_NOT_FOUND', async () => {
170+
const engine = await boot({ sharingModel: 'private', hook: 'beforeUpdate' });
171+
await seed(engine, { id: 'case_gone', name: 'parked', owner_id: null, queue: QUEUE });
172+
await engine.delete(CASE, { where: { id: 'case_gone' }, context: { isSystem: true } } as never);
173+
const err = await claim(engine, 'case_gone', A).then(() => undefined, (e: unknown) => e);
174+
expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 });
175+
});
176+
177+
it('a row the caller cannot read answers as not found, never as forbidden', async () => {
178+
const engine = await boot({ sharingModel: 'private', hook: 'beforeUpdate' });
179+
await seed(engine, { id: 'case_theirs', name: 'owned', owner_id: B, queue: null });
180+
const err = await claim(engine, 'case_theirs', A).then(() => undefined, (e: unknown) => e);
181+
expect(err).toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 });
182+
const stored = await engine.findOne(CASE, { where: { id: 'case_theirs' } } as never, SYS);
183+
expect((stored as any)?.owner_id).toBe(B);
184+
});
185+
});

0 commit comments

Comments
 (0)