Skip to content

Commit 2737ac6

Browse files
committed
fix(plugins)!: role and membership-tier holder reads complete past their bound and refuse on a failed read
TeamGraphService.expandRoleUsers (plugin-sharing) and ApprovalService.expandMembershipTierUsers (plugin-approvals) read sys_member once at a 10,000-row bound and turned a failed read into []. Both now page through the shared keysetWalk to completion; a failed read or an incomplete walk throws, a missing table still answers []. The approver-spec resolver names a failed directory read in its warning. Claude-Session: https://claude.ai/code/session_01ADHkmS2E1xdkLMJPnabYgC Co-authored-by: Claude <noreply@anthropic.com>
1 parent b15e854 commit 2737ac6

2 files changed

Lines changed: 143 additions & 25 deletions

File tree

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

Lines changed: 79 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import { ExpressionEngine, collectCelRootIdentifiers } from '@objectstack/formul
2121
// writer-local re-derivation here was rejected by name (Option B): it would be
2222
// a third answer to a question the codebase already answered two ways.
2323
import { createRecordOrganizationResolver, type RecordOrganizationResolver } from '@objectstack/metadata-core';
24-
import { keysetWalk, strandedDecisionFailure } from '@objectstack/types';
24+
import { isMissingTableError, keysetWalk, strandedDecisionFailure } from '@objectstack/types';
2525
// [#15981 / #16166] Every built-in identity NAME is deliberately absent here:
2626
// both arms of `isOverrideActor` read an ADR-0095 capability rung, never a name.
2727
// `BUILTIN_IDENTITY_PLATFORM_ADMIN` went with the platform arm's name read and
@@ -1118,6 +1118,14 @@ const OOO_MAX_CHAIN = 8;
11181118
*/
11191119
const MEMBER_SCREEN_READ_LIMIT = 50000;
11201120

1121+
/**
1122+
* [#29362] Rows per page of the membership-tier read
1123+
* ({@link ApprovalService.expandMembershipTierUsers}) — the bound the read
1124+
* always carried, so a tier held by fewer people issues the one read it always
1125+
* did, and a tier held by more is read in further pages rather than cut.
1126+
*/
1127+
const MEMBER_TIER_PAGE_ROWS = 10000;
1128+
11211129
/**
11221130
* Approver types resolved by QUERYING a graph rather than by taking `value`
11231131
* literally (#3807). Each can legitimately come back empty — an unstaffed
@@ -2551,6 +2559,9 @@ export class ApprovalService implements IApprovalService {
25512559
// The user a `manager` approver resolved FROM, kept for the warning below
25522560
// when no manager comes back.
25532561
let managerSubject: unknown;
2562+
// [#29362] The directory failure the catch below took, kept so the warning
2563+
// can say the read FAILED rather than that the slot expanded to nobody.
2564+
let directoryFailure: string | undefined;
25542565
try {
25552566
if (type === 'team') {
25562567
// #10230: the request's OWN organization, not `directoryOrg`. They are
@@ -2589,7 +2600,11 @@ export class ApprovalService implements IApprovalService {
25892600
if (mgr) return this.applyOooDelegation(mgr, now, organizationId, substitutions);
25902601
}
25912602
}
2592-
} catch { /* a directory lookup failed → handled below as resolving to nobody */ }
2603+
} catch (err) {
2604+
// A directory lookup failed → handled below as resolving to nobody, and
2605+
// the graph-type warning names the failure (#29362).
2606+
directoryFailure = err instanceof Error ? err.message : String(err);
2607+
}
25932608
// #22558: a PERSON type that resolved to nobody contributes NO slot — see
25942609
// PERSON_APPROVER_TYPES for why its `type:value` literal could never be
25952610
// taken. With nothing else on the slate, the request reaches the node's
@@ -2656,12 +2671,24 @@ export class ApprovalService implements IApprovalService {
26562671
// follows. The old ending ("the request cannot advance until someone is
26572672
// added") restated a fate this resolver cannot know, and was false on
26582673
// the default path.
2659-
this.logger?.warn?.(
2660-
`[approvals] approver '${type}:${a.value}' expanded to nobody — the slot names no one, so no one is `
2661-
+ `asked through it. Staff it or re-point the approver; a slate left naming no one is decided by the `
2662-
+ `node's onEmptyApprovers.`,
2663-
{ type, value: a.value, organizationId: organizationId ?? null },
2664-
);
2674+
if (directoryFailure !== undefined) {
2675+
// [#29362] A failed read is not an unstaffed approver: say which one
2676+
// this is, and carry the error, so an operator does not go staffing a
2677+
// position whose holders simply could not be read.
2678+
this.logger?.warn?.(
2679+
`[approvals] approver '${type}:${a.value}' could not be expanded — a directory read failed, so the `
2680+
+ `slot falls back to its literal rather than route to part of its people. Fix the read (see error); `
2681+
+ `a slate left naming no one is decided by the node's onEmptyApprovers.`,
2682+
{ type, value: a.value, organizationId: organizationId ?? null, error: directoryFailure },
2683+
);
2684+
} else {
2685+
this.logger?.warn?.(
2686+
`[approvals] approver '${type}:${a.value}' expanded to nobody — the slot names no one, so no one is `
2687+
+ `asked through it. Staff it or re-point the approver; a slate left naming no one is decided by the `
2688+
+ `node's onEmptyApprovers.`,
2689+
{ type, value: a.value, organizationId: organizationId ?? null },
2690+
);
2691+
}
26652692
}
26662693
// #27397: a `user` that resolved to no one adds no slot — `user:<value>`
26672694
// is no acting address (`approver-address.ts`), and the bare value is the
@@ -3355,16 +3382,55 @@ export class ApprovalService implements IApprovalService {
33553382
* {@link expandPositionUsers} carries the ruling both reads inherit
33563383
* (#8613 / commit 04d03c3a0) — this method is also the second limb of that union, so a
33573384
* change here changes position routing too.
3385+
*
3386+
* [#29362] Read to COMPLETION, or refused — never a shortened or an invented
3387+
* empty slate. Pages of {@link MEMBER_TIER_PAGE_ROWS} through the platform's
3388+
* one keyset walk (`keysetWalk`, `@objectstack/types`), ordered by `id`, so a
3389+
* tier held past the bound routes to every holder rather than the first
3390+
* 10,000 rows. A read that fails, or a walk that cannot vouch for completion
3391+
* (a row without an `id`, a page that did not honour the cursor), THROWS:
3392+
* {@link resolveApproverSpec}'s directory catch then lets the slot fall back
3393+
* to its literal and says the read failed. Answering `[]` instead routed a
3394+
* `position` approver to its assignment holders alone — a shrunk slate that
3395+
* looks complete — and logged an `org_membership_level` one as "expanded to
3396+
* nobody", indistinguishable from a tier no one holds. A table that does not
3397+
* exist is the one failure that IS an answer (a stack that never materialises
3398+
* `sys_member` has no tier holders) and keeps answering `[]`, judged by the
3399+
* shared missing-table predicate.
33583400
*/
33593401
private async expandMembershipTierUsers(tier: string, organizationId?: string | null): Promise<string[]> {
33603402
if (!tier) return [];
3361-
const filter: any = { role: tier };
3403+
const filter: Record<string, unknown> = { role: tier };
33623404
if (organizationId) filter.organization_id = organizationId;
3363-
let rows: any[] = [];
3405+
const scope = `the holders of membership tier '${tier}'${organizationId ? ` in organization '${organizationId}'` : ''}`;
3406+
const users = new Set<string>();
3407+
const walk = keysetWalk<Record<string, unknown>>(
3408+
(page) => this.engine.find('sys_member', { ...page, fields: ['id', 'user_id'], context: SYSTEM_CTX }),
3409+
{ where: filter, pageSize: MEMBER_TIER_PAGE_ROWS },
3410+
);
33643411
try {
3365-
rows = await this.engine.find('sys_member', { filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX } as any);
3366-
} catch { rows = []; }
3367-
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
3412+
for await (const page of walk.pages()) {
3413+
for (const row of page) {
3414+
const uid = String(row?.user_id ?? '');
3415+
if (uid) users.add(uid);
3416+
}
3417+
}
3418+
} catch (err) {
3419+
if (isMissingTableError(err, 'sys_member')) return [];
3420+
throw new Error(
3421+
`[approvals] ${scope} could not be read: ${err instanceof Error ? err.message : String(err)}. `
3422+
+ 'Routing to a shortened slate would leave holders unasked, so the expansion refuses instead.',
3423+
{ cause: err },
3424+
);
3425+
}
3426+
if (walk.truncated) {
3427+
throw new Error(
3428+
`[approvals] ${scope} could not be read to completion: the read by id could not continue past a page `
3429+
+ '(a row without an id, or a page that repeated the cursor). Routing to a shortened slate would leave '
3430+
+ 'holders unasked, so the expansion refuses instead.',
3431+
);
3432+
}
3433+
return Array.from(users);
33683434
}
33693435

33703436
/**

‎packages/plugins/plugin-sharing/src/team-graph.ts‎

Lines changed: 64 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import type { ITeamGraphService } from '@objectstack/spec/contracts';
4+
import { isMissingTableError, keysetWalk } from '@objectstack/types';
45
import type { SharingEngine } from './sharing-service.js';
56

67
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;
@@ -128,6 +129,66 @@ function roleHolderPredicate(roleName: string, org: string | null | undefined):
128129
return filter;
129130
}
130131

132+
/**
133+
* [#29362] Rows per page of the role-holder read — the bound the read always
134+
* carried, so a role held by fewer people issues the one read it always did.
135+
*/
136+
const ROLE_HOLDER_PAGE_ROWS = 10000;
137+
138+
/**
139+
* [#29362] Every holder of `roleName` (in `org`, when given), read to
140+
* completion — or a refusal, never a shortened or an invented empty set.
141+
*
142+
* Pages of {@link ROLE_HOLDER_PAGE_ROWS} through the platform's one keyset
143+
* walk (`keysetWalk`, `@objectstack/types`): ordered by `id`, each page
144+
* resuming after the last id the one before it returned, so a role held past
145+
* the bound is read whole rather than cut at an arbitrary 10,000 rows.
146+
*
147+
* Loud, never short. The set feeds sharing GRANTS, and the reconcilers diff the
148+
* grants a rule already holds against it — an answer missing a holder revokes
149+
* that holder's access, and an invented `[]` revokes everyone's. So:
150+
*
151+
* - a read that fails throws, carrying the driver's error as `cause`;
152+
* - a walk that cannot vouch for completion (a row without an `id` to resume
153+
* after, a page the driver returned without honouring the cursor) throws;
154+
* - a table that does not exist is the one failure that IS an answer — a
155+
* stack that never materialises `sys_member` has no role holders — and
156+
* answers `[]` as it always did, judged by the shared missing-table
157+
* predicate rather than by swallowing every error.
158+
*/
159+
async function readRoleHoldersToCompletion(
160+
engine: SharingEngine,
161+
roleName: string,
162+
org: string | null | undefined,
163+
): Promise<string[]> {
164+
const refusal = (reason: string, cause?: unknown) => new Error(
165+
`[sharing] the holders of role '${roleName}'${org ? ` in organization '${org}'` : ''} could not be read: `
166+
+ `${reason}. A shortened or empty holder set would withhold or revoke the grants it confers, so the `
167+
+ 'expansion refuses instead.',
168+
cause === undefined ? undefined : { cause },
169+
);
170+
const users = new Set<string>();
171+
const walk = keysetWalk<Record<string, unknown>>(
172+
(page) => engine.find('sys_member', { ...page, fields: ['id', 'user_id'], context: SYSTEM_CTX }),
173+
{ where: roleHolderPredicate(roleName, org), pageSize: ROLE_HOLDER_PAGE_ROWS },
174+
);
175+
try {
176+
for await (const page of walk.pages()) {
177+
for (const row of page) {
178+
const uid = String(row?.user_id ?? '');
179+
if (uid) users.add(uid);
180+
}
181+
}
182+
} catch (err) {
183+
if (isMissingTableError(err, 'sys_member')) return [];
184+
throw refusal(err instanceof Error ? err.message : String(err), err);
185+
}
186+
if (walk.truncated) {
187+
throw refusal('the read by id could not continue past a page (a row without an id, or a page that repeated the cursor)');
188+
}
189+
return Array.from(users);
190+
}
191+
131192
/**
132193
* Is `userId` a member of `teamId`? The user-scoped twin of
133194
* {@link TeamGraphService.expandUsers}: the same table and the same predicate,
@@ -228,18 +289,9 @@ export class TeamGraphService implements ITeamGraphService {
228289
const cached = this.cache.expandRole!.get(key);
229290
if (cached) return cached;
230291
const org = organizationId ?? this.organizationId;
231-
let rows: any[] = [];
232-
try {
233-
rows = await this.engine.find('sys_member', {
234-
filter: roleHolderPredicate(roleName, org),
235-
fields: ['user_id'],
236-
limit: 10000,
237-
context: SYSTEM_CTX,
238-
});
239-
} catch {
240-
rows = [];
241-
}
242-
const users = Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
292+
// [#29362] Read to completion, and a failed read throws — so nothing is
293+
// cached for it, and the next caller reads again.
294+
const users = await readRoleHoldersToCompletion(this.engine, roleName, org);
243295
this.cache.expandRole!.set(key, users);
244296
return users;
245297
}

0 commit comments

Comments
 (0)