Skip to content

Commit fd462c5

Browse files
feat(plugin-approvals): the record lock reads say whether a row is held by its own approval or by its master's (#37191)
repo:objectstack#3 · os-support-ai · session_01WGufzeiHatzB4rRx1t4Php _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBEaJzgBWzjWCNjBjkVoeRto)_ Fixes #37151 Clause-②: yes (widening: both lock doors' published entry gains a field) Metadata-protocol: none Ruling-ref: 7148480184 (maintainer, option A, 2026-11-25T00:22Z; seat record 7148474531). Execution, not a decision. ## 维护者速读 - 列表页和单条记录的“查锁”接口现在多回答一项:被锁的记录是自己的审批锁住的,还是所属主记录的审批锁住的;页面上暂时无变化,表格据此隐藏删除按钮由另一张卡(表格行菜单)接着做。 - 按你选定的方案 A 落地,替审批中报销单、订单的明细行使用者解决“列表给了删除、点了却被拒”的问题。 - 出错时最坏情况是某行的锁类型标错,表格多藏或少藏一个删除按钮,不会写错任何数据;可直接撤回。 - 无 ## What changes - **Both lock doors answer the kind.** `IApprovalService.getRecordLock` and `getRecordLocks` (and their REST doors `GET /api/v1/approvals/records/:object/:recordId/lock`, `POST /api/v1/approvals/records/:object/locks`) answer a locked readable row `{ locked: true, lockSource: 'record' | 'master' }`, an unlocked one `{ locked: false }`; `null` (404 / `locked: null`) still means unreadable-or-missing, never told apart. - `'record'`: a pending request on the row itself under a locking node. Its delete is accepted and cancels the request. - `'master'`: the row is a `master_detail` line of a held record (`bindDetailRowLockHook` refuses insert, update and delete). It **wins when both hold** (a self-held line under a held master), because that is the delete the server refuses. - **One spelling of the answer:** `recordLockAnswer(heldByMaster, heldItself)` in `approval-service.ts` builds it for both doors. The single door asks the master's lock first (so a self-held line under a held master answers `'master'`); the page door now asks the detail-row lock of every readable row, not only of the rows its record lookup left unlocked. Read counts per page are unchanged (the two existing read-count pins hold byte for byte). - **Spec contract** (`packages/spec/src/contracts/approval-service.ts`): both return types gain the optional `lockSource?: 'record' | 'master'` (optional, so an implementation answering `{ locked }` alone still conforms — a pure widening; no exported type or const is added, as with the original member). The #25934 ruling A sentence "What is answered: `locked` only." is revised to state the new answer and cites ruling 7148480184; the batch docblock's "exactly what `getRecordLock` answers for that id" now says "spelled as the engine spells it" and names the anchor difference. - **REST** (`approvals-routes.ts`): both doors serve the answer through one projection, `recordLockPayload`, field by field — `locked`, and `lockSource` only on a locked answer and only when it is `'record'` or `'master'`. Anything else an implementation hands back (a request id, `pending`, an unknown kind) is not served; a locked answer naming no kind is served `{ locked: true }`. The route comment's parity sentence ("Each entry is exactly the single-record door's answer for that id") now adds "as the engine spells it" and names the anchor difference. - **Readability anchors, unchanged at both doors** (item 7148285178; Round 2 below). 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). Pinned both ways: the single door answers the lock for a loosely spelled id, the batch door answers it `null`, and the two agree for every id spelled as the engine spells it. - Docs: `content/docs/automation/approvals.mdx` states `lockSource` where it states the lock answer, and the exact-spelling rule. - Changeset: spec, plugin-approvals, rest at `patch` (`Metadata-protocol: none` ⇒ patch under the changeset-level ruling; the widening is declared on the `Clause-②` line). **Disclosure bound (#8652 ruling 5299823744).** The field adds one kind bit to an answer already served only to a caller who can read the row: no request id, node, participants, approver identity, `pending` flag or request content. A caller who can write the line already learns the kind from the `RECORD_LOCKED` sentence; a read-only line reader learns which of the row and its master holds it, where before they learned that one of the two does. **Field name, measured.** `lockSource`, as claimed: spec `api/protocol.zod.ts` `lockSource` ("Which layer asserted the lock", an enum beside the lock flag, `kernel/metadata-protection.zod.ts` `MetadataLockSourceSchema`). Other `lock*` keys measured in `packages/spec/src`: `lockedBy` (a user id, `ui/view.zod.ts`), `lockScope` (`automation/execution.zod.ts`: global / per_record / per_user, the scope a concurrency lock covers, not its origin), `lockState`, `lockReason`; `heldBy` in `packages/cli` names holder packages (a principal). None is closer. ### Read these first 1. `packages/plugins/plugin-approvals/src/approval-service.ts` — `getRecordLock` (master asked first) and `getRecordLocks` (detail lock over every readable row). Riskiest hunk: the master-first order in `getRecordLock`. 2. `packages/rest/src/approvals-routes.ts` — `recordLockPayload`, the disclosure projection. 3. `packages/spec/src/contracts/approval-service.ts` — the revised ruled sentence. ### Two-minute verification `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/record-lock-read.integration.test.ts` — expect 20 tests passed, including the `lockSource` describe (self-held record `'record'`, line of a held master `'master'`, self-held line under a held master `'master'` and its delete refused `RECORD_LOCKED`, self-held line under an unheld master `'record'` and its delete accepted) and the describe pinning each door's own readability anchor for a loosely spelled id. ## Tests - `record-lock-read.integration.test.ts` (real ObjectQL + better-sqlite3 + `ApprovalsServicePlugin.start()`): existing pins re-expressed with the kind; new top-level describes — `lockSource` single/batch parity for a self-held record, a line of a held master, a self-held line under a held master, an unheld record and line, a self-held line under an unheld master, the decided state; each kind tied to the delete the server refuses or accepts; and the readability anchor: a case-insensitive-collation stand-in (a read middleware folding `id` predicates), with a CONTROL that the engine does hand the row back under the loose spelling; the single door answers the lock for it, the batch door `null`; parity for every caller on ids the engine echoes; and a read-count pin for a page with a missing id. - `client.test.ts`: both SDK answers carry and type `lockSource` (a typed assignment the test program compiles). - `rest-approvals-record-lock-route.test.ts`: both doors serve `lockSource` on a locked answer, drop it on an unlocked one, drop an unknown kind and extra fields. - `approval-record-lock-read.dogfood.test.ts`: the fixture's `LOCKED` body gains `lockSource: 'record'` (stale-fixture consequence of this change). <details><summary>Run readings (head 00e32ec)</summary> Union of the derived local families at a453d12; the two ratchet families re-run at the final head 00e32ec (its only change types two test-call option bags). - `pnpm --filter @objectstack/plugin-approvals test` (a453d12): `Test Files 128 passed (128)`, `Tests 1928 passed (1928)`, lock `VERDICT command-exit 0`. - `pnpm --filter @objectstack/plugin-approvals typecheck` + `vitest run src/record-lock-read.integration.test.ts` (00e32ec): `check:test-typecheck: OK ... 8 file(s) / 321 error(s)` (unchanged debt), `Tests 20 passed (20)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/rest test` (a453d12): `Test Files 429 passed (429)`, `Tests 8819 passed | 351 skipped (9170)`, `VERDICT command-exit 0`; `pnpm --filter @objectstack/rest typecheck`: exit 0. - `pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/spec check:generated`: `All 14 generated artifacts are up to date`, exit 0. - Dogfood, this file only (`pnpm --filter '@objectstack/dogfood^...' build`, then `vitest run test/approval-record-lock-read.dogfood.test.ts`): `Tests 1 passed (1)`, `VERDICT command-exit 0`. Full battery not owed (no `!`, widening arm). - `dispatch-gates --ran`: `119 derived famil(ies) accounted for — 116 run, 3 NOT-MEASURED`. NOT MEASURED (exit 3, PREREQUISITE NOT MET, all in CI): `check-plugin-teardown-shape --self-test` (shallow clone cannot reach its pinned fixture commit), `spec check:skill-examples` (`client-react` not built in this worktree), `check:dual-build-cjs-loads` (unbuilt packages). `check:query-options-erasure` was red at a453d12 (test surface 236 to 237, two new `as any` option bags) and green at 00e32ec (`ratchet holds`, `test surface: 236`). `check:nul-bytes` at 00e32ec: OK. - `overlap-check`: `VERDICT clean exit 0` (origin/main and #37148). </details> ## Round 2 (seat ruling on PR #37191), head e99cf2c - **Anchor: not narrowed.** The single door's readability anchor is restored byte for byte to `origin/main` (any returned row counts as readable); the batch door keeps its strict anchor. 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). I found no reason the single door cannot keep its anchor: the `lockSource` master check reads the row through the engine (`detailRowHeldByLockingApproval`, whose existing pin answers from the row it found, not from the engine's spelling), so a loosely spelled line of a held master answers `'master'` at the single door. The round-1 anchor-parity pin is replaced by pins for the two kept behaviours. Changeset, `approvals.mdx`, both docblocks, the plugin docblocks and the batch route comment now state the two anchors instead of an alignment. - **Client SDK:** `client.approvals.getRecordLock` and `getRecordLocks` (`packages/client/src/index.ts`) type the answer with the optional `lockSource?: 'record' | 'master'`; pinned in `client.test.ts` with a typed assignment. `@objectstack/client` patch added to the changeset. Still a widening under the declared `Clause-②`. - **Not touched:** `record-page-routes.ts` and the skills sentence (routed to triage by the seat). <details><summary>Round 2 run readings (head e99cf2c)</summary> - `pnpm --filter @objectstack/plugin-approvals test`: `Test Files 128 passed (128)`, `Tests 1928 passed (1928)`; `rest` `vitest run src/rest-approvals-record-lock-route.test.ts src/rest-write-response-internal-fields.tripwire.test.ts`: `Tests 36 passed (36)`; `pnpm --filter @objectstack/client test`: `Test Files 59 passed (59)`, `Tests 820 passed (820)`; one lock run, `VERDICT command-exit 0`. - Typecheck plugin-approvals (test-layer debt unchanged at 321), rest and client (test layer 0 errors): exit 0. `spec build && check:generated`: `All 14 generated artifacts are up to date`. - Reverse checks (fix committed, worktree-only restores, both files restored with `git checkout HEAD`, hashes equal to HEAD's): `approval-service.ts` from 00e32ec (the strict single-door anchor) makes the kept-anchor pin red (`1 failed | 19 passed`); `packages/client/src/index.ts` from `origin/main` makes the client test-layer typecheck red (`src/client.test.ts: 2 type error(s)`). - `dispatch-gates --ran`: `120 derived famil(ies) accounted for — 116 run, 4 NOT-MEASURED`. NOT MEASURED (exit 3, PREREQUISITE NOT MET; all run in CI): `check-plugin-teardown-shape --self-test` (shallow clone), `spec check:skill-examples` (client-react not built), `check:dual-build-cjs-loads` and `check:i18n` (workspace packages and the CLI not built in this fresh worktree). `check:query-options-erasure` and `check:nul-bytes`: exit 0. - `overlap-check`: `VERDICT clean exit 0` (origin/main 893eac8 and #37148). </details> ## Round 3 (L1 7152634100, L2 PASS with S1 7152618670), head 030cd91 Wording only; no behaviour change. - **S1:** round 2 said the single door answers "the lock" for a loosely spelled id. That is only half true. Measured against the code: `getRecordLock` counts any returned row as readable. Its master half (`detailRowHeldByLockingApproval`) reads the row the engine found, so a loosely spelled line of a held master answers `'master'` (pinned in round 2). Its own half (`recordHeldByLockingApproval`) looks up the pending request by the id as asked, so a record held by its own request may answer `{ locked: false }` under another spelling. That is main's behaviour. The spec batch docblock, the changeset and `approvals.mdx` now say exactly this; the plugin's `getRecordLock` docblock says it too. - **S2:** the anchor ruling is cited by comment id: seat ruling 7152650156 on #37151. It withdraws the "built with a parity pin" line of 7148480184. The citation is in the spec docblock, the changeset and `approvals.mdx`, and also in the plugin docblocks, the batch route comment and the test header, replacing "seat ruling on PR #37191". Triage's anchor row 7148285178 is carried, not ticked: the seat asked triage to move it to a carrier (mailbox #36743 comment 7152670747). - **Nits:** the spec `getRecordLock` docblock now says an implementation may omit `lockSource` on a locked answer (the REST doors then serve `{ locked: true }` alone); the changeset says the same. The broken sentence in the client `getRecordLock` docblock is joined. - **Routing:** the skills sentence is a row on #35769 (triage 7151747767), and the record-page composite is #37195 (Acceptance notes updated). <details><summary>Round 3 run readings (head 030cd91)</summary> - `overlap-check`: `VERDICT clean exit 0` (origin/main bc3ec37, #37148), run before the push. - One lock run (`VERDICT command-exit 0`): closure build of client and plugin-approvals (spec rebuilt), `spec check:generated` `All 14 generated artifacts are up to date`, typecheck client / plugin-approvals (test debt 321, unchanged) / rest exit 0, `record-lock-read.integration.test.ts` `Tests 20 passed (20)` (test header text changed). - Text gates, exit 0: `check:doc-authoring`, `check:issue-citations`, `check:docs-transcript-drift`, `check:nul-bytes`, `spec check:docs`, `check-affected-docs`, `check-empty-changeset`, `check-changeset-no-major`, `check:spec-docblock-symbol-anchors`. </details> ## Acceptance notes - **Not changed, carried elsewhere:** the published skill sentence in `skills/objectstack-automation/references/state-machines-and-approvals.md` ("`locked` and nothing else") is carried as a row on the skills sweep card #35769 (triage 7151747767); the record-page composite (`packages/rest/src/record-page-routes.ts`, which serves its `lock` as `{ locked }` alone) is #37195. - **Read-only inference, not filed:** the record-lock write hook keys a by-id write on the id as the writer spells it; on a driver whose id column matches a spelling the request bookkeeping does not (a numeric id asked as `07`), the hook's request lookup and the driver's row match could disagree. No public entry was shown to send such an id; no reach measured. - `ui/packages/plugin-grid/**` untouched: hiding Delete on `lockSource: 'master'` is seat 4's half under #36911. ## Verification - Reverse verification (fix committed first): `approval-service.ts` restored from `origin/main` (a10345a) into the worktree only, `record-lock-read.integration.test.ts` run: 11 failed / 9 passed (round 1, at db800fe: every new and kind-bearing pin red); restored with `git checkout HEAD --`, blob hash equal to HEAD's, `git diff HEAD` empty. - Cross-package type check: the plugin's `getRecordLock` return type widened to admit a third kind ⇒ `tsc --noEmit` red `TS2416 Property 'getRecordLock' in type 'ApprovalService' is not assignable to the same property in base type 'IApprovalService'` against the rebuilt spec `dist`; restored, hash verified. - `overlap-check --branch=claude/issue-37151-lock-source-field`: `VERDICT clean exit 0` — merges cleanly with origin/main and with #37148 (shares both `approval-service.ts` files, different regions). --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzeiHatzB4rRx1t4Php)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzeiHatzB4rRx1t4Php --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3d4f423 commit fd462c5

11 files changed

Lines changed: 445 additions & 98 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/plugin-approvals': patch
4+
'@objectstack/rest': patch
5+
'@objectstack/client': patch
6+
---
7+
8+
feat(plugin-approvals): the record lock reads say whether a row is held by its own approval or by its master's
9+
10+
Clause-②: yes (widening: both lock doors' published entry gains a field)
11+
Metadata-protocol: none
12+
13+
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:
14+
15+
- `'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.
16+
- `'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`.
17+
18+
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.
19+
20+
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.
21+
22+
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.
23+
24+
`@objectstack/client`: `client.approvals.getRecordLock` and `getRecordLocks` type the answer with the optional `lockSource?: 'record' | 'master'`.

‎content/docs/automation/approvals.mdx‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -450,16 +450,26 @@ request row:
450450
```bash
451451
curl -b cookies.txt \
452452
"https://your-app.example.com/api/v1/approvals/records/expense/rec_123/lock"
453-
# → { "success": true, "data": { "locked": true } }
453+
# → { "success": true, "data": { "locked": true, "lockSource": "record" } }
454454
```
455455

456-
The answer is `locked` and nothing else: no request, approvers or history,
457-
which stay behind the object's `approvalsVisibleToReaders` switch. `locked` is
458-
`true` while a pending request's node has `lockRecord` other than `false`. That
459-
is the same check the server applies when it refuses an edit with `409
460-
RECORD_LOCKED`, so a page that reads it never offers an edit the server will
461-
refuse. Asked of a line, it answers `true` while the record the line belongs to
462-
is locked. The record is read as the caller: a record they cannot read answers
456+
The answer is `locked` and, on a locked record, `lockSource`, and nothing else:
457+
no request, approvers or history, which stay behind the object's
458+
`approvalsVisibleToReaders` switch. `locked` is `true` while a pending request's
459+
node has `lockRecord` other than `false`. That is the same check the server
460+
applies when it refuses an edit with `409 RECORD_LOCKED`, so a page that reads
461+
it never offers an edit the server will refuse. Asked of a line, it answers
462+
`true` while the record the line belongs to is locked.
463+
464+
`lockSource` says which approval holds the record, and so which delete the
465+
server refuses. `"record"`: the record's own request holds it, and deleting the
466+
record still goes through and cancels the request. `"master"`: the record is a
467+
line of a locked record, and the server refuses its delete as well as its edit.
468+
A line under a locked record that also has a pending request of its own answers
469+
`"master"`. An unlocked record answers `{ "locked": false }` with no
470+
`lockSource`.
471+
472+
The record is read as the caller: a record they cannot read answers
463473
`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets. The
464474
SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service
465475
member is `IApprovalService.getRecordLock`. An approvals service without that
@@ -473,14 +483,21 @@ curl -b cookies.txt -X POST -H 'Content-Type: application/json' \
473483
-d '{"recordIds":["rec_123","rec_456","rec_789"]}' \
474484
"https://your-app.example.com/api/v1/approvals/records/expense/locks"
475485
# → { "success": true, "data": { "records": [
476-
# { "recordId": "rec_123", "locked": true },
486+
# { "recordId": "rec_123", "locked": true, "lockSource": "record" },
477487
# { "recordId": "rec_456", "locked": false },
478488
# { "recordId": "rec_789", "locked": null } ] } }
479489
```
480490

481491
Each entry is what the single-record read answers for that id, in the order the
482492
ids were sent; `null` stands where that read answers `404`, so a record the
483-
caller cannot read and one that does not exist look the same. One request
493+
caller cannot read and one that does not exist look the same. Send the ids as
494+
the server spelled them: an id the database matches only under another spelling
495+
(a different letter case, `07` for `7`) answers `null` here. The single-record
496+
read does find such a record and answers for it, but it looks up the record's
497+
own request by the id as sent, so it may answer `{ "locked": false }` for a
498+
record its own request holds; a line of a locked record still answers
499+
`"master"`. The two reads keep these different rules on purpose (seat ruling
500+
7152650156 on #37151). One request
484501
carries at most 200 ids (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`); a longer list,
485502
an empty one or any other body key is refused with `400 VALIDATION_ERROR`. The
486503
SDK call is `client.approvals.getRecordLocks(object, recordIds)`, the service

‎packages/client/src/client.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -758,19 +758,29 @@ describe('Approvals namespace (ADR-0019)', () => {
758758
});
759759

760760
it('[#26314] reads a record\'s approval lock off the envelope, path segments encoded', async () => {
761-
const { client, fetchMock } = createMockClient({ success: true, data: { locked: true } });
761+
const { client, fetchMock } = createMockClient({ success: true, data: { locked: true, lockSource: 'record' } });
762762
const result = await client.approvals.getRecordLock('order', 'rec/1');
763-
expect(result).toEqual({ locked: true });
763+
expect(result).toEqual({ locked: true, lockSource: 'record' });
764+
// The answer types the kind (the test program compiles this line).
765+
const kind: 'record' | 'master' | undefined = result.lockSource;
766+
expect(kind).toBe('record');
764767
const [url, opts] = fetchMock.mock.calls[0];
765768
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/order/rec%2F1/lock');
766769
expect(opts?.method ?? 'GET').toBe('GET');
767770
});
768771

769772
it('reads the approval locks of a page of records in one POST, object segment encoded', async () => {
770-
const records = [{ recordId: 'rec_1', locked: true }, { recordId: 'rec_2', locked: null }];
773+
const records = [
774+
{ recordId: 'rec_1', locked: true, lockSource: 'master' },
775+
{ recordId: 'rec_2', locked: null },
776+
{ recordId: 'rec_3', locked: false },
777+
];
771778
const { client, fetchMock } = createMockClient({ success: true, data: { records } });
772779
const result = await client.approvals.getRecordLocks('sales order', ['rec_1', 'rec_2']);
773780
expect(result).toEqual({ records });
781+
// The entry types the kind (the test program compiles this line).
782+
const kinds: Array<'record' | 'master' | undefined> = result.records.map((entry) => entry.lockSource);
783+
expect(kinds).toEqual(['master', undefined, undefined]);
774784
expect(fetchMock).toHaveBeenCalledTimes(1);
775785
const [url, opts] = fetchMock.mock.calls[0];
776786
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/sales%20order/locks');

‎packages/client/src/index.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7148,18 +7148,24 @@ export class ObjectStackClient {
71487148
},
71497149

71507150
/**
7151-
* Whether a record is held by a locking approval — `{ locked }` and
7152-
* nothing else, answered to every caller who can read the record, whether
7151+
* Whether a record is held by a locking approval — `{ locked }`, plus on a
7152+
* locked record which approval holds it, `lockSource`: `'record'` (its own;
7153+
* deleting it cancels the request) or `'master'` (the record a
7154+
* master-detail line belongs to; the server refuses the line's delete too) —
7155+
* and nothing else, answered to every caller who can read the record, whether
71537156
* or not they take part in the approval (`IApprovalService.getRecordLock`).
71547157
* A record the caller cannot read answers 404, exactly as a record id that
71557158
* does not exist; a deployment without the read answers 501.
71567159
*/
7157-
getRecordLock: async (object: string, recordId: string): Promise<{ locked: boolean }> => {
7160+
getRecordLock: async (
7161+
object: string,
7162+
recordId: string,
7163+
): Promise<{ locked: boolean; lockSource?: 'record' | 'master' }> => {
71587164
const route = this.getRoute('approvals');
71597165
const res = await this.fetch(
71607166
`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/${encodeURIComponent(recordId)}/lock`,
71617167
);
7162-
return this.unwrapResponse<{ locked: boolean }>(res);
7168+
return this.unwrapResponse<{ locked: boolean; lockSource?: 'record' | 'master' }>(res);
71637169
},
71647170

71657171
/**
@@ -7173,13 +7179,15 @@ export class ObjectStackClient {
71737179
getRecordLocks: async (
71747180
object: string,
71757181
recordIds: readonly string[],
7176-
): Promise<{ records: Array<{ recordId: string; locked: boolean | null }> }> => {
7182+
): Promise<{ records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }> }> => {
71777183
const route = this.getRoute('approvals');
71787184
const res = await this.fetch(`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/locks`, {
71797185
method: 'POST',
71807186
body: JSON.stringify({ recordIds: [...recordIds] }),
71817187
});
7182-
return this.unwrapResponse<{ records: Array<{ recordId: string; locked: boolean | null }> }>(res);
7188+
return this.unwrapResponse<{
7189+
records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }>;
7190+
}>(res);
71837191
},
71847192

71857193
/**

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

Lines changed: 64 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2232,6 +2232,23 @@ async function findChildRequestId(
22322232
*/
22332233
const REQUEST_VISIBILITY = new WeakMap<ApprovalService, RequestVisibilitySource>();
22342234

2235+
/**
2236+
* The answer both record-lock doors give a readable row
2237+
* (`IApprovalService.getRecordLock` / `getRecordLocks`, ruling 7148480184):
2238+
* which approval holds it, the master's winning when both do — a line of a held
2239+
* master refuses delete as well as edit, while a record held by its own request
2240+
* may be deleted, which cancels the request. One spelling, so the two doors
2241+
* cannot answer a row differently.
2242+
*/
2243+
function recordLockAnswer(
2244+
heldByMaster: boolean,
2245+
heldItself: boolean,
2246+
): { locked: boolean; lockSource?: 'record' | 'master' } {
2247+
if (heldByMaster) return { locked: true, lockSource: 'master' };
2248+
if (heldItself) return { locked: true, lockSource: 'record' };
2249+
return { locked: false };
2250+
}
2251+
22352252
/**
22362253
* [#23889] Each service's own slot labeller — the one its live writers label
22372254
* `pending_approver_labels` / `acted_as_label` with — for the boot backfills
@@ -11313,15 +11330,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1131311330
* detail object only — the detail-row lock's batch form
1131411331
* ({@link detailRowsHeldByLockingApproval}: one FK read plus one lookup per
1131511332
* `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]`.
11333+
* it does at {@link getRecordLock}, with the same `lockSource`. Entry `i`
11334+
* answers `recordIds[i]`.
11335+
*
11336+
* ## Which rows count as readable — the row whose id IS the asked id
11337+
*
11338+
* A row is readable here when the caller's read hands back a row whose id
11339+
* IS the asked id, spelled as asked: one `$in` read cannot say which asked
11340+
* id a row the engine spells differently answers (a case-insensitive
11341+
* collation, a numeric id asked as `'07'`), so such an id answers `null`
11342+
* here. {@link getRecordLock} counts any row its read hands back, so for
11343+
* such an id the two doors differ, deliberately: the two doors keep
11344+
* different readability anchors on purpose, and aligning them would narrow
11345+
* a published answer (seat ruling 7152650156 on #37151). For an id spelled as the
11346+
* engine spells it — what a list holds — entry `i` is exactly the single
11347+
* door's answer.
1131711348
*
1131811349
* The cap is the door's to refuse loudly; here a blank id answers `null`.
1131911350
*/
1132011351
async getRecordLocks(
1132111352
object: string,
1132211353
recordIds: readonly string[],
1132311354
context: ExecutionContext,
11324-
): Promise<Array<{ locked: boolean } | null>> {
11355+
): Promise<Array<{ locked: boolean; lockSource?: 'record' | 'master' } | null>> {
1132511356
const objectName = String(object ?? '').trim();
1132611357
const ids = recordIds.map((recordId) => String(recordId ?? '').trim());
1132711358
const asked = Array.from(new Set(ids.filter((id) => id !== '')));
@@ -11335,12 +11366,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1133511366
const held = readableAsked.length > 0
1133611367
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
1133711368
: new Set<string>();
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)
11369+
// The single door's second half, asked of every readable row: a line held
11370+
// by its own request under a held master answers `'master'` there too.
11371+
const heldByMaster = readableAsked.length > 0
11372+
? await detailRowsHeldByLockingApproval(this.engine, objectName, readableAsked)
1134211373
: new Set<string>();
11343-
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) || heldByMaster.has(id) } : null));
11374+
return ids.map((id) => (readableIds.has(id) ? recordLockAnswer(heldByMaster.has(id), held.has(id)) : null));
1134411375
}
1134511376

1134611377
async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {
@@ -11438,22 +11469,35 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1143811469
* id, existing or not. ⚠️ Probing with {@link SYSTEM_CTX} here would admit
1143911470
* every authenticated user in the tenant.
1144011471
*
11441-
* ## What is answered — the lock, and nothing about the request
11442-
*
11443-
* `{ locked }` only: no request id, node, participants or `pending`. Request
11444-
* content stays behind `approvalsVisibleToReaders` (#8652 ruling 5299823744,
11445-
* untouched). The judgement is the record-lock hook's own
11446-
* ({@link recordHeldByLockingApproval}), never a second copy of it — and,
11447-
* for a master-detail line, the detail-row lock's
11448-
* ({@link detailRowHeldByLockingApproval}): a locked record's lines are
11449-
* locked with it, so the read answers `true` for a line whose write the hook
11450-
* refuses.
11472+
* Any row the read hands back counts, whatever spelling of the id the
11473+
* engine hands back (a case-insensitive collation, a numeric id asked as
11474+
* `'07'`); {@link getRecordLocks} counts only the row whose id IS the asked
11475+
* id. The two doors keep different readability anchors on purpose:
11476+
* aligning them would narrow a published answer (seat ruling 7152650156 on #37151).
11477+
* For such an id the master half below reads the row the engine found, but
11478+
* the row's own request is looked up by the id as asked
11479+
* ({@link recordHeldByLockingApproval}), so a record held by its own request
11480+
* may answer `{ locked: false }` under another spelling.
11481+
*
11482+
* ## What is answered — the lock and its kind, nothing about the request
11483+
*
11484+
* `{ locked, lockSource }` (ruling 7148480184, option A): no request id,
11485+
* node, participants or `pending`. Request content stays behind
11486+
* `approvalsVisibleToReaders` (#8652 ruling 5299823744, untouched);
11487+
* `lockSource` is one kind bit. The judgement is the record-lock hook's own
11488+
* ({@link recordHeldByLockingApproval}), never a second copy of it —
11489+
* `lockSource: 'record'` — and, for a master-detail line, the detail-row
11490+
* lock's ({@link detailRowHeldByLockingApproval}): a locked record's lines
11491+
* are locked with it, so the read answers `true` for a line whose write the
11492+
* hook refuses — `lockSource: 'master'`, asked first because it wins when
11493+
* both hold: a line of a held master refuses delete too, a record held by
11494+
* its own request may be deleted (the delete cancels the request).
1145111495
*/
1145211496
async getRecordLock(
1145311497
object: string,
1145411498
recordId: string,
1145511499
context: ExecutionContext,
11456-
): Promise<{ locked: boolean } | null> {
11500+
): Promise<{ locked: boolean; lockSource?: 'record' | 'master' } | null> {
1145711501
const objectName = String(object ?? '').trim();
1145811502
const id = String(recordId ?? '').trim();
1145911503
if (!objectName || !id) return null;
@@ -11462,9 +11506,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
1146211506
where: { id }, fields: ['id'], limit: 1, context,
1146311507
});
1146411508
if (!Array.isArray(readable) || readable.length === 0) return null;
11465-
const locked = await recordHeldByLockingApproval(this.engine, objectName, id)
11466-
|| await detailRowHeldByLockingApproval(this.engine, objectName, id);
11467-
return { locked };
11509+
if (await detailRowHeldByLockingApproval(this.engine, objectName, id)) return recordLockAnswer(true, false);
11510+
return recordLockAnswer(false, await recordHeldByLockingApproval(this.engine, objectName, id));
1146811511
}
1146911512

1147011513
private async loadRequest(

0 commit comments

Comments
 (0)