Skip to content

Commit a770353

Browse files
committed
fix(plugin-approvals): the batch lock read answers a line of a held master as the single read does
getRecordLocks asked only whether each row was held by a request of its own; getRecordLock also asks the detail-row lock. Add the batch form detailRowsHeldByLockingApproval (one FK read plus one lookup per master_detail edge, never one per row), make the one-row form delegate to it, and pin single/batch parity for a record held itself, a line of a held master and an unheld record. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php
1 parent 517e415 commit a770353

3 files changed

Lines changed: 116 additions & 16 deletions

File tree

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,9 @@ import {
168168
type FieldVisibilitySource,
169169
} from './payload-redaction.js';
170170
import { APPROVAL_REQUEST_CHILD_OBJECTS, type RequestVisibilitySource } from './request-read-gate.js';
171-
import { detailRowHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval } from './lifecycle-hooks.js';
171+
import {
172+
detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval,
173+
} from './lifecycle-hooks.js';
172174
import { PendingApproverReadGrantSource, type PendingApproverReadGrants } from './pending-approver-read-grant.js';
173175
// The ADR-0043 pages — the ONE copy of their text, rendered by the plugin's
174176
// self-hosted mount and by `handleActionPage` alike.
@@ -11303,11 +11305,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1130311305

1130411306
/**
1130511307
* `IApprovalService.getRecordLocks` — {@link getRecordLock} for a page of
11306-
* rows, in two reads whatever the page size: the caller's read of the ids
11307-
* (the same #8652 anchor, one `$in` read AS THE CALLER, so an unreadable row
11308-
* and a missing one both answer `null` and stay indistinguishable) and one
11309-
* pending-request lookup judged by the record-lock hook's own judgement
11310-
* ({@link recordsHeldByLockingApproval}). Entry `i` answers `recordIds[i]`.
11308+
* rows, in a bounded number of reads whatever the page size: the caller's
11309+
* read of the ids (the same #8652 anchor, one `$in` read AS THE CALLER, so an
11310+
* unreadable row and a missing one both answer `null` and stay
11311+
* indistinguishable), one pending-request lookup judged by the record-lock
11312+
* hook's own judgement ({@link recordsHeldByLockingApproval}) and — on a
11313+
* detail object only — the detail-row lock's batch form
11314+
* ({@link detailRowsHeldByLockingApproval}: one FK read plus one lookup per
11315+
* `master_detail` edge), so a line of a held master answers `true` here as
11316+
* it does at {@link getRecordLock}. Entry `i` answers `recordIds[i]`.
1131111317
*
1131211318
* The cap is the door's to refuse loudly; here a blank id answers `null`.
1131311319
*/
@@ -11329,7 +11335,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1132911335
const held = readableAsked.length > 0
1133011336
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
1133111337
: new Set<string>();
11332-
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null));
11338+
// The single door's second half, for the rows the first left unlocked.
11339+
const unheld = readableAsked.filter((id) => !held.has(id));
11340+
const heldByMaster = unheld.length > 0
11341+
? await detailRowsHeldByLockingApproval(this.engine, objectName, unheld)
11342+
: new Set<string>();
11343+
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) || heldByMaster.has(id) } : null));
1133311344
}
1133411345

1133511346
async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {

‎packages/plugins/plugin-approvals/src/lifecycle-hooks.ts‎

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -540,23 +540,56 @@ export async function detailRowHeldByLockingApproval(
540540
objectName: string,
541541
recordId: string,
542542
): Promise<boolean> {
543-
if (isApprovalBookkeepingObject(objectName)) return false;
543+
return (await detailRowsHeldByLockingApproval(engine, objectName, [recordId])).has(recordId);
544+
}
545+
546+
/**
547+
* {@link detailRowHeldByLockingApproval} for many rows of one object at once:
548+
* the ids among `recordIds` that are DETAIL rows of a master held by a LOCKING
549+
* pending approval. One SYSTEM read of the rows' FK columns for the whole list,
550+
* then one lookup per `master_detail` edge for every master those rows name —
551+
* `1 + edges` reads whatever the list's length, never one per row — and the
552+
* same judgement ({@link lockingRequestsForRecords}), so a page asked at once
553+
* and a row asked alone cannot disagree. An object with no `master_detail`
554+
* edge reads nothing.
555+
*
556+
* ⚠️ Like the one-row form, it answers for the rows, not for a caller, and the
557+
* FK read is SYSTEM.
558+
*/
559+
export async function detailRowsHeldByLockingApproval(
560+
engine: Pick<MinimalEngine, 'find' | 'getSchema'>,
561+
objectName: string,
562+
recordIds: ReadonlyArray<string>,
563+
): Promise<Set<string>> {
564+
const held = new Set<string>();
565+
if (recordIds.length === 0 || isApprovalBookkeepingObject(objectName)) return held;
544566
const edges = masterEdgesOf(engine, objectName);
545-
if (edges.length === 0) return false;
567+
if (edges.length === 0) return held;
546568
const rows = await engine.find(objectName, {
547-
where: { id: recordId },
569+
// One id keeps the by-id shape the one-row read always sent.
570+
where: recordIds.length === 1 ? { id: recordIds[0] } : { id: { $in: [...recordIds] } },
548571
fields: ['id', ...edges.map((e) => e.fk)],
549-
limit: 1,
572+
limit: recordIds.length,
550573
// SYSTEM_CTX's arrays are `as const` (readonly); the declared type wants mutable ones.
551574
context: { ...SYSTEM_CTX, positions: [], permissions: [] },
552575
} satisfies EngineQueryOptions);
553-
const row = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;
554-
if (!row) return false;
576+
const found = (Array.isArray(rows) ? rows : []) as Array<Record<string, unknown>>;
577+
if (found.length === 0) return held;
555578
for (const e of edges) {
556-
const masterId = scalarFk(row[e.fk]);
557-
if (masterId && (await lockingRequestsForRecords(engine, e.master, [masterId])).length > 0) return true;
579+
const masterIds = Array.from(new Set(
580+
found.map((row) => scalarFk(row[e.fk])).filter((id): id is string => id !== null),
581+
));
582+
if (masterIds.length === 0) continue;
583+
const heldMasters = new Set(
584+
(await lockingRequestsForRecords(engine, e.master, masterIds)).map((p) => String(p?.record_id ?? '')),
585+
);
586+
if (heldMasters.size === 0) continue;
587+
for (const row of found) {
588+
const masterId = scalarFk(row[e.fk]);
589+
if (masterId && heldMasters.has(masterId)) held.add(String(row.id));
590+
}
558591
}
559-
return false;
592+
return held;
560593
}
561594

562595
/**

‎packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,62 @@ describe('a locked record\'s lines are locked with it — the record-lock read a
335335
expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('written');
336336
});
337337

338+
it('the page read answers a line of a held master as the single read does — held itself, held by its master, unheld', async () => {
339+
const rig = await boot();
340+
// Held itself: record `_a` of the sheet. Held by its master: line `_a`. Unheld: record `_b` and line `_b`.
341+
const scenes: Array<[string, string[]]> = [
342+
[HELD, [recordA(HELD), recordB(HELD), MISSING, recordA(HELD)]],
343+
[LINE, [recordA(LINE), recordB(LINE), MISSING, recordA(LINE)]],
344+
];
345+
for (const caller of [SUBMITTER, APPROVER, READER]) {
346+
for (const [object, ids] of scenes) {
347+
const page = await rig.svc.getRecordLocks(object, ids, asUser(caller));
348+
const oneByOne = [];
349+
for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller)));
350+
expect(page, `${caller} ${object}`).toEqual(oneByOne);
351+
}
352+
}
353+
expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER)))
354+
.toEqual([{ locked: true }, { locked: false }]);
355+
// The reader: line `_a` locked, as its write is refused; line `_b` unreadable reads as missing.
356+
expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE), MISSING], asUser(READER)))
357+
.toEqual([{ locked: true }, null, null]);
358+
expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('RECORD_LOCKED');
359+
// A line held by a request of its own answers locked by both reads too.
360+
await rig.svc.openNodeRequest({
361+
object: LINE, recordId: recordB(LINE), runId: 'run_line_b', nodeId: 'review', flowName: 'line_review',
362+
config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: recordB(LINE), title: recordB(LINE) },
363+
}, asUser(SUBMITTER));
364+
expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER)))
365+
.toEqual([await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER)),
366+
await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))]);
367+
expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER)))
368+
.toEqual([{ locked: true }, { locked: true }]);
369+
// Decided: the line unlocks for the page read as for the hook.
370+
await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER));
371+
expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE)], asUser(READER))).toEqual([{ locked: false }]);
372+
});
373+
374+
it('reads a page of lines in a bounded number of engine reads whatever its size, never one per row', async () => {
375+
const rig = await boot();
376+
for (let i = 0; i < 6; i += 1) {
377+
await rig.engine.insert(LINE, { id: `${LINE}_x${i}`, title: `x${i}`, sheet: i % 2 ? recordA(HELD) : recordB(HELD) },
378+
{ context: SYSTEM } as any);
379+
}
380+
const find = rig.engine.find.bind(rig.engine);
381+
const reads: string[] = [];
382+
(rig.engine as any).find = (object: string, query: any) => {
383+
reads.push(object);
384+
return find(object, query);
385+
};
386+
const ids = [recordA(LINE), recordB(LINE), ...Array.from({ length: 6 }, (_, i) => `${LINE}_x${i}`)];
387+
// As SYSTEM: the extra lines are outside the stand-in's per-user grants.
388+
const page = await rig.svc.getRecordLocks(LINE, ids, SYSTEM);
389+
// The caller's anchor, the rows' own requests, the rows' FK columns, the masters' requests.
390+
expect(reads).toEqual([LINE, 'sys_approval_request', LINE, 'sys_approval_request']);
391+
expect(page.map((entry) => entry?.locked)).toEqual([true, false, false, true, false, true, false, true]);
392+
});
393+
338394
it('answers a line the caller cannot read exactly as one that does not exist', async () => {
339395
const rig = await boot();
340396
await rig.svc.openNodeRequest({

0 commit comments

Comments
 (0)