Skip to content
15 changes: 15 additions & 0 deletions .changeset/39065-claim-no-longer-waiting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/plugin-detail': patch
'@object-ui/i18n': patch
---

fix(console): a claim answered 404 or 403 says the record is no longer waiting to be claimed

Clause-②: no
Metadata-protocol: none

Two queue members who claim the same record at once still end with exactly one owner. What the loser is told depends on when the server checks its claim: a claim checked while the record was still unowned answers `409 CONCURRENT_UPDATE`, and a claim checked after the other member's claim committed answers what any request gets at that moment, `404 RECORD_NOT_FOUND` when the record left the caller's sight (a `private` object) or `403 PERMISSION_DENIED` when the caller can still read it. Through the HTTP data door the late answers are the common ones. Status codes, messages and the ownership gate are unchanged.

`claimQueuedRecord` (`@object-ui/plugin-detail`) now reports a `404` or `403` as a new outcome, `{ outcome: 'unavailable', error }`, where it reported `refused` before. The Console's record page shows one sentence for it, "This record is no longer waiting to be claimed.", and re-reads the record, as it does for a `409`. The sentence does not say someone else claimed the record, because a `404` is also what a deleted record answers. `@object-ui/i18n` carries the sentence as `detail.claimUnavailable` in every shipped locale.

If you call `claimQueuedRecord` yourself and branch on its outcome, handle `unavailable` beside `taken`: both mean the record is not yours to claim, so reload it or move on. Any other refusal is still `refused`.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,24 @@
* [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.
* `SharingService`. Exactly one claim lands and the stored owner is the winner:
* that is the invariant, in every cell of this file.
*
* The cells cross the two answers a lost race used to get with the two unit
* What the loser is told depends on when its authorization gate reads the row
* (ADR-0142 D4 as ruled on #39065, option B). A loser whose gate read the row
* unowned, before the winner committed, answers `409 CONCURRENT_UPDATE`. A
* loser whose gate runs after the winner's commit is answered as any request
* is at that moment: `404 RECORD_NOT_FOUND` under `private` (the row left its
* sight) and `403 PERMISSION_DENIED` under `public_read` (it can read the row
* but not edit it). So every loser is answered from the set 409, 404, 403.
*
* The lockstep cells below start both claims in the same tick with no I/O on
* either path, so both gates read the parked row before either commits, and
* they pin the 409. The I/O-tick cells put one awaited I/O tick ahead of one
* claimant, the order a cold first request or any networked door produces,
* and pin the invariant and the set.
*
* The lockstep 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
Expand All @@ -25,6 +38,9 @@
* (no existence leak), on the hooked object whose writes open the unit.
*/

import { access } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it, expect, vi } from 'vitest';
import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
Expand All @@ -50,7 +66,20 @@ const SET = PermissionSetSchema.parse({
name: 'cq_member',
objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
});
const SETS = [MEMBER_DEFAULT, SET];
/** A user in no queue, holding no share: a transfer-grant holder from outside the queue. */
const C = 'usr_cq_c';
/** The two permissions that satisfy the gate's transfer grant on the case object. */
const TRANSFER_SETS = {
allowTransfer: PermissionSetSchema.parse({
name: 'cq_transfer',
objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowTransfer: true } },
}),
modifyAllRecords: PermissionSetSchema.parse({
name: 'cq_modify_all',
objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, modifyAllRecords: true } },
}),
} as const;
const SETS = [MEMBER_DEFAULT, SET, TRANSFER_SETS.allowTransfer, TRANSFER_SETS.modifyAllRecords];
const memberOf = (userId: string) => ({
userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER',
});
Expand Down Expand Up @@ -83,7 +112,7 @@ async function boot(opts: { sharingModel: 'private' | 'public_read'; hook: HookS
: { 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_user', [A, B, C].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;
Expand Down Expand Up @@ -165,6 +194,117 @@ for (const { sharingModel, hook } of CELLS) {
});
}

/** The answers a losing claim may get (ruling B on #39065), as `code/status`. */
const LOSER_ANSWERS = new Set(['CONCURRENT_UPDATE/409', 'RECORD_NOT_FOUND/404', 'PERMISSION_DENIED/403']);
/**
* One real I/O tick: a failed `fs.access` completes on the libuv pool, so its
* callback waits for the event loop while the other claimant's synchronous
* better-sqlite3 write runs to its commit.
*/
const ioTick = () => access(join(tmpdir(), `claim-race-io-tick-${process.pid}-missing`)).catch(() => undefined);

for (const sharingModel of ['private', 'public_read'] as const) {
describe(`[ADR-0142 D4] concurrent claims, one I/O tick ahead of one claimant — ${sharingModel} OWD`, () => {
it(`exactly one claim lands and the loser is answered from 409, 404, 403, over ${ROUNDS} rounds`, async () => {
const engine = await boot({ sharingModel, hook: 'none' });
const losers: Record<string, number> = {};
for (let round = 0; round < ROUNDS; round++) {
const id = `case_io_${round}`;
await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE });
// The tick goes ahead of A on even rounds and of B on odd ones, so
// neither claimant's position decides the outcome.
const [first, late] = round % 2 === 0 ? [B, A] : [A, B];
const settled = await Promise.allSettled([
claim(engine, id, first),
ioTick().then(() => claim(engine, id, late)),
]);
const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[first, late][i]] : []));
expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(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]);
for (const r of settled) {
if (r.status === 'rejected') {
const key = outcome(r);
expect(LOSER_ANSWERS.has(key), `round ${round}: loser answered ${key}`).toBe(true);
losers[key] = (losers[key] ?? 0) + 1;
}
}
}
// The tick did reach the gate: at least one loser was answered after the
// winner's commit (404 or 403). Without this the cells would only repeat
// the lockstep ones above.
const late = Object.entries(losers).filter(([k]) => k !== 'CONCURRENT_UPDATE/409').reduce((n, [, c]) => n + c, 0);
expect(late, JSON.stringify(losers)).toBeGreaterThan(0);
});
});
}

/**
* Holders of the transfer grant, measured and pinned as they stand (contract
* review 7365351117 on PR #39233).
*
* Ruling B's invariant above, exactly one owner and each loser answered 409,
* 404 or 403, is for claimants WITHOUT the transfer grant. The grant is the
* gate's `hasTransferGrant()`: `allowTransfer`, or `modifyAllRecords`, which
* satisfies it alone. A holder's owner write is a transfer, not a claim: it
* skips the conditional write, so two holders both succeed and the last
* writer owns the row. A holder is not a loser.
*
* `allowTransfer` opens an ownership change only on a row the holder can
* already read and edit, because the row check runs first. So a holder of
* `allowTransfer` alone, outside the queue and with no share, who writes after
* a member's claim committed, is answered as any request is: 404 under
* `private`, 403 under `public_read`, and the member stays the owner.
* `modifyAllRecords` opens the row too, so that holder's write lands.
*/
const TRANSFER_ROUNDS = 4;
const holderOf = (userId: string, grant: keyof typeof TRANSFER_SETS) => ({
...memberOf(userId), permissions: [TRANSFER_SETS[grant].name, SET.name, 'member_default'],
});
const transferAs = (engine: ObjectQL, id: string, user: string, grant: keyof typeof TRANSFER_SETS) =>
engine.update(CASE, { id, owner_id: user }, { where: { id }, context: holderOf(user, grant) } as never);
const answerOf = (p: Promise<unknown>): Promise<string> =>
p.then(() => 'ok', (e: unknown) => `${(e as any)?.code}/${(e as any)?.status}`);
const ownerOf = async (engine: ObjectQL, id: string): Promise<unknown> =>
((await engine.findOne(CASE, { where: { id } } as never, SYS)) as any)?.owner_id;

for (const sharingModel of ['private', 'public_read'] as const) {
describe(`[ADR-0142 D4] transfer-grant holders are not claimants — ${sharingModel} OWD`, () => {
for (const grant of ['allowTransfer', 'modifyAllRecords'] as const) {
it(`two ${grant} holders writing an unowned record at once both succeed; the last writer owns it`, async () => {
const engine = await boot({ sharingModel, hook: 'none' });
for (let round = 0; round < TRANSFER_ROUNDS; round++) {
const id = `case_tx_${grant}_${round}`;
await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE });
const answers = await Promise.all([answerOf(transferAs(engine, id, A, grant)), answerOf(transferAs(engine, id, B, grant))]);
expect(answers, `round ${round}`).toEqual(['ok', 'ok']);
expect(await ownerOf(engine, id), `round ${round}: the last writer owns the row`).toBe(B);
}
});
}

const late: Record<'allowTransfer' | 'modifyAllRecords', { answer: string; owner: string }> = {
modifyAllRecords: { answer: 'ok', owner: C },
allowTransfer: sharingModel === 'private'
? { answer: 'RECORD_NOT_FOUND/404', owner: A }
: { answer: 'PERMISSION_DENIED/403', owner: A },
};
for (const grant of ['modifyAllRecords', 'allowTransfer'] as const) {
const { answer, owner } = late[grant];
it(`a ${grant} holder outside the queue, after a member's claim committed: ${answer}, owner ${owner === C ? 'moves to the holder' : 'stays the member'}`, async () => {
const engine = await boot({ sharingModel, hook: 'none' });
for (let round = 0; round < TRANSFER_ROUNDS; round++) {
const id = `case_late_${grant}_${round}`;
await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE });
expect(await answerOf(claim(engine, id, A)), `round ${round}: the member's claim`).toBe('ok');
expect(await answerOf(transferAs(engine, id, C, grant)), `round ${round}: the holder's write`).toBe(answer);
expect(await ownerOf(engine, id), `round ${round}: the stored owner`).toBe(owner);
}
});
}
});
}

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' });
Expand Down
128 changes: 128 additions & 0 deletions packages/verify/src/claim-race-http-door-39065.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// #39065, ruling B on ADR-0142 D4: two members of one queue claim the same
// parked record at once through the real HTTP data door
// (`PATCH /api/v1/data/OBJECT/ID` with `{ owner_id: <self> }`), on a booted
// stack with the real SecurityPlugin, sharing and a declared queue whose
// members are a position.
//
// The invariant is that exactly one claim lands and the stored owner is the
// winner. The loser is answered from the set 409, 404, 403: `409
// CONCURRENT_UPDATE` when its gate read the record unowned before the winner
// committed, otherwise what any request gets at that moment, `404
// RECORD_NOT_FOUND` where the record left its sight (`private`) and `403
// PERMISSION_DENIED` where it can still read it (`public_read`). Through this
// door one request usually runs to its commit before the other reads its
// session, so the late answers are the common ones here; which of the three a
// loser gets is timing, and is not pinned.

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { defineStack } from '@objectstack/spec';
// The harness loads these two inside a function body; paid here, during collection, not in a clocked window.
import '@objectstack/service-datasource';
import '@objectstack/service-automation';
import { PermissionSetSchema } from '@objectstack/spec/security';
import { bootStack, type VerifyStack } from './harness.js';
import { warmUpBoot } from './boot-warm-up.testkit.js';

// Booting the full in-process stack runs well past vitest's 5s default.
const BOOT_TIMEOUT = 120_000;

await warmUpBoot();

const PRIVATE_CASE = 'cqh_case';
const PUBLIC_CASE = 'cqh_public_case';
const QUEUE = 'cqh_intake';
const POSITION = 'cqh_agent';
/** Rounds per object: the race is a scheduling fact, so one round proves little. */
const ROUNDS = 4;
/** The answers a losing claim may get, as `code/status`. */
const LOSER_ANSWERS = new Set(['CONCURRENT_UPDATE/409', 'RECORD_NOT_FOUND/404', 'PERMISSION_DENIED/403']);

const memberSet = PermissionSetSchema.parse({
name: 'cqh_member',
label: 'Claim race member',
isDefault: true,
objects: Object.fromEntries(
[PRIVATE_CASE, PUBLIC_CASE].map((o) => [o, { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }]),
),
});

const config = () =>
defineStack({
manifest: { id: 'com.example.claim-race-http', namespace: 'cqh', version: '0.0.1', type: 'app', name: 'Claim race over HTTP' },
objects: [
{ name: PRIVATE_CASE, label: 'Case', pluralLabel: 'Cases', sharingModel: 'private', fields: { name: { type: 'text', label: 'Name' } } },
{ name: PUBLIC_CASE, label: 'Public case', pluralLabel: 'Public cases', sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } } },
],
queues: [{ name: QUEUE, label: 'Intake', members: [{ type: 'position', value: POSITION }] }],
permissions: [memberSet],
} as never);

interface Member {
token: string;
userId: string;
}

describe('[ADR-0142 D4, #39065] concurrent claims through the HTTP data door', () => {
let stack: VerifyStack;
let a: Member;
let b: Member;
let organizationId: string;

beforeAll(async () => {
stack = await bootStack(config());
const members: Member[] = [];
for (const email of ['cqh-a@verify.test', 'cqh-b@verify.test']) {
const token = await stack.signUp(email);
const ctx = await stack.contextFor(token);
members.push({ token, userId: String(ctx.userId) });
organizationId = String(ctx.tenantId);
}
[a, b] = members;
const ql = (await stack.kernel.getServiceAsync('objectql')) as {
insert(object: string, row: Record<string, unknown>, opts: unknown): Promise<unknown>;
};
for (const m of members) {
await ql.insert(
'sys_user_position',
{ user_id: m.userId, position: POSITION, organization_id: organizationId },
{ context: { isSystem: true } },
);
}
}, BOOT_TIMEOUT);

afterAll(async () => {
await stack?.stop();
});

/** One claim through the door: `ok`, or the loser's `code/status`. */
const claim = async (object: string, id: string, m: Member): Promise<string> => {
const res = await stack.apiAs(m.token, 'PATCH', `/data/${object}/${id}`, { owner_id: m.userId });
if (res.ok) return 'ok';
const body = (await res.json()) as { code?: unknown; error?: { code?: unknown } };
return `${String(body.code ?? body.error?.code)}/${res.status}`;
};

for (const object of [PRIVATE_CASE, PUBLIC_CASE]) {
it(`${object}: exactly one claim lands and the loser is answered from 409, 404, 403, over ${ROUNDS} rounds`, async () => {
const losers: Record<string, number> = {};
for (let round = 0; round < ROUNDS; round++) {
const id = `${object}_${round}`;
await stack.hooks.run(object, 'insert', { id, name: 'parked', owner_id: null, queue: QUEUE, organization_id: organizationId }, { system: true });
// Alternate who sends first, so neither member's position decides.
const pair = round % 2 === 0 ? [a, b] : [b, a];
const answers = await Promise.all(pair.map((m) => claim(object, id, m)));
const won = pair.filter((_, i) => answers[i] === 'ok');
expect(won.map((m) => m.userId), `round ${round}: ${answers.join(' | ')}`).toHaveLength(1);
const [stored] = await stack.rows(object, { id });
expect(stored?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0].userId);
for (const answer of answers.filter((x) => x !== 'ok')) {
expect(LOSER_ANSWERS.has(answer), `round ${round}: loser answered ${answer}`).toBe(true);
losers[answer] = (losers[answer] ?? 0) + 1;
}
}
expect(Object.values(losers).reduce((n, c) => n + c, 0), JSON.stringify(losers)).toBe(ROUNDS);
});
}
});
4 changes: 4 additions & 0 deletions ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2604,6 +2604,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
toast.success(t('detail.claimed', { defaultValue: 'You own this record now.' }));
} else if (result.outcome === 'taken') {
toast.error(t('detail.claimTaken', { defaultValue: 'Someone else claimed this record first.' }));
} else if (result.outcome === 'unavailable') {
// A 404 or 403 straight after a claim: the sentence names no claimant,
// since a 404 is also what a deleted record answers.
toast.error(t('detail.claimUnavailable', { defaultValue: 'This record is no longer waiting to be claimed.' }));
} else {
toast.error(
extractWriteErrorMessage(result.error)
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1857,6 +1857,7 @@ const ar = {
claimed: "أصبحت مالك هذا السجل الآن.",
claimTaken: "استلم شخص آخر هذا السجل قبلك.",
claimFailed: "لم يُقبل الاستلام.",
claimUnavailable: "لم يعد هذا السجل بانتظار الاستلام.",
cancel: "إلغاء",
cancelEdit: "تجاهل التغييرات",
sectionMoreDetails: "مزيد من التفاصيل",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,7 @@ const de = {
claimed: "Dieser Datensatz gehört jetzt Ihnen.",
claimTaken: "Jemand anderes hat diesen Datensatz zuerst übernommen.",
claimFailed: "Die Übernahme wurde nicht angenommen.",
claimUnavailable: "Dieser Datensatz wartet nicht mehr auf eine Übernahme.",
cancel: "Abbrechen",
cancelEdit: "Änderungen verwerfen",
sectionMoreDetails: "Weitere Details",
Expand Down
Loading
Loading