From 8d8ed6472e23f7b015d06043572d289c19113ada Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:03:37 +0000 Subject: [PATCH 1/7] feat(plugin-approvals): the record lock reads say which approval holds a row (lockSource) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .../plugin-approvals/src/approval-service.ts | 91 ++++++++++++++----- .../spec/src/contracts/approval-service.ts | 37 +++++--- 2 files changed, 95 insertions(+), 33 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 50e23203422..434e8a74bfa 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -2232,6 +2232,23 @@ async function findChildRequestId( */ const REQUEST_VISIBILITY = new WeakMap(); +/** + * The answer both record-lock doors give a readable row + * (`IApprovalService.getRecordLock` / `getRecordLocks`, ruling 7148480184): + * which approval holds it, the master's winning when both do — a line of a held + * master refuses delete as well as edit, while a record held by its own request + * may be deleted, which cancels the request. One spelling, so the two doors + * cannot answer a row differently. + */ +function recordLockAnswer( + heldByMaster: boolean, + heldItself: boolean, +): { locked: boolean; lockSource?: 'record' | 'master' } { + if (heldByMaster) return { locked: true, lockSource: 'master' }; + if (heldItself) return { locked: true, lockSource: 'record' }; + return { locked: false }; +} + /** * [#23889] Each service's own slot labeller — the one its live writers label * `pending_approver_labels` / `acted_as_label` with — for the boot backfills @@ -11313,7 +11330,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * detail object only — the detail-row lock's batch form * ({@link detailRowsHeldByLockingApproval}: one FK read plus one lookup per * `master_detail` edge), so a line of a held master answers `true` here as - * it does at {@link getRecordLock}. Entry `i` answers `recordIds[i]`. + * it does at {@link getRecordLock}, with the same `lockSource`. Entry `i` + * answers `recordIds[i]`. + * + * ## Which rows count as readable — the single door's rule + * + * {@link getRecordLock} counts a row readable when the caller's read of its + * id returns a row, whatever spelling of the id the engine hands back (a + * case-insensitive collation, a numeric id asked as `'07'`). One `$in` read + * cannot say which asked id a row answers when the engine spells it + * differently, so an id it echoes back is judged here, and the ids it does + * not echo are answered by the single door itself, one call each — but only + * when the read handed back a row under a spelling nobody asked, the one + * sign that an unechoed id may still name a readable row. A page asked with + * the ids the engine spells (what a list holds) never pays that read; an + * unechoed id with no such row answers `null`, as the single door would. + * The one case left: a page asking two spellings of the same row, where + * the engine echoes one, answers `null` for the other. * * The cap is the door's to refuse loudly; here a blank id answers `null`. */ @@ -11321,7 +11354,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega object: string, recordIds: readonly string[], context: ExecutionContext, - ): Promise> { + ): Promise> { const objectName = String(object ?? '').trim(); const ids = recordIds.map((recordId) => String(recordId ?? '').trim()); const asked = Array.from(new Set(ids.filter((id) => id !== ''))); @@ -11330,17 +11363,31 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const readable = await this.engine.find(objectName, { where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context, }); - const readableIds = new Set((Array.isArray(readable) ? readable : []).map((row: any) => String(row?.id))); + const rows = (Array.isArray(readable) ? readable : []) as Array<{ id?: unknown }>; + const readableIds = new Set(rows.map((row) => String(row?.id))); const readableAsked = asked.filter((id) => readableIds.has(id)); + // The single door's readability rule for the ids the read did not echo + // (see the doc block): only when some row came back under another spelling. + const askedIds = new Set(asked); + const answeredAlone = new Map(); + if (rows.some((row) => !askedIds.has(String(row?.id)))) { + for (const id of asked) { + if (!readableIds.has(id)) answeredAlone.set(id, await this.getRecordLock(objectName, id, context)); + } + } const held = readableAsked.length > 0 ? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked) : new Set(); - // The single door's second half, for the rows the first left unlocked. - const unheld = readableAsked.filter((id) => !held.has(id)); - const heldByMaster = unheld.length > 0 - ? await detailRowsHeldByLockingApproval(this.engine, objectName, unheld) + // The single door's second half, asked of every readable row: a line held + // by its own request under a held master answers `'master'` there too. + const heldByMaster = readableAsked.length > 0 + ? await detailRowsHeldByLockingApproval(this.engine, objectName, readableAsked) : new Set(); - return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) || heldByMaster.has(id) } : null)); + return ids.map((id) => { + if (answeredAlone.has(id)) return answeredAlone.get(id)!; + if (!readableIds.has(id)) return null; + return recordLockAnswer(heldByMaster.has(id), held.has(id)); + }); } async getRequest(requestId: string, context: ExecutionContext): Promise { @@ -11438,22 +11485,25 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * id, existing or not. ⚠️ Probing with {@link SYSTEM_CTX} here would admit * every authenticated user in the tenant. * - * ## What is answered — the lock, and nothing about the request + * ## What is answered — the lock and its kind, nothing about the request * - * `{ locked }` only: no request id, node, participants or `pending`. Request - * content stays behind `approvalsVisibleToReaders` (#8652 ruling 5299823744, - * untouched). The judgement is the record-lock hook's own - * ({@link recordHeldByLockingApproval}), never a second copy of it — and, - * for a master-detail line, the detail-row lock's - * ({@link detailRowHeldByLockingApproval}): a locked record's lines are - * locked with it, so the read answers `true` for a line whose write the hook - * refuses. + * `{ locked, lockSource }` (ruling 7148480184, option A): no request id, + * node, participants or `pending`. Request content stays behind + * `approvalsVisibleToReaders` (#8652 ruling 5299823744, untouched); + * `lockSource` is one kind bit. The judgement is the record-lock hook's own + * ({@link recordHeldByLockingApproval}), never a second copy of it — + * `lockSource: 'record'` — and, for a master-detail line, the detail-row + * lock's ({@link detailRowHeldByLockingApproval}): a locked record's lines + * are locked with it, so the read answers `true` for a line whose write the + * hook refuses — `lockSource: 'master'`, asked first because it wins when + * both hold: a line of a held master refuses delete too, a record held by + * its own request may be deleted (the delete cancels the request). */ async getRecordLock( object: string, recordId: string, context: ExecutionContext, - ): Promise<{ locked: boolean } | null> { + ): Promise<{ locked: boolean; lockSource?: 'record' | 'master' } | null> { const objectName = String(object ?? '').trim(); const id = String(recordId ?? '').trim(); if (!objectName || !id) return null; @@ -11462,9 +11512,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega where: { id }, fields: ['id'], limit: 1, context, }); if (!Array.isArray(readable) || readable.length === 0) return null; - const locked = await recordHeldByLockingApproval(this.engine, objectName, id) - || await detailRowHeldByLockingApproval(this.engine, objectName, id); - return { locked }; + if (await detailRowHeldByLockingApproval(this.engine, objectName, id)) return recordLockAnswer(true, false); + return recordLockAnswer(false, await recordHeldByLockingApproval(this.engine, objectName, id)); } private async loadRequest( diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index a929ddb6a48..fafb0c56112 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -1109,15 +1109,24 @@ export interface IApprovalService { * who cannot read it gets `null` — exactly the answer for a record id that * does not exist, ⛔ never one that tells the two apart. A caller refused * the object's read outright is refused the same way for every id. - * - **What is answered:** `locked` only. `true` when a pending request on the - * record comes from a node whose `lockRecord` is not `false` — the same - * judgement, off the same snapshot, the record-lock `beforeUpdate` hook - * enforces. Asked of a master-detail line, it also answers `true` while - * a record the line belongs to is so held — the detail-row lock's judgement, - * which refuses the line's writes. + * - **What is answered:** `locked`, and — only when `locked` is `true` — + * `lockSource`, which approval holds the record (ruling 7148480184, option + * A, revising the #25934 ruling A text "`locked` only"). `locked` is `true` + * when a pending request on the record comes from a node whose + * `lockRecord` is not `false` — the same judgement, off the same snapshot, + * the record-lock `beforeUpdate` hook enforces — and then `lockSource` is + * `'record'`. Asked of a master-detail line, it also answers `true` while + * a record the line belongs to is so held — the detail-row lock's + * judgement, which refuses the line's writes — and then `lockSource` is + * `'master'`. When both hold (a line held by its own request under a held + * master) `lockSource` is `'master'`: the stricter of the two delete rules. + * A record held by its own request may still be deleted, which cancels + * the request; a line of a held master refuses insert, update and delete. + * An unlocked record answers `{ locked: false }`, with no `lockSource`. * ⛔ No request id, node, participants or `pending` flag: whether * the caller may see the request is still `approvalsVisibleToReaders`' - * question, and this member does not answer it. + * question, and this member does not answer it. `lockSource` is one kind + * bit, never which request or who decides it. * * **Optional, and its absence is loud:** an approvals implementation without * it still satisfies this contract, so a door probes for presence and answers @@ -1125,13 +1134,14 @@ export interface IApprovalService { * * @param object - The target object's name * @param recordId - The target record's id - * @returns `{ locked }`, or `null` when the caller cannot read that record + * @returns `{ locked, lockSource }` for a locked record, `{ locked: false }` + * for an unlocked one, or `null` when the caller cannot read that record */ getRecordLock?( object: string, recordId: string, context: ExecutionContext, - ): Promise<{ locked: boolean } | null>; + ): Promise<{ locked: boolean; lockSource?: 'record' | 'master' } | null>; /** * **Are these records held by a locking approval?** — {@link getRecordLock} @@ -1140,12 +1150,15 @@ export interface IApprovalService { * per row. * * Entry `i` of the answer answers `recordIds[i]` with exactly what - * {@link getRecordLock} answers for that id: `{ locked }` when the caller + * {@link getRecordLock} answers for that id: `{ locked, lockSource }` for a + * locked record and `{ locked: false }` for an unlocked one when the caller * can read the record, `null` when it cannot or when it does not exist, * ⛔ never an entry that tells the two apart. The same judgement, off the * same snapshot, the record-lock `beforeUpdate` hook enforces — and, for a * master-detail line, the detail-row lock's: a line answers `true` while a - * record it belongs to is so held. A repeated id + * record it belongs to is so held, with `lockSource: 'master'` (which wins + * when the line is held by a request of its own too). A row counts as + * readable by the same rule as at {@link getRecordLock}. A repeated id * is answered at each of its positions. A caller refused the object's read * outright is refused the same way for every id. * @@ -1163,7 +1176,7 @@ export interface IApprovalService { object: string, recordIds: readonly string[], context: ExecutionContext, - ): Promise>; + ): Promise>; /** * Record a decision on a node-driven request. Honours the node's From db800fe9877a800b0ef6b02b8a86f6c53e5df76c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:06:16 +0000 Subject: [PATCH 2/7] test(plugin-approvals,rest): pin lockSource at both doors and one readability rule Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .../src/record-lock-read.integration.test.ts | 205 ++++++++++++++++-- packages/rest/src/approvals-routes.ts | 42 +++- .../rest-approvals-record-lock-route.test.ts | 44 +++- ...-response-internal-fields.tripwire.test.ts | 2 +- 4 files changed, 252 insertions(+), 41 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index 40208e771c8..86c053d7ed3 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -7,7 +7,8 @@ * * ## What each pin holds * - * - a non-participant who can read the record is told `{ locked: true }` — + * - a non-participant who can read the record is told + * `{ locked: true, lockSource: 'record' }` — * while still served no request row (#8652's ruling is untouched), and * while their write is still refused `RECORD_LOCKED`: the read and the hook * give one answer; @@ -17,10 +18,15 @@ * - a pending node with `lockRecord: false`, or no pending request at all, * answers `{ locked: false }`; * - the request row's `lock_record` and this read agree on every request in - * the scene — one judgement, read off one snapshot. + * the scene — one judgement, read off one snapshot; + * - `lockSource` says which approval holds a locked row — its own + * (`'record'`) or its master's (`'master'`, winning when both hold) — and + * so which delete the server refuses; the page read gives each row the + * single read's kind, and counts a row readable by the single read's rule, + * a loosely matched id included (ruling 7148480184). * * The REST door's half (one 404 for both `null`s, the closed query set, the - * `{ locked }`-only payload) is pinned in `@objectstack/rest`; the whole path + * `{ locked, lockSource }`-only payload) is pinned in `@objectstack/rest`; the whole path * on a real boot with the real security plugin in the dogfood suite * (`approval-record-lock-read.dogfood.test.ts`). * @@ -69,6 +75,11 @@ const recordA = (object: string) => `${object}_a`; const recordB = (object: string) => `${object}_b`; const MISSING = 'no_such_record'; +/** A row held by a locking request of its own (ruling 7148480184). */ +const BYREC = { locked: true, lockSource: 'record' }; +/** A master-detail line held by its master's locking request — the kind that refuses delete too. */ +const BYMASTER = { locked: true, lockSource: 'master' }; + function sheet(name: string) { return { name, @@ -214,7 +225,7 @@ describe('ApprovalService.getRecordLocks — the lock read for a page of rows', expect(page, caller).toEqual(oneByOne); } // The reader: `_a` locked; `_b` unreadable and `MISSING` absent read alike. - expect(await rig.svc.getRecordLocks(HELD, ids, asUser(READER))).toEqual([{ locked: true }, null, null, { locked: true }]); + expect(await rig.svc.getRecordLocks(HELD, ids, asUser(READER))).toEqual([BYREC, null, null, BYREC]); expect(await rig.svc.getRecordLocks(OPEN, [recordA(OPEN), recordB(OPEN)], asUser(SUBMITTER))) .toEqual([{ locked: false }, { locked: false }]); }); @@ -237,7 +248,7 @@ describe('ApprovalService.getRecordLocks — the lock read for a page of rows', () => 'answered', (err: any) => `${err?.code} ${err?.status}`, ); expect(refusal).toBe('PERMISSION_DENIED 403'); - expect(await rig.svc.getRecordLocks(HELD, ['', recordA(HELD)], asUser(READER))).toEqual([null, { locked: true }]); + expect(await rig.svc.getRecordLocks(HELD, ['', recordA(HELD)], asUser(READER))).toEqual([null, BYREC]); }); it('unlocks the page once the request is decided, as the hook does', async () => { @@ -251,15 +262,15 @@ describe('ApprovalService.getRecordLocks — the lock read for a page of rows', describe('[#26314] ApprovalService.getRecordLock', () => { it('tells a non-participant reader the record is locked, and nothing about the request', async () => { const rig = await boot(); - expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(READER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(READER))).toEqual(BYREC); // #8652 untouched: the request itself is still not served to them… expect(await rig.svc.listRequests({ object: HELD, recordId: recordA(HELD) }, asUser(READER))).toEqual([]); expect(await rig.svc.getRequest(rig.requests.get(HELD)!, asUser(READER))).toBeNull(); // …and the lock it reports is the one the hook enforces on their write. expect(await writeAs(rig, READER, HELD, recordA(HELD))).toBe('RECORD_LOCKED'); // The participants are told the same. - expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(SUBMITTER))).toEqual({ locked: true }); - expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(APPROVER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(SUBMITTER))).toEqual(BYREC); + expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(APPROVER))).toEqual(BYREC); }); it('answers a record the caller cannot read exactly as one that does not exist', async () => { @@ -272,7 +283,7 @@ describe('[#26314] ApprovalService.getRecordLock', () => { object: HELD, recordId: recordB(HELD), runId: 'run_b', nodeId: 'review', flowName: 'sheet_review', config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: recordB(HELD), title: recordB(HELD) }, }, asUser(SUBMITTER)); - expect(await rig.svc.getRecordLock(HELD, recordB(HELD), asUser(SUBMITTER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(HELD, recordB(HELD), asUser(SUBMITTER))).toEqual(BYREC); expect(await rig.svc.getRecordLock(HELD, recordB(HELD), asUser(READER))).toBeNull(); // No read on the object at all: the same refusal whether the id exists or not. const refusalOf = async (id: string) => { @@ -304,7 +315,7 @@ describe('[#26314] ApprovalService.getRecordLock', () => { const row = await rig.svc.getRequest(rig.requests.get(object)!, asUser(APPROVER)); const read = await rig.svc.getRecordLock(object, recordA(object), asUser(APPROVER)); expect(row?.lock_record, object).toBe(object === HELD); - expect(read, object).toEqual({ locked: row?.lock_record }); + expect(read, object).toEqual(row?.lock_record ? BYREC : { locked: false }); } }); }); @@ -314,10 +325,10 @@ describe('a locked record\'s lines are locked with it — the record-lock read a it('tells a reader a line of a locked record is locked, as its write is refused', async () => { const rig = await boot(); - expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(READER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(READER))).toEqual(BYMASTER); expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('RECORD_LOCKED'); - expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER))).toEqual({ locked: true }); - expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(APPROVER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER))).toEqual(BYMASTER); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(APPROVER))).toEqual(BYMASTER); }); it('CONTROL — a line under a record with no pending request, or under a `lockRecord: false` node, is unlocked and writes', async () => { @@ -352,10 +363,10 @@ describe('a locked record\'s lines are locked with it — the record-lock read a } } expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER))) - .toEqual([{ locked: true }, { locked: false }]); + .toEqual([BYMASTER, { locked: false }]); // The reader: line `_a` locked, as its write is refused; line `_b` unreadable reads as missing. expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE), MISSING], asUser(READER))) - .toEqual([{ locked: true }, null, null]); + .toEqual([BYMASTER, null, null]); expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('RECORD_LOCKED'); // A line held by a request of its own answers locked by both reads too. await rig.svc.openNodeRequest({ @@ -366,7 +377,7 @@ describe('a locked record\'s lines are locked with it — the record-lock read a .toEqual([await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER)), await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))]); expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER))) - .toEqual([{ locked: true }, { locked: true }]); + .toEqual([BYMASTER, BYREC]); // Decided: the line unlocks for the page read as for the hook. await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE)], asUser(READER))).toEqual([{ locked: false }]); @@ -398,7 +409,7 @@ describe('a locked record\'s lines are locked with it — the record-lock read a object: HELD, recordId: recordB(HELD), runId: 'run_b', nodeId: 'review', flowName: 'sheet_review', config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: recordB(HELD), title: recordB(HELD) }, }, asUser(SUBMITTER)); - expect(await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))).toEqual({ locked: true }); + expect(await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))).toEqual(BYMASTER); expect(await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(READER))).toBeNull(); expect(await rig.svc.getRecordLock(LINE, MISSING, asUser(READER))).toBeNull(); }); @@ -425,3 +436,163 @@ describe('the one-row detail read answers from the row it found, not from how th expect([...await detailRowsHeldByLockingApproval(engine, 'line', ['line-1'])]).toEqual(['LINE-1']); }); }); + +/** + * Ruling 7148480184 (option A): both lock reads say WHICH approval holds a + * locked row — `'record'`, its own; `'master'`, the record a master-detail line + * belongs to — because the two refuse different deletes: a record held by its + * own request may be deleted (the delete cancels the request), a line of a held + * master is refused insert, update and delete. `'master'` wins when both hold. + */ +describe('lockSource — which approval holds a locked row, the same at the single read and the page read', () => { + const LINE = lineOf(HELD); + + /** The caller's delete, and the refusal code when it is refused. */ + async function deleteAs(rig: Rig, userId: string, object: string, recordId: string): Promise { + try { + await rig.engine.delete(object, { where: { id: recordId }, context: asUser(userId) } as any); + return 'deleted'; + } catch (err: any) { + return String(err?.code ?? err?.message); + } + } + + /** Entry `i` of the page read is the single read of `ids[i]`, for every caller. */ + async function expectParity(rig: Rig, object: string, ids: string[]): Promise { + for (const caller of [SUBMITTER, APPROVER, READER]) { + const page = await rig.svc.getRecordLocks(object, ids, asUser(caller)); + const oneByOne = []; + for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller))); + expect(page, `${caller} ${object} ${ids.join(',')}`).toEqual(oneByOne); + } + } + + it('a self-held record, a line of a held master, a self-held line under a held master and an unheld row', async () => { + const rig = await boot(); + // A line held by a request of its own, under the held master `_a` of the sheet. + const selfHeldLine = `${LINE}_self`; + await rig.engine.insert(LINE, { id: selfHeldLine, title: selfHeldLine, sheet: recordA(HELD) }, { context: SYSTEM } as any); + await rig.svc.openNodeRequest({ + object: LINE, recordId: selfHeldLine, runId: 'run_line_self', nodeId: 'review', flowName: 'line_review', + config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: selfHeldLine, title: selfHeldLine }, + }, asUser(SUBMITTER)); + + expect(await rig.svc.getRecordLock(HELD, recordA(HELD), SYSTEM)).toEqual(BYREC); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), SYSTEM)).toEqual(BYMASTER); + expect(await rig.svc.getRecordLock(LINE, selfHeldLine, SYSTEM)).toEqual(BYMASTER); + expect(await rig.svc.getRecordLock(HELD, recordB(HELD), SYSTEM)).toEqual({ locked: false }); + expect(await rig.svc.getRecordLock(LINE, recordB(LINE), SYSTEM)).toEqual({ locked: false }); + + const sheetIds = [recordA(HELD), recordB(HELD), MISSING]; + const lineIds = [recordA(LINE), selfHeldLine, recordB(LINE), MISSING, recordA(LINE)]; + expect(await rig.svc.getRecordLocks(HELD, sheetIds, SYSTEM)).toEqual([BYREC, { locked: false }, null]); + expect(await rig.svc.getRecordLocks(LINE, lineIds, SYSTEM)) + .toEqual([BYMASTER, BYMASTER, { locked: false }, null, BYMASTER]); + await expectParity(rig, HELD, sheetIds); + await expectParity(rig, LINE, lineIds); + + // The kind is the delete the server refuses: every `'master'` row is + // refused, a self-held line under a held master included (the next case + // pins a `'record'` row's delete going through). + expect(await deleteAs(rig, SUBMITTER, LINE, recordA(LINE))).toBe('RECORD_LOCKED'); + expect(await deleteAs(rig, SUBMITTER, LINE, selfHeldLine)).toBe('RECORD_LOCKED'); + }); + + it('a line held by its own request under an UNHELD master answers `record`, and may be deleted', async () => { + const rig = await boot(); + await rig.svc.openNodeRequest({ + object: LINE, recordId: recordB(LINE), runId: 'run_line_b', nodeId: 'review', flowName: 'line_review', + config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: recordB(LINE), title: recordB(LINE) }, + }, asUser(SUBMITTER)); + expect(await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))).toEqual(BYREC); + await expectParity(rig, LINE, [recordA(LINE), recordB(LINE)]); + // A `'record'` row's delete goes through, and cancels its request. + expect(await deleteAs(rig, SUBMITTER, LINE, recordB(LINE))).toBe('deleted'); + expect(await rig.svc.listRequests({ object: LINE, recordId: recordB(LINE), status: 'pending' }, SYSTEM)).toEqual([]); + }); + + it('once the request is decided neither kind is answered: the record and its line answer unlocked', async () => { + const rig = await boot(); + await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + expect(await rig.svc.getRecordLock(HELD, recordA(HELD), asUser(READER))).toEqual({ locked: false }); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(READER))).toEqual({ locked: false }); + await expectParity(rig, LINE, [recordA(LINE)]); + }); +}); + +/** + * The readability anchor, one rule at both doors (#37151 comment 7148285178): + * `getRecordLock` counts a row readable when the caller's read of the id + * returns one, whatever spelling of the id the engine hands back; the page read + * used to count it only when the engine echoed the asked spelling, so a loosely + * matched id answered `null` there and the lock at the single read. + */ +describe('both lock reads count a row readable by one rule — a loosely matched id included', () => { + const LINE = lineOf(HELD); + + /** Rewrite every `id` value in a read's predicate to lower case: a case-insensitive collation. */ + function caseInsensitiveIds(engine: ObjectQL, object: string): void { + const lower = (value: unknown): unknown => typeof value === 'string' ? value.toLowerCase() : value; + const fold = (where: any): any => { + if (Array.isArray(where)) return where.map(fold); + if (!where || typeof where !== 'object') return where; + const out: Record = {}; + for (const [key, value] of Object.entries(where)) { + if (key === 'id') { + out[key] = value && typeof value === 'object' && Array.isArray((value as any).$in) + ? { ...(value as object), $in: (value as any).$in.map(lower) } + : lower(value); + } else { + out[key] = key.startsWith('$') ? fold(value) : value; + } + } + return out; + }; + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (READ_OPS.has(op.operation) && op.ast?.where) op.ast.where = fold(op.ast.where); + return next(); + }, { object }); + } + + it('answers a loosely matched id at the page read as the single read does', async () => { + const rig = await boot(); + caseInsensitiveIds(rig.engine, LINE); + caseInsensitiveIds(rig.engine, HELD); + const loose = (id: string) => id.toUpperCase(); + + // The single read finds the row under the loose spelling; the line's master is held. + expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toEqual(BYMASTER); + // The page read answers it the same — alone, beside echoed ids, beside a missing one. + expect(await rig.svc.getRecordLocks(LINE, [loose(recordA(LINE))], asUser(SUBMITTER))).toEqual([BYMASTER]); + const lineIds = [loose(recordA(LINE)), recordB(LINE), MISSING, loose(recordB(LINE)), recordA(LINE)]; + expect(await rig.svc.getRecordLocks(LINE, lineIds, asUser(SUBMITTER))) + .toEqual([BYMASTER, { locked: false }, null, { locked: false }, BYMASTER]); + for (const caller of [SUBMITTER, APPROVER, READER]) { + for (const [object, ids] of [ + [LINE, lineIds], + [HELD, [loose(recordA(HELD)), recordB(HELD), loose(MISSING), loose(recordB(HELD))]], + ] as Array<[string, string[]]>) { + const page = await rig.svc.getRecordLocks(object, ids, asUser(caller)); + const oneByOne = []; + for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller))); + expect(page, `${caller} ${object}`).toEqual(oneByOne); + } + } + // The reader still cannot read line `_b`, however it is spelled. + expect(await rig.svc.getRecordLocks(LINE, [loose(recordB(LINE)), loose(recordA(LINE))], asUser(READER))) + .toEqual([null, BYMASTER]); + }); + + it('pays no read per row for a page asked in the spellings the engine echoes, missing ids included', async () => { + const rig = await boot(); + caseInsensitiveIds(rig.engine, HELD); + const find = rig.engine.find.bind(rig.engine); + const reads: string[] = []; + (rig.engine as any).find = (object: string, query: any) => { + reads.push(object); + return find(object, query); + }; + await rig.svc.getRecordLocks(HELD, [recordA(HELD), recordB(HELD), MISSING], asUser(SUBMITTER)); + expect(reads).toEqual([HELD, 'sys_approval_request']); + }); +}); diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index 08134961997..12a815c0b6d 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -129,6 +129,23 @@ export function readRecordLocksBody(body: unknown): { recordIds: string[] } | { return { recordIds: ids as string[] }; } +/** + * What both record-lock doors serve of a service's answer for a readable + * record: `locked`, and — on a locked record only — `lockSource`, `'record'` + * or `'master'` (ruling 7148480184). Built field by field, so whatever else an + * implementation hands back (a request id, a `pending` flag) is never served: + * the answer stays one lock bit plus one kind bit (#8652 ruling 5299823744). + * A locked answer from an implementation that names no kind is served + * `{ locked: true }` alone, never a guessed kind. + */ +function recordLockPayload( + lock: { locked: boolean; lockSource?: unknown }, +): { locked: boolean; lockSource?: 'record' | 'master' } { + if (lock.locked !== true) return { locked: false }; + const source = lock.lockSource; + return source === 'record' || source === 'master' ? { locked: true, lockSource: source } : { locked: true }; +} + /** * [#29880] Read `?status=` on `GET {basePath}/approvals/requests` against the * value set `sys_approval_request.status` declares. @@ -498,8 +515,11 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // `IApprovalService.getRecordLock` carries the rule: the record is read AS // THE CALLER, and an unreadable record answers `null`, the same as a // record id that does not exist — so this door answers both with the same - // 404, and the payload is `{ locked }` alone. Optional on the contract, so - // an implementation without it answers 501, never a guess. + // 404, and the payload is `{ locked }` plus, on a locked record only, its + // `lockSource` — `'record'` (its own approval) or `'master'` (the record a + // master-detail line belongs to; ruling 7148480184) — and nothing else + // (`recordLockPayload`). Optional on the contract, so an implementation + // without it answers 501, never a guess. this.routeManager.register({ method: 'GET', path: `${dataPath}/approvals/records/:object/:recordId/lock`, @@ -519,7 +539,7 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s sendEnvelopeError(res, 404, 'RECORD_NOT_FOUND', `No such '${object}' record`); return; } - sendOk(res, { locked: lock.locked === true }); + sendOk(res, recordLockPayload(lock)); } catch (error: any) { handleRouteError(res, error); } @@ -529,10 +549,10 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // The lock of a PAGE of records, in one request: what a list asks before it // opens a cell editor, so moving through the rows sends no request per row. - // Each entry is exactly the single-record door's answer for that id, the - // 404 folded to `locked: null` (unreadable or missing, told apart by - // nothing); a service without `getRecordLocks` answers 501, never one - // `getRecordLock` per id. + // Each entry is exactly the single-record door's answer for that id — + // `locked`, and `lockSource` on a locked row — the 404 folded to + // `locked: null` (unreadable or missing, told apart by nothing); a service + // without `getRecordLocks` answers 501, never one `getRecordLock` per id. this.routeManager.register({ method: 'POST', path: `${dataPath}/approvals/records/:object/locks`, @@ -552,10 +572,10 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s const { object } = req.params; const answers = await svc.getRecordLocks(object, read.recordIds, context ?? {}); sendOk(res, { - records: read.recordIds.map((recordId, index) => ({ - recordId, - locked: answers[index] ? answers[index]!.locked === true : null, - })), + records: read.recordIds.map((recordId, index) => { + const answer = answers[index]; + return answer ? { recordId, ...recordLockPayload(answer) } : { recordId, locked: null }; + }), }); } catch (error: any) { handleRouteError(res, error); diff --git a/packages/rest/src/rest-approvals-record-lock-route.test.ts b/packages/rest/src/rest-approvals-record-lock-route.test.ts index 4fb472e8e82..135fd3f2945 100644 --- a/packages/rest/src/rest-approvals-record-lock-route.test.ts +++ b/packages/rest/src/rest-approvals-record-lock-route.test.ts @@ -10,8 +10,10 @@ * * - preservation: the service is asked with the path's object and record id * and the caller's own context, and its answer is served as - * `{ success: true, data: { locked } }` — `locked` and nothing else, even - * when an implementation hands back more; + * `{ success: true, data: { locked, lockSource } }` — `locked`, and on a + * locked record which approval holds it (`'record'` or `'master'`, ruling + * 7148480184), and nothing else, even when an implementation hands back + * more; * - one 404 for every `null`: the same status and the same body whatever the * id, so the door cannot tell an unreadable record from a missing one; * - the closed query-parameter set is EMPTY (AGENTS.md route rule 5): a name @@ -95,19 +97,35 @@ function boot(approvals: Record) { } describe('[#26314] GET /approvals/records/:object/:recordId/lock', () => { - it('asks the service with the path and the caller, and serves `locked` alone', async () => { + it('asks the service with the path and the caller, and serves `locked` and its `lockSource` alone', async () => { // An implementation that hands back MORE than the contract's payload: - // the door still serves `locked` and nothing else. - const getRecordLock = vi.fn().mockResolvedValue({ locked: true, requestId: 'req_1', pending: true }); + // the door still serves `locked`, the kind, and nothing else. + const getRecordLock = vi.fn().mockResolvedValue({ + locked: true, lockSource: 'master', requestId: 'req_1', pending: true, + }); const drive = boot({ getRecordLock }); - expect(await drive('expense', 'rec_1')).toEqual({ status: 200, body: { success: true, data: { locked: true } } }); + expect(await drive('expense_line', 'line_1')).toEqual({ + status: 200, body: { success: true, data: { locked: true, lockSource: 'master' } }, + }); expect(getRecordLock).toHaveBeenCalledTimes(1); - expect(getRecordLock).toHaveBeenCalledWith('expense', 'rec_1', CALLER); + expect(getRecordLock).toHaveBeenCalledWith('expense_line', 'line_1', CALLER); - getRecordLock.mockResolvedValueOnce({ locked: false }); + getRecordLock.mockResolvedValueOnce({ locked: true, lockSource: 'record' }); + expect(await drive('expense', 'rec_1')).toEqual({ + status: 200, body: { success: true, data: { locked: true, lockSource: 'record' } }, + }); + // Unlocked: no kind, even when an implementation names one. + getRecordLock.mockResolvedValueOnce({ locked: false, lockSource: 'record' }); expect(await drive('expense', 'rec_2')).toEqual({ status: 200, body: { success: true, data: { locked: false } } }); }); + it('serves a locked answer that names no kind, or an unknown one, as `{ locked: true }` alone — never a guessed kind', async () => { + const getRecordLock = vi.fn().mockResolvedValueOnce({ locked: true }).mockResolvedValueOnce({ locked: true, lockSource: 'req_1' }); + const drive = boot({ getRecordLock }); + expect(await drive('expense', 'rec_1')).toEqual({ status: 200, body: { success: true, data: { locked: true } } }); + expect(await drive('expense', 'rec_1')).toEqual({ status: 200, body: { success: true, data: { locked: true } } }); + }); + it('answers every `null` with one 404, the same body whatever the id', async () => { const drive = boot({ getRecordLock: vi.fn().mockResolvedValue(null) }); const unreadable = await drive('expense', 'rec_someone_elses'); @@ -174,25 +192,27 @@ function bootLocks(approvals: Record) { describe('POST /approvals/records/:object/locks — the lock of a page of records', () => { it('asks the service once with the ids in order and the caller, and serves one entry per id', async () => { const getRecordLocks = vi.fn().mockResolvedValue([ - { locked: true, requestId: 'req_1' }, null, { locked: false }, + { locked: true, lockSource: 'record', requestId: 'req_1' }, null, { locked: false }, + { locked: true, lockSource: 'master', pending: true }, ]); const drive = bootLocks({ getRecordLocks }); - const answer = await drive('expense', { recordIds: ['rec_1', 'rec_hidden', 'rec_3'] }); + const answer = await drive('expense', { recordIds: ['rec_1', 'rec_hidden', 'rec_3', 'rec_4'] }); expect(answer).toEqual({ status: 200, body: { success: true, data: { records: [ - { recordId: 'rec_1', locked: true }, + { recordId: 'rec_1', locked: true, lockSource: 'record' }, { recordId: 'rec_hidden', locked: null }, { recordId: 'rec_3', locked: false }, + { recordId: 'rec_4', locked: true, lockSource: 'master' }, ], }, }, }); expect(getRecordLocks).toHaveBeenCalledTimes(1); - expect(getRecordLocks).toHaveBeenCalledWith('expense', ['rec_1', 'rec_hidden', 'rec_3'], CALLER); + expect(getRecordLocks).toHaveBeenCalledWith('expense', ['rec_1', 'rec_hidden', 'rec_3', 'rec_4'], CALLER); }); it('takes a full page at the cap', async () => { diff --git a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts index 8094cc4ba8d..4def3367a6c 100644 --- a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts +++ b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts @@ -403,7 +403,7 @@ const DISPOSITIONS: Record = { 'POST /api/v1/approvals/requests/:id/remind': { kind: 'no-record-echo', why: 'Reminder receipt.' }, 'POST /api/v1/approvals/requests/:id/request-info': { kind: 'no-record-echo', why: 'Approval request state.' }, 'POST /api/v1/approvals/requests/:id/comment': { kind: 'no-record-echo', why: 'Approval comment row.' }, - 'POST /api/v1/approvals/records/:object/locks': { kind: 'no-record-echo', why: 'A READ over POST: `{ recordId, locked }` per id, no field of the row.' }, + 'POST /api/v1/approvals/records/:object/locks': { kind: 'no-record-echo', why: 'A READ over POST: `{ recordId, locked, lockSource? }` per id, no field of the row.' }, 'POST /api/v1/analytics/dataset/query': { kind: 'no-record-echo', why: 'A READ (aggregated dataset) over POST.' }, 'POST /api/v1/analytics/dataset/query/batch': { kind: 'no-record-echo', why: 'A READ (aggregated datasets, one answer entry per query) over POST.' }, From d582aebd462022b54db500cbee6bc334640ecd9a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:12:30 +0000 Subject: [PATCH 3/7] fix(plugin-approvals): both lock doors count a row readable only when the read echoes the asked id Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .../plugin-approvals/src/approval-service.ts | 49 +++++++------------ .../src/record-lock-read.integration.test.ts | 32 ++++++------ .../spec/src/contracts/approval-service.ts | 3 +- 3 files changed, 37 insertions(+), 47 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 434e8a74bfa..9015e1b3cbb 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -11333,20 +11333,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * it does at {@link getRecordLock}, with the same `lockSource`. Entry `i` * answers `recordIds[i]`. * - * ## Which rows count as readable — the single door's rule - * - * {@link getRecordLock} counts a row readable when the caller's read of its - * id returns a row, whatever spelling of the id the engine hands back (a - * case-insensitive collation, a numeric id asked as `'07'`). One `$in` read - * cannot say which asked id a row answers when the engine spells it - * differently, so an id it echoes back is judged here, and the ids it does - * not echo are answered by the single door itself, one call each — but only - * when the read handed back a row under a spelling nobody asked, the one - * sign that an unechoed id may still name a readable row. A page asked with - * the ids the engine spells (what a list holds) never pays that read; an - * unechoed id with no such row answers `null`, as the single door would. - * The one case left: a page asking two spellings of the same row, where - * the engine echoes one, answers `null` for the other. + * ## Which rows count as readable — one rule at both doors + * + * A row is readable when the caller's read hands back a row whose id IS the + * asked id, spelled as asked — the rule {@link getRecordLock} applies too + * (see its doc block for why a loosely matched id answers `null` at both). * * The cap is the door's to refuse loudly; here a blank id answers `null`. */ @@ -11363,18 +11354,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const readable = await this.engine.find(objectName, { where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context, }); - const rows = (Array.isArray(readable) ? readable : []) as Array<{ id?: unknown }>; - const readableIds = new Set(rows.map((row) => String(row?.id))); + const readableIds = new Set((Array.isArray(readable) ? readable : []).map((row: any) => String(row?.id))); const readableAsked = asked.filter((id) => readableIds.has(id)); - // The single door's readability rule for the ids the read did not echo - // (see the doc block): only when some row came back under another spelling. - const askedIds = new Set(asked); - const answeredAlone = new Map(); - if (rows.some((row) => !askedIds.has(String(row?.id)))) { - for (const id of asked) { - if (!readableIds.has(id)) answeredAlone.set(id, await this.getRecordLock(objectName, id, context)); - } - } const held = readableAsked.length > 0 ? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked) : new Set(); @@ -11383,11 +11364,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const heldByMaster = readableAsked.length > 0 ? await detailRowsHeldByLockingApproval(this.engine, objectName, readableAsked) : new Set(); - return ids.map((id) => { - if (answeredAlone.has(id)) return answeredAlone.get(id)!; - if (!readableIds.has(id)) return null; - return recordLockAnswer(heldByMaster.has(id), held.has(id)); - }); + return ids.map((id) => (readableIds.has(id) ? recordLockAnswer(heldByMaster.has(id), held.has(id)) : null)); } async getRequest(requestId: string, context: ExecutionContext): Promise { @@ -11485,6 +11462,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * id, existing or not. ⚠️ Probing with {@link SYSTEM_CTX} here would admit * every authenticated user in the tenant. * + * The row read must be the asked id's own: a row the engine hands back under + * another spelling (a case-insensitive collation, a numeric id asked as + * `'07'`) answers `null`, as at {@link getRecordLocks}. That is the one rule + * both doors can apply alike: one `$in` read for a page cannot say which + * asked id a row spelled otherwise answers — a page asking two spellings of + * one row reads exactly like a page asking a missing id — and resolving it + * would cost a read per row. The ids a client holds are the ones the engine + * spelled, so nothing it asks is refused by this; and the lock is judged + * under the row's own id, never under another spelling of it. + * * ## What is answered — the lock and its kind, nothing about the request * * `{ locked, lockSource }` (ruling 7148480184, option A): no request id, @@ -11511,7 +11498,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const readable = await this.engine.find(objectName, { where: { id }, fields: ['id'], limit: 1, context, }); - if (!Array.isArray(readable) || readable.length === 0) return null; + if (!Array.isArray(readable) || !readable.some((row: any) => String(row?.id) === id)) return null; if (await detailRowHeldByLockingApproval(this.engine, objectName, id)) return recordLockAnswer(true, false); return recordLockAnswer(false, await recordHeldByLockingApproval(this.engine, objectName, id)); } diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index 86c053d7ed3..d074bf71eba 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -522,10 +522,11 @@ describe('lockSource — which approval holds a locked row, the same at the sing /** * The readability anchor, one rule at both doors (#37151 comment 7148285178): - * `getRecordLock` counts a row readable when the caller's read of the id - * returns one, whatever spelling of the id the engine hands back; the page read - * used to count it only when the engine echoed the asked spelling, so a loosely - * matched id answered `null` there and the lock at the single read. + * a row counts as readable when the caller's read hands back the row whose id + * IS the asked id. `getRecordLock` used to count any row the read handed back, + * so a loosely matched id (a case-insensitive collation, `'07'` for `'7'`) + * answered the lock there and `null` at the page read, which cannot say which + * asked id a row spelled otherwise answers without a read per row. */ describe('both lock reads count a row readable by one rule — a loosely matched id included', () => { const LINE = lineOf(HELD); @@ -554,33 +555,34 @@ describe('both lock reads count a row readable by one rule — a loosely matched }, { object }); } - it('answers a loosely matched id at the page read as the single read does', async () => { + it('answers a loosely matched id `null` at both reads, and the echoed spelling of the same row its lock', async () => { const rig = await boot(); caseInsensitiveIds(rig.engine, LINE); caseInsensitiveIds(rig.engine, HELD); const loose = (id: string) => id.toUpperCase(); + // CONTROL — the engine does hand the row back under the loose spelling. + const found = await rig.engine.find(LINE, { where: { id: loose(recordA(LINE)) }, fields: ['id'], context: SYSTEM } as any); + expect((found as any[]).map((row) => row.id)).toEqual([recordA(LINE)]); - // The single read finds the row under the loose spelling; the line's master is held. - expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toEqual(BYMASTER); - // The page read answers it the same — alone, beside echoed ids, beside a missing one. - expect(await rig.svc.getRecordLocks(LINE, [loose(recordA(LINE))], asUser(SUBMITTER))).toEqual([BYMASTER]); + expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toBeNull(); + expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER))).toEqual(BYMASTER); + expect(await rig.svc.getRecordLocks(LINE, [loose(recordA(LINE))], asUser(SUBMITTER))).toEqual([null]); + // Beside the echoed spelling of the same row, beside a missing id: one answer per spelling. const lineIds = [loose(recordA(LINE)), recordB(LINE), MISSING, loose(recordB(LINE)), recordA(LINE)]; expect(await rig.svc.getRecordLocks(LINE, lineIds, asUser(SUBMITTER))) - .toEqual([BYMASTER, { locked: false }, null, { locked: false }, BYMASTER]); + .toEqual([null, { locked: false }, null, null, BYMASTER]); for (const caller of [SUBMITTER, APPROVER, READER]) { for (const [object, ids] of [ [LINE, lineIds], - [HELD, [loose(recordA(HELD)), recordB(HELD), loose(MISSING), loose(recordB(HELD))]], + [LINE, [loose(recordA(LINE))]], + [HELD, [loose(recordA(HELD)), recordB(HELD), loose(MISSING), recordA(HELD)]], ] as Array<[string, string[]]>) { const page = await rig.svc.getRecordLocks(object, ids, asUser(caller)); const oneByOne = []; for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller))); - expect(page, `${caller} ${object}`).toEqual(oneByOne); + expect(page, `${caller} ${object} ${ids.join(',')}`).toEqual(oneByOne); } } - // The reader still cannot read line `_b`, however it is spelled. - expect(await rig.svc.getRecordLocks(LINE, [loose(recordB(LINE)), loose(recordA(LINE))], asUser(READER))) - .toEqual([null, BYMASTER]); }); it('pays no read per row for a page asked in the spellings the engine echoes, missing ids included', async () => { diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index fafb0c56112..7a2d4d41330 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -1105,7 +1105,8 @@ export interface IApprovalService { * the carrier. * * - **Who is answered:** every caller who can READ the record, judged by - * reading it AS THE CALLER (object read, then row-level access). A caller + * reading it AS THE CALLER (object read, then row-level access); the row + * read must be the asked id's own, spelled as asked. A caller * who cannot read it gets `null` — exactly the answer for a record id that * does not exist, ⛔ never one that tells the two apart. A caller refused * the object's read outright is refused the same way for every id. From a453d12cbdc40d8ae88c0dfeaa66ba0f5a21ebad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:13:34 +0000 Subject: [PATCH 4/7] docs(approvals): state lockSource on both lock doors; dogfood fixture and changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .changeset/37151-record-lock-source.md | 21 ++++++++++++ content/docs/automation/approvals.mdx | 32 +++++++++++++------ .../approval-record-lock-read.dogfood.test.ts | 12 ++++--- 3 files changed, 50 insertions(+), 15 deletions(-) create mode 100644 .changeset/37151-record-lock-source.md diff --git a/.changeset/37151-record-lock-source.md b/.changeset/37151-record-lock-source.md new file mode 100644 index 00000000000..49c9b2ee63d --- /dev/null +++ b/.changeset/37151-record-lock-source.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-approvals': patch +'@objectstack/rest': patch +--- + +feat(plugin-approvals): the record lock reads say whether a row is held by its own approval or by its master's + +Clause-②: yes (widening: both lock doors' published entry gains a field) +Metadata-protocol: none + +Both approval lock reads (`IApprovalService.getRecordLock` and `getRecordLocks`, and their REST doors `GET /api/v1/approvals/records/:object/:recordId/lock` and `POST /api/v1/approvals/records/:object/locks`) now answer a locked record with `lockSource`, which approval holds it: + +- `'record'`: a pending request on the record itself, from a node whose `lockRecord` is not `false`. Deleting the record still goes through and cancels the request. +- `'master'`: the record is a `master_detail` line of a record so held. The server refuses the line's insert, update and delete with `409 RECORD_LOCKED`. + +When both hold (a line with a pending request of its own, under a held master), the answer is `'master'`, because that is the delete the server refuses. An unlocked record still answers `{ locked: false }`, with no `lockSource`, and `null` (`404 RECORD_NOT_FOUND` at the single door, `locked: null` in the batch door) still means unreadable or missing, never told apart. No request id, node, approvers or `pending` flag is served. A list can now hide Delete on a line whose master is under approval instead of offering a delete the server refuses. + +The `IApprovalService` return types gain the optional `lockSource?: 'record' | 'master'`, so an existing implementation that answers `{ locked }` alone still satisfies the contract; the REST doors then serve `{ locked: true }` without a kind. + +Both doors now count a row as readable by one rule: the caller's read must hand back the row whose id is the asked id, spelled as asked. The single-record door used to accept any row the read handed back, so an id the database matched loosely (a different letter case under a case-insensitive collation, `07` for a numeric `7`) answered the lock there and `null` in the batch door. It now answers `null` at both. A client asking with the ids the server gave it sees no change. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index b07bd02a01a..0a8e4b54d61 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -450,17 +450,29 @@ request row: ```bash curl -b cookies.txt \ "https://your-app.example.com/api/v1/approvals/records/expense/rec_123/lock" -# → { "success": true, "data": { "locked": true } } +# → { "success": true, "data": { "locked": true, "lockSource": "record" } } ``` -The answer is `locked` and nothing else: no request, approvers or history, -which stay behind the object's `approvalsVisibleToReaders` switch. `locked` is -`true` while a pending request's node has `lockRecord` other than `false`. That -is the same check the server applies when it refuses an edit with `409 -RECORD_LOCKED`, so a page that reads it never offers an edit the server will -refuse. Asked of a line, it answers `true` while the record the line belongs to -is locked. The record is read as the caller: a record they cannot read answers -`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets. The +The answer is `locked` and, on a locked record, `lockSource`, and nothing else: +no request, approvers or history, which stay behind the object's +`approvalsVisibleToReaders` switch. `locked` is `true` while a pending request's +node has `lockRecord` other than `false`. That is the same check the server +applies when it refuses an edit with `409 RECORD_LOCKED`, so a page that reads +it never offers an edit the server will refuse. Asked of a line, it answers +`true` while the record the line belongs to is locked. + +`lockSource` says which approval holds the record, and so which delete the +server refuses. `"record"`: the record's own request holds it, and deleting the +record still goes through and cancels the request. `"master"`: the record is a +line of a locked record, and the server refuses its delete as well as its edit. +A line under a locked record that also has a pending request of its own answers +`"master"`. An unlocked record answers `{ "locked": false }` with no +`lockSource`. + +The record is read as the caller: a record they cannot read answers +`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets, and +so does an id spelled differently from the record's own (a different letter +case, `07` for `7`), even where the database matches it. The SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service member is `IApprovalService.getRecordLock`. An approvals service without that member answers `501`. @@ -473,7 +485,7 @@ curl -b cookies.txt -X POST -H 'Content-Type: application/json' \ -d '{"recordIds":["rec_123","rec_456","rec_789"]}' \ "https://your-app.example.com/api/v1/approvals/records/expense/locks" # → { "success": true, "data": { "records": [ -# { "recordId": "rec_123", "locked": true }, +# { "recordId": "rec_123", "locked": true, "lockSource": "record" }, # { "recordId": "rec_456", "locked": false }, # { "recordId": "rec_789", "locked": null } ] } } ``` diff --git a/packages/qa/dogfood/test/approval-record-lock-read.dogfood.test.ts b/packages/qa/dogfood/test/approval-record-lock-read.dogfood.test.ts index 9c0368ac3bf..75fba4d4160 100644 --- a/packages/qa/dogfood/test/approval-record-lock-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-record-lock-read.dogfood.test.ts @@ -8,16 +8,17 @@ // only lock source was the record's approval-request read, and that door // rightly serves a non-participant no rows (#8652). The lock now has its own // carrier, `GET /approvals/records/:object/:recordId/lock`, answering `{ locked }` -// — and nothing else — to every caller who can read the record. +// — plus, on a locked record, which approval holds it (`lockSource`, ruling +// 7148480184) — and nothing else — to every caller who can read the record. // // Real `SecurityPlugin`, real flows, real approvals plugin. Both objects are // `private`, so the baseline set lets a member read and edit only their own // rows; the editor and the reader are widened by an extra set each. // // ⭐ a non-participant who can read AND edit the held record is told -// `{ locked: true }` — and is still served no request row, and their +// `{ locked: true, lockSource: 'record' }` — and is still served no request row, and their // edit is still refused `RECORD_LOCKED`: the read agrees with the lock; -// ⭐ a read-only reader is told `{ locked: true }`; +// ⭐ a read-only reader is told `{ locked: true, lockSource: 'record' }`; // ⭐ a caller who cannot read the record gets the answer a record id that // does not exist gets — the same status and the same body; // ⭐ a pending node with `lockRecord: false` answers `{ locked: false }` @@ -181,11 +182,12 @@ describe('the record-anchored approval lock read, through the REST door (#26314) const res = await stack.apiAs(token, 'GET', `/approvals/records/${object}/${encodeURIComponent(recordId)}/lock`); return { status: res.status, body: (await res.json()) as unknown }; }; - const LOCKED = { status: 200, body: { success: true, data: { locked: true } } }; + // Held by its own request: `lockSource: 'record'` (ruling 7148480184). + const LOCKED = { status: 200, body: { success: true, data: { locked: true, lockSource: 'record' } } }; const UNLOCKED = { status: 200, body: { success: true, data: { locked: false } } }; // ⭐ 1 — the non-participant reader-editor: told it is locked, in - // exactly `{ locked }`, while still served no request row (#8652's + // exactly `{ locked, lockSource }`, while still served no request row (#8652's // ruling untouched) and still refused the edit (the read agrees with // the lock it reports). expect(await lockOf(editorToken, HELD, heldId)).toEqual(LOCKED); From 00e32ec3a59938c54d0eb564fff7b59edd00a3b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:00:07 +0000 Subject: [PATCH 5/7] test(plugin-approvals): type the new pins' engine options instead of erasing them Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .../plugin-approvals/src/record-lock-read.integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index d074bf71eba..463adc817a3 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -450,7 +450,7 @@ describe('lockSource — which approval holds a locked row, the same at the sing /** The caller's delete, and the refusal code when it is refused. */ async function deleteAs(rig: Rig, userId: string, object: string, recordId: string): Promise { try { - await rig.engine.delete(object, { where: { id: recordId }, context: asUser(userId) } as any); + await rig.engine.delete(object, { where: { id: recordId }, context: asUser(userId) }); return 'deleted'; } catch (err: any) { return String(err?.code ?? err?.message); @@ -561,7 +561,7 @@ describe('both lock reads count a row readable by one rule — a loosely matched caseInsensitiveIds(rig.engine, HELD); const loose = (id: string) => id.toUpperCase(); // CONTROL — the engine does hand the row back under the loose spelling. - const found = await rig.engine.find(LINE, { where: { id: loose(recordA(LINE)) }, fields: ['id'], context: SYSTEM } as any); + const found = await rig.engine.find(LINE, { where: { id: loose(recordA(LINE)) }, fields: ['id'], context: SYSTEM }); expect((found as any[]).map((row) => row.id)).toEqual([recordA(LINE)]); expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toBeNull(); From e99cf2cfdea67ae14b2d5218f32618df96a10293 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:14:44 +0000 Subject: [PATCH 6/7] fix(plugin-approvals): keep the single lock door's readability anchor; type lockSource in the client SDK Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .changeset/37151-record-lock-source.md | 5 +- content/docs/automation/approvals.mdx | 9 +-- packages/client/src/client.test.ts | 16 +++++- packages/client/src/index.ts | 19 +++++-- .../plugin-approvals/src/approval-service.ts | 33 ++++++----- .../src/record-lock-read.integration.test.ts | 55 ++++++++++--------- packages/rest/src/approvals-routes.ts | 5 +- .../spec/src/contracts/approval-service.ts | 12 ++-- 8 files changed, 95 insertions(+), 59 deletions(-) diff --git a/.changeset/37151-record-lock-source.md b/.changeset/37151-record-lock-source.md index 49c9b2ee63d..0a8b1aabadf 100644 --- a/.changeset/37151-record-lock-source.md +++ b/.changeset/37151-record-lock-source.md @@ -2,6 +2,7 @@ '@objectstack/spec': patch '@objectstack/plugin-approvals': patch '@objectstack/rest': patch +'@objectstack/client': patch --- feat(plugin-approvals): the record lock reads say whether a row is held by its own approval or by its master's @@ -18,4 +19,6 @@ When both hold (a line with a pending request of its own, under a held master), The `IApprovalService` return types gain the optional `lockSource?: 'record' | 'master'`, so an existing implementation that answers `{ locked }` alone still satisfies the contract; the REST doors then serve `{ locked: true }` without a kind. -Both doors now count a row as readable by one rule: the caller's read must hand back the row whose id is the asked id, spelled as asked. The single-record door used to accept any row the read handed back, so an id the database matched loosely (a different letter case under a case-insensitive collation, `07` for a numeric `7`) answered the lock there and `null` in the batch door. It now answers `null` at both. A client asking with the ids the server gave it sees no change. +Which rows count as readable is unchanged at both doors. The two doors keep different readability anchors on purpose: the single door counts any returned row, the batch door only the row whose id is the asked id; aligning them would narrow a published answer (seat ruling on PR #37191). So an id the database matches only under another spelling (a different letter case, `07` for a numeric `7`) answers its lock at the single-record door and `null` in the batch door; a client asking with the ids the server gave it gets the same answer from both. + +`@objectstack/client`: `client.approvals.getRecordLock` and `getRecordLocks` type the answer with the optional `lockSource?: 'record' | 'master'`. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 0a8e4b54d61..81fb7d08ca9 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -470,9 +470,7 @@ A line under a locked record that also has a pending request of its own answers `lockSource`. The record is read as the caller: a record they cannot read answers -`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets, and -so does an id spelled differently from the record's own (a different letter -case, `07` for `7`), even where the database matches it. The +`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets. The SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service member is `IApprovalService.getRecordLock`. An approvals service without that member answers `501`. @@ -492,7 +490,10 @@ curl -b cookies.txt -X POST -H 'Content-Type: application/json' \ Each entry is what the single-record read answers for that id, in the order the ids were sent; `null` stands where that read answers `404`, so a record the -caller cannot read and one that does not exist look the same. One request +caller cannot read and one that does not exist look the same. Send the ids as +the server spelled them: an id the database matches only under another spelling +(a different letter case, `07` for `7`) answers `null` here, where the +single-record read answers its lock. One request carries at most 200 ids (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`); a longer list, an empty one or any other body key is refused with `400 VALIDATION_ERROR`. The SDK call is `client.approvals.getRecordLocks(object, recordIds)`, the service diff --git a/packages/client/src/client.test.ts b/packages/client/src/client.test.ts index abc25076e25..270c290f0bb 100644 --- a/packages/client/src/client.test.ts +++ b/packages/client/src/client.test.ts @@ -758,19 +758,29 @@ describe('Approvals namespace (ADR-0019)', () => { }); it('[#26314] reads a record\'s approval lock off the envelope, path segments encoded', async () => { - const { client, fetchMock } = createMockClient({ success: true, data: { locked: true } }); + const { client, fetchMock } = createMockClient({ success: true, data: { locked: true, lockSource: 'record' } }); const result = await client.approvals.getRecordLock('order', 'rec/1'); - expect(result).toEqual({ locked: true }); + expect(result).toEqual({ locked: true, lockSource: 'record' }); + // The answer types the kind (the test program compiles this line). + const kind: 'record' | 'master' | undefined = result.lockSource; + expect(kind).toBe('record'); const [url, opts] = fetchMock.mock.calls[0]; expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/order/rec%2F1/lock'); expect(opts?.method ?? 'GET').toBe('GET'); }); it('reads the approval locks of a page of records in one POST, object segment encoded', async () => { - const records = [{ recordId: 'rec_1', locked: true }, { recordId: 'rec_2', locked: null }]; + const records = [ + { recordId: 'rec_1', locked: true, lockSource: 'master' }, + { recordId: 'rec_2', locked: null }, + { recordId: 'rec_3', locked: false }, + ]; const { client, fetchMock } = createMockClient({ success: true, data: { records } }); const result = await client.approvals.getRecordLocks('sales order', ['rec_1', 'rec_2']); expect(result).toEqual({ records }); + // The entry types the kind (the test program compiles this line). + const kinds: Array<'record' | 'master' | undefined> = result.records.map((entry) => entry.lockSource); + expect(kinds).toEqual(['master', undefined, undefined]); expect(fetchMock).toHaveBeenCalledTimes(1); const [url, opts] = fetchMock.mock.calls[0]; expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/sales%20order/locks'); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index ef40186d3b0..ce2338a6c16 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -7148,18 +7148,25 @@ export class ObjectStackClient { }, /** - * Whether a record is held by a locking approval — `{ locked }` and + * Whether a record is held by a locking approval — `{ locked }`, plus on a + * locked record which approval holds it, `lockSource`: `'record'` (its own; + * deleting it cancels the request) or `'master'` (the record a + * master-detail line belongs to; the server refuses the line's delete too) — + * and * nothing else, answered to every caller who can read the record, whether * or not they take part in the approval (`IApprovalService.getRecordLock`). * A record the caller cannot read answers 404, exactly as a record id that * does not exist; a deployment without the read answers 501. */ - getRecordLock: async (object: string, recordId: string): Promise<{ locked: boolean }> => { + getRecordLock: async ( + object: string, + recordId: string, + ): Promise<{ locked: boolean; lockSource?: 'record' | 'master' }> => { const route = this.getRoute('approvals'); const res = await this.fetch( `${this.baseUrl}${route}/records/${encodeURIComponent(object)}/${encodeURIComponent(recordId)}/lock`, ); - return this.unwrapResponse<{ locked: boolean }>(res); + return this.unwrapResponse<{ locked: boolean; lockSource?: 'record' | 'master' }>(res); }, /** @@ -7173,13 +7180,15 @@ export class ObjectStackClient { getRecordLocks: async ( object: string, recordIds: readonly string[], - ): Promise<{ records: Array<{ recordId: string; locked: boolean | null }> }> => { + ): Promise<{ records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }> }> => { const route = this.getRoute('approvals'); const res = await this.fetch(`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/locks`, { method: 'POST', body: JSON.stringify({ recordIds: [...recordIds] }), }); - return this.unwrapResponse<{ records: Array<{ recordId: string; locked: boolean | null }> }>(res); + return this.unwrapResponse<{ + records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }>; + }>(res); }, /** diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 9015e1b3cbb..0b6d48183b0 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -11333,11 +11333,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * it does at {@link getRecordLock}, with the same `lockSource`. Entry `i` * answers `recordIds[i]`. * - * ## Which rows count as readable — one rule at both doors - * - * A row is readable when the caller's read hands back a row whose id IS the - * asked id, spelled as asked — the rule {@link getRecordLock} applies too - * (see its doc block for why a loosely matched id answers `null` at both). + * ## Which rows count as readable — the row whose id IS the asked id + * + * A row is readable here when the caller's read hands back a row whose id + * IS the asked id, spelled as asked: one `$in` read cannot say which asked + * id a row the engine spells differently answers (a case-insensitive + * collation, a numeric id asked as `'07'`), so such an id answers `null` + * here. {@link getRecordLock} counts any row its read hands back, so for + * such an id the two doors differ, deliberately: the two doors keep + * different readability anchors on purpose, and aligning them would narrow + * a published answer (seat ruling on PR #37191). For an id spelled as the + * engine spells it — what a list holds — entry `i` is exactly the single + * door's answer. * * The cap is the door's to refuse loudly; here a blank id answers `null`. */ @@ -11462,15 +11469,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * id, existing or not. ⚠️ Probing with {@link SYSTEM_CTX} here would admit * every authenticated user in the tenant. * - * The row read must be the asked id's own: a row the engine hands back under - * another spelling (a case-insensitive collation, a numeric id asked as - * `'07'`) answers `null`, as at {@link getRecordLocks}. That is the one rule - * both doors can apply alike: one `$in` read for a page cannot say which - * asked id a row spelled otherwise answers — a page asking two spellings of - * one row reads exactly like a page asking a missing id — and resolving it - * would cost a read per row. The ids a client holds are the ones the engine - * spelled, so nothing it asks is refused by this; and the lock is judged - * under the row's own id, never under another spelling of it. + * Any row the read hands back counts, whatever spelling of the id the + * engine hands back (a case-insensitive collation, a numeric id asked as + * `'07'`); {@link getRecordLocks} counts only the row whose id IS the asked + * id. The two doors keep different readability anchors on purpose: + * aligning them would narrow a published answer (seat ruling on PR #37191). * * ## What is answered — the lock and its kind, nothing about the request * @@ -11498,7 +11501,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const readable = await this.engine.find(objectName, { where: { id }, fields: ['id'], limit: 1, context, }); - if (!Array.isArray(readable) || !readable.some((row: any) => String(row?.id) === id)) return null; + if (!Array.isArray(readable) || readable.length === 0) return null; if (await detailRowHeldByLockingApproval(this.engine, objectName, id)) return recordLockAnswer(true, false); return recordLockAnswer(false, await recordHeldByLockingApproval(this.engine, objectName, id)); } diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index 463adc817a3..60555c8f87d 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -22,8 +22,10 @@ * - `lockSource` says which approval holds a locked row — its own * (`'record'`) or its master's (`'master'`, winning when both hold) — and * so which delete the server refuses; the page read gives each row the - * single read's kind, and counts a row readable by the single read's rule, - * a loosely matched id included (ruling 7148480184). + * single read's kind (ruling 7148480184); + * - the two doors keep their own readability anchors (seat ruling on PR + * #37191): the single read counts any row its read hands back, the page + * read only the row whose id IS the asked id. * * The REST door's half (one 404 for both `null`s, the closed query set, the * `{ locked, lockSource }`-only payload) is pinned in `@objectstack/rest`; the whole path @@ -521,14 +523,14 @@ describe('lockSource — which approval holds a locked row, the same at the sing }); /** - * The readability anchor, one rule at both doors (#37151 comment 7148285178): - * a row counts as readable when the caller's read hands back the row whose id - * IS the asked id. `getRecordLock` used to count any row the read handed back, - * so a loosely matched id (a case-insensitive collation, `'07'` for `'7'`) - * answered the lock there and `null` at the page read, which cannot say which - * asked id a row spelled otherwise answers without a read per row. + * The readability anchors, kept apart on purpose (seat ruling on PR #37191): + * `getRecordLock` counts any row its read hands back, whatever spelling of the + * id the engine hands back; `getRecordLocks` counts only the row whose id IS + * the asked id. Aligning them would narrow a published answer, so each door's + * own anchor is pinned here, and the two doors agree for every id spelled as + * the engine spells it. */ -describe('both lock reads count a row readable by one rule — a loosely matched id included', () => { +describe('the two doors keep their own readability anchors — a loosely matched id', () => { const LINE = lineOf(HELD); /** Rewrite every `id` value in a read's predicate to lower case: a case-insensitive collation. */ @@ -555,7 +557,7 @@ describe('both lock reads count a row readable by one rule — a loosely matched }, { object }); } - it('answers a loosely matched id `null` at both reads, and the echoed spelling of the same row its lock', async () => { + it('the single door answers the lock for a loosely spelled id; the page door answers it `null`', async () => { const rig = await boot(); caseInsensitiveIds(rig.engine, LINE); caseInsensitiveIds(rig.engine, HELD); @@ -564,24 +566,25 @@ describe('both lock reads count a row readable by one rule — a loosely matched const found = await rig.engine.find(LINE, { where: { id: loose(recordA(LINE)) }, fields: ['id'], context: SYSTEM }); expect((found as any[]).map((row) => row.id)).toEqual([recordA(LINE)]); - expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toBeNull(); - expect(await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER))).toEqual(BYMASTER); + // The single door: any row the read hands back counts — the line of a held master answers its lock. + expect(await rig.svc.getRecordLock(LINE, loose(recordA(LINE)), asUser(SUBMITTER))).toEqual(BYMASTER); + expect(await rig.svc.getRecordLock(LINE, loose(recordB(LINE)), asUser(SUBMITTER))).toEqual({ locked: false }); + // …and still `null` for a row the caller cannot read, however it is spelled. + expect(await rig.svc.getRecordLock(LINE, loose(recordB(LINE)), asUser(READER))).toBeNull(); + + // The page door: only the row whose id IS the asked id — a loose spelling answers `null`, + // alone and beside the echoed spelling of the same row. expect(await rig.svc.getRecordLocks(LINE, [loose(recordA(LINE))], asUser(SUBMITTER))).toEqual([null]); - // Beside the echoed spelling of the same row, beside a missing id: one answer per spelling. - const lineIds = [loose(recordA(LINE)), recordB(LINE), MISSING, loose(recordB(LINE)), recordA(LINE)]; - expect(await rig.svc.getRecordLocks(LINE, lineIds, asUser(SUBMITTER))) - .toEqual([null, { locked: false }, null, null, BYMASTER]); + expect(await rig.svc.getRecordLocks(LINE, [loose(recordA(LINE)), recordA(LINE), MISSING], asUser(SUBMITTER))) + .toEqual([null, BYMASTER, null]); + + // Every id spelled as the engine spells it: the two doors agree, for every caller. + const echoed = [recordA(LINE), recordB(LINE), MISSING, recordA(LINE)]; for (const caller of [SUBMITTER, APPROVER, READER]) { - for (const [object, ids] of [ - [LINE, lineIds], - [LINE, [loose(recordA(LINE))]], - [HELD, [loose(recordA(HELD)), recordB(HELD), loose(MISSING), recordA(HELD)]], - ] as Array<[string, string[]]>) { - const page = await rig.svc.getRecordLocks(object, ids, asUser(caller)); - const oneByOne = []; - for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller))); - expect(page, `${caller} ${object} ${ids.join(',')}`).toEqual(oneByOne); - } + const page = await rig.svc.getRecordLocks(LINE, echoed, asUser(caller)); + const oneByOne = []; + for (const id of echoed) oneByOne.push(await rig.svc.getRecordLock(LINE, id, asUser(caller))); + expect(page, caller).toEqual(oneByOne); } }); diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index 12a815c0b6d..205f19b8696 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -549,7 +549,10 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // The lock of a PAGE of records, in one request: what a list asks before it // opens a cell editor, so moving through the rows sends no request per row. - // Each entry is exactly the single-record door's answer for that id — + // Each entry is exactly the single-record door's answer for that id, as + // the engine spells it (an id matched only under another spelling answers + // `locked: null` here: the two doors keep different readability anchors + // on purpose, seat ruling on PR #37191) — // `locked`, and `lockSource` on a locked row — the 404 folded to // `locked: null` (unreadable or missing, told apart by nothing); a service // without `getRecordLocks` answers 501, never one `getRecordLock` per id. diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 7a2d4d41330..bb925acb28a 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -1105,8 +1105,7 @@ export interface IApprovalService { * the carrier. * * - **Who is answered:** every caller who can READ the record, judged by - * reading it AS THE CALLER (object read, then row-level access); the row - * read must be the asked id's own, spelled as asked. A caller + * reading it AS THE CALLER (object read, then row-level access). A caller * who cannot read it gets `null` — exactly the answer for a record id that * does not exist, ⛔ never one that tells the two apart. A caller refused * the object's read outright is refused the same way for every id. @@ -1151,7 +1150,7 @@ export interface IApprovalService { * per row. * * Entry `i` of the answer answers `recordIds[i]` with exactly what - * {@link getRecordLock} answers for that id: `{ locked, lockSource }` for a + * {@link getRecordLock} answers for that id, spelled as the engine spells it: `{ locked, lockSource }` for a * locked record and `{ locked: false }` for an unlocked one when the caller * can read the record, `null` when it cannot or when it does not exist, * ⛔ never an entry that tells the two apart. The same judgement, off the @@ -1159,7 +1158,12 @@ export interface IApprovalService { * master-detail line, the detail-row lock's: a line answers `true` while a * record it belongs to is so held, with `lockSource: 'master'` (which wins * when the line is held by a request of its own too). A row counts as - * readable by the same rule as at {@link getRecordLock}. A repeated id + * readable only when the read hands back the row whose id IS the asked id; + * {@link getRecordLock} counts any row its read hands back, so an id the + * engine matches under another spelling answers `null` here and the lock + * there. The two doors keep different readability anchors on purpose: + * aligning them would narrow a published answer (seat ruling on PR #37191). + * A repeated id * is answered at each of its positions. A caller refused the object's read * outright is refused the same way for every id. * From 030cd914ca876896bf487e2a01efaf24aeba3b37 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:17:05 +0000 Subject: [PATCH 7/7] docs(approvals): state how the single lock door judges a loosely spelled id; cite the anchor ruling Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php --- .changeset/37151-record-lock-source.md | 4 ++-- content/docs/automation/approvals.mdx | 8 ++++++-- packages/client/src/index.ts | 3 +-- .../plugins/plugin-approvals/src/approval-service.ts | 8 ++++++-- .../src/record-lock-read.integration.test.ts | 6 +++--- packages/rest/src/approvals-routes.ts | 2 +- packages/spec/src/contracts/approval-service.ts | 12 +++++++++--- 7 files changed, 28 insertions(+), 15 deletions(-) diff --git a/.changeset/37151-record-lock-source.md b/.changeset/37151-record-lock-source.md index 0a8b1aabadf..a1e0d9060f6 100644 --- a/.changeset/37151-record-lock-source.md +++ b/.changeset/37151-record-lock-source.md @@ -17,8 +17,8 @@ Both approval lock reads (`IApprovalService.getRecordLock` and `getRecordLocks`, When both hold (a line with a pending request of its own, under a held master), the answer is `'master'`, because that is the delete the server refuses. An unlocked record still answers `{ locked: false }`, with no `lockSource`, and `null` (`404 RECORD_NOT_FOUND` at the single door, `locked: null` in the batch door) still means unreadable or missing, never told apart. No request id, node, approvers or `pending` flag is served. A list can now hide Delete on a line whose master is under approval instead of offering a delete the server refuses. -The `IApprovalService` return types gain the optional `lockSource?: 'record' | 'master'`, so an existing implementation that answers `{ locked }` alone still satisfies the contract; the REST doors then serve `{ locked: true }` without a kind. +The `IApprovalService` return types gain the optional `lockSource?: 'record' | 'master'`, so an implementation may omit it on a locked answer and still satisfies the contract; the REST doors then serve `{ locked: true }` without a kind. -Which rows count as readable is unchanged at both doors. The two doors keep different readability anchors on purpose: the single door counts any returned row, the batch door only the row whose id is the asked id; aligning them would narrow a published answer (seat ruling on PR #37191). So an id the database matches only under another spelling (a different letter case, `07` for a numeric `7`) answers its lock at the single-record door and `null` in the batch door; a client asking with the ids the server gave it gets the same answer from both. +Which rows count as readable is unchanged at both doors. The two doors keep different readability anchors on purpose: the single door counts any returned row, the batch door only the row whose id is the asked id; aligning them would narrow a published answer (seat ruling 7152650156 on #37151). So an id the database matches only under another spelling (a different letter case, `07` for a numeric `7`) answers `null` in the batch door. The single-record door counts the row it finds as readable and judges it, as before: a line of a held master answers `'master'`, because that check reads the row found, but a record's own request is looked up by the id as asked, so a record held by its own request may answer `{ locked: false }` under another spelling. A client asking with the ids the server gave it gets the same answer from both doors. `@objectstack/client`: `client.approvals.getRecordLock` and `getRecordLocks` type the answer with the optional `lockSource?: 'record' | 'master'`. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 81fb7d08ca9..effd486b0f1 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -492,8 +492,12 @@ Each entry is what the single-record read answers for that id, in the order the ids were sent; `null` stands where that read answers `404`, so a record the caller cannot read and one that does not exist look the same. Send the ids as the server spelled them: an id the database matches only under another spelling -(a different letter case, `07` for `7`) answers `null` here, where the -single-record read answers its lock. One request +(a different letter case, `07` for `7`) answers `null` here. The single-record +read does find such a record and answers for it, but it looks up the record's +own request by the id as sent, so it may answer `{ "locked": false }` for a +record its own request holds; a line of a locked record still answers +`"master"`. The two reads keep these different rules on purpose (seat ruling +7152650156 on #37151). One request carries at most 200 ids (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`); a longer list, an empty one or any other body key is refused with `400 VALIDATION_ERROR`. The SDK call is `client.approvals.getRecordLocks(object, recordIds)`, the service diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index ce2338a6c16..6d9368259b5 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -7152,8 +7152,7 @@ export class ObjectStackClient { * locked record which approval holds it, `lockSource`: `'record'` (its own; * deleting it cancels the request) or `'master'` (the record a * master-detail line belongs to; the server refuses the line's delete too) — - * and - * nothing else, answered to every caller who can read the record, whether + * and nothing else, answered to every caller who can read the record, whether * or not they take part in the approval (`IApprovalService.getRecordLock`). * A record the caller cannot read answers 404, exactly as a record id that * does not exist; a deployment without the read answers 501. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 0b6d48183b0..63a1d9c3abd 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -11342,7 +11342,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * here. {@link getRecordLock} counts any row its read hands back, so for * such an id the two doors differ, deliberately: the two doors keep * different readability anchors on purpose, and aligning them would narrow - * a published answer (seat ruling on PR #37191). For an id spelled as the + * a published answer (seat ruling 7152650156 on #37151). For an id spelled as the * engine spells it — what a list holds — entry `i` is exactly the single * door's answer. * @@ -11473,7 +11473,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * engine hands back (a case-insensitive collation, a numeric id asked as * `'07'`); {@link getRecordLocks} counts only the row whose id IS the asked * id. The two doors keep different readability anchors on purpose: - * aligning them would narrow a published answer (seat ruling on PR #37191). + * aligning them would narrow a published answer (seat ruling 7152650156 on #37151). + * For such an id the master half below reads the row the engine found, but + * the row's own request is looked up by the id as asked + * ({@link recordHeldByLockingApproval}), so a record held by its own request + * may answer `{ locked: false }` under another spelling. * * ## What is answered — the lock and its kind, nothing about the request * diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index 60555c8f87d..d97914b0134 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -23,8 +23,8 @@ * (`'record'`) or its master's (`'master'`, winning when both hold) — and * so which delete the server refuses; the page read gives each row the * single read's kind (ruling 7148480184); - * - the two doors keep their own readability anchors (seat ruling on PR - * #37191): the single read counts any row its read hands back, the page + * - the two doors keep their own readability anchors (seat ruling + * 7152650156 on #37151): the single read counts any row its read hands back, the page * read only the row whose id IS the asked id. * * The REST door's half (one 404 for both `null`s, the closed query set, the @@ -523,7 +523,7 @@ describe('lockSource — which approval holds a locked row, the same at the sing }); /** - * The readability anchors, kept apart on purpose (seat ruling on PR #37191): + * The readability anchors, kept apart on purpose (seat ruling 7152650156 on #37151): * `getRecordLock` counts any row its read hands back, whatever spelling of the * id the engine hands back; `getRecordLocks` counts only the row whose id IS * the asked id. Aligning them would narrow a published answer, so each door's diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index 205f19b8696..cf6e8cf4f72 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -552,7 +552,7 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // Each entry is exactly the single-record door's answer for that id, as // the engine spells it (an id matched only under another spelling answers // `locked: null` here: the two doors keep different readability anchors - // on purpose, seat ruling on PR #37191) — + // on purpose, seat ruling 7152650156 on #37151) — // `locked`, and `lockSource` on a locked row — the 404 folded to // `locked: null` (unreadable or missing, told apart by nothing); a service // without `getRecordLocks` answers 501, never one `getRecordLock` per id. diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index bb925acb28a..6aa2cc4030f 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -1123,6 +1123,8 @@ export interface IApprovalService { * A record held by its own request may still be deleted, which cancels * the request; a line of a held master refuses insert, update and delete. * An unlocked record answers `{ locked: false }`, with no `lockSource`. + * An implementation may omit `lockSource` on a locked answer; the REST + * doors then serve `{ locked: true }` alone, never a guessed kind. * ⛔ No request id, node, participants or `pending` flag: whether * the caller may see the request is still `approvalsVisibleToReaders`' * question, and this member does not answer it. `lockSource` is one kind @@ -1160,9 +1162,13 @@ export interface IApprovalService { * when the line is held by a request of its own too). A row counts as * readable only when the read hands back the row whose id IS the asked id; * {@link getRecordLock} counts any row its read hands back, so an id the - * engine matches under another spelling answers `null` here and the lock - * there. The two doors keep different readability anchors on purpose: - * aligning them would narrow a published answer (seat ruling on PR #37191). + * engine matches under another spelling answers `null` here and is judged + * there — but not wholly on the row found: the line-of-a-held-master half + * reads the row the engine found, so such a line answers `'master'`, while + * the row's own request is looked up by the id as asked, so a record held by + * its own request may answer `{ locked: false }` there. The two doors keep + * different readability anchors on purpose: aligning them would narrow a + * published answer (seat ruling 7152650156 on #37151). * A repeated id * is answered at each of its positions. A caller refused the object's read * outright is refused the same way for every id.