Skip to content

Commit ec9e8bb

Browse files
committed
fix(plugins)!: team and position recipients are read past 10,000 rows, and a failed holder read refuses instead of answering nobody
Sharing: TeamGraphService.expandUsers (sys_team_member) and the assignment limb of PositionGraphService.expandPositionUsers (sys_user_position) read to completion through keysetWalk; the user-scoped checks teamHasMember, holdsRole and holdsPosition refuse a failed read instead of answering false. The queue service keeps its declared posture (a failed member read contributes nobody) on its holder check too. Approvals: the team approver and the position assignment limb read to completion through one readHoldersToCompletion beside the tier read. Absence is judged once, by the new isObjectAbsentError in @objectstack/types. Claude-Session: https://claude.ai/code/session_01ADHkmT6XzrVS2iPpNyXNYL Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5ee0c46 commit ec9e8bb

8 files changed

Lines changed: 336 additions & 180 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/types': patch
3+
'@objectstack/plugin-sharing': patch
4+
'@objectstack/plugin-approvals': patch
5+
---
6+
7+
fix(plugins)!: team and position recipients reach every holder past 10,000 rows in sharing and approvals, and a team, position or role holder read that fails is refused loudly instead of answered with nobody
8+
9+
Clause-②: yes (narrowing)
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped and no metadata changes: the team and position expansions read lists they already read, to completion, and the holder checks refuse a read that already failed. The one new export (isObjectAbsentError in @objectstack/types) is an addition. No author has anything to rewrite. -->
13+
14+
**BREAKING** only where a `sys_team_member`, `sys_user_position` or `sys_member` read fails: the team and position expansions and the user-scoped holder checks used to answer nobody (an empty list, or `false`) then, and now refuse.
15+
16+
This completes the family the role and membership-tier fix started. The team and position reads still read once with a 10,000-row bound and turned any read error into nobody.
17+
18+
- **Every holder, nobody else.** In plugin-sharing, `TeamGraphService.expandUsers` (`sys_team_member`, every `team` sharing recipient) and the assignment limb of `PositionGraphService.expandPositionUsers` (`sys_user_position`, every `position` sharing recipient) now read in pages of 10,000 ordered by id until the holders are exhausted. In plugin-approvals, the `team` approver and the assignment limb of the `position` approver (and every caller of the position expansion: escalation targets, reassign checks, `resolveAs` expressions) do the same. Past 10,000 holders, the holders past the 10,000th row used to get no grant and no approval slot. They now do.
19+
- **Smaller groups are unchanged.** A team or position held by fewer than 10,000 people issues one read, as before, and answers the same set.
20+
- **Loud, never short or empty.** A read that fails, or a page the driver returned without honouring the id cursor, now throws.
21+
- Sharing, whole-rule passes: the expansion rejects, so that rule's reconcile or revoke pass fails, its callers log their existing per-rule warning, and the grants it already holds stay. Before, a failed team read answered `[]`, and a failed assignment read answered the `sys_member.role` holders alone, so the retired-recipient revoke took grants away from people who still held the recipient.
22+
- Sharing, per-user recompute (a write to `sys_team_member` or `sys_user_position`): the holder checks `teamHasMember`, `holdsRole` and `PositionGraphService.holdsPosition` now refuse a failed read instead of answering `false`. The recompute logs `recipient membership re-evaluation failed` for that rule and user, and the user's grants stay. Before, an outage revoked that user's grants.
23+
- Approvals: the approver slot falls back to its literal (`team:ID` or `position:NAME`) and logs `could not be expanded — a directory or read-filter lookup failed` with its `error`. Before, a failed team read logged "expanded to nobody", and a failed assignment read routed a `position` approver to its membership-tier holders alone, which looked like a complete slate.
24+
- **Ownership queues keep their declared posture.** A queue member specification whose team or position read fails still contributes nobody, on the expansion and on the queue's holder check alike, and now logs it once. Whether a queue should refuse too is left to a ruling.
25+
- **A missing object is still no holders.** A stack that never registers, or never creates, `sys_team_member`, `sys_user_position` or `sys_member` keeps answering no holders through it. That is judged by the new `isObjectAbsentError(error, readObject)` in `@objectstack/types`: the shared missing-table predicate for that object, or the engine's `OBJECT_NOT_FOUND` naming that object. Any other error, including an absence of a different object, stays loud.
26+
27+
**The remedy.** None is needed. A refusal means the membership table could not be read: fix that read, and the next expansion succeeds. A failed read is never cached.

‎content/docs/automation/approvals.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -455,8 +455,9 @@ What an entry that resolves to nobody leaves on the slate depends on its kind:
455455
decide it (the admin-override callout under
456456
[Acting on requests in the console](#acting-on-requests-in-the-console)).
457457
Beside entries that do resolve, a literal is a slot like any other, so a
458-
`behavior` that needs every slot (`unanimous`) waits on it too. A `position` or
459-
`org_membership_level` entry whose `sys_member` read failed keeps its literal
458+
`behavior` that needs every slot (`unanimous`) waits on it too. A `team`,
459+
`position` or `org_membership_level` entry whose holder read failed
460+
(`sys_team_member`, `sys_user_position` or `sys_member`) keeps its literal
460461
the same way. It logs `could not be expanded — a directory or read-filter
461462
lookup failed` with the `error`, instead of `expanded to nobody`, and never
462463
routes to the holders that happened to read.

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

Lines changed: 51 additions & 50 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 { isMissingTableError, keysetWalk, strandedDecisionFailure } from '@objectstack/types';
24+
import { isObjectAbsentError, 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
@@ -1119,29 +1119,13 @@ const OOO_MAX_CHAIN = 8;
11191119
const MEMBER_SCREEN_READ_LIMIT = 50000;
11201120

11211121
/**
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.
1122+
* [#29362, #29503] Rows per page of the directory holder reads
1123+
* ({@link ApprovalService.readHoldersToCompletion}: the membership tier, the
1124+
* position assignments, the team members) — the bound each read always
1125+
* carried, so a group held by fewer people issues the one read it always did,
1126+
* and one held by more is read in further pages rather than cut.
11261127
*/
1127-
const MEMBER_TIER_PAGE_ROWS = 10000;
1128-
1129-
/**
1130-
* [#29362] Did a `sys_member` read fail because this stack has no membership
1131-
* object at all — the one failure whose empty answer is the truth? Two
1132-
* spellings of the same absence, each attributed to `sys_member` so a failure
1133-
* about another object is not evidence about this one: the driver's
1134-
* missing-table refusal (the shared `isMissingTableError`, the table
1135-
* registered but never created), and the engine's `OBJECT_NOT_FOUND` (a
1136-
* composition that never registers the object, refused before any driver is
1137-
* asked — the reading `sys-metadata-repository.ts` gives its own history
1138-
* object). Anything else is an outage and stays loud.
1139-
*/
1140-
function membershipObjectAbsent(err: unknown): boolean {
1141-
if (isMissingTableError(err, 'sys_member')) return true;
1142-
const refused = err as { code?: unknown; object?: unknown } | null | undefined;
1143-
return refused?.code === 'OBJECT_NOT_FOUND' && refused.object === 'sys_member';
1144-
}
1128+
const HOLDER_PAGE_ROWS = 10000;
11451129

11461130
/**
11471131
* Approver types resolved by QUERYING a graph rather than by taking `value`
@@ -2917,16 +2901,12 @@ export class ApprovalService implements IApprovalService {
29172901
private async expandTeamUsers(teamId: string, organizationId?: string | null): Promise<string[]> {
29182902
if (!teamId) return [];
29192903
if (await this.teamIsProvablyOutsideOrg(teamId, organizationId)) return [];
2920-
let rows: any[] = [];
2921-
try {
2922-
rows = await this.engine.find('sys_team_member', {
2923-
where: { team_id: teamId },
2924-
fields: ['user_id'],
2925-
limit: 10000,
2926-
context: SYSTEM_CTX,
2927-
} as any);
2928-
} catch { rows = []; }
2929-
const users = Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
2904+
// [#29503] Every member, read to completion — or a refusal that
2905+
// {@link resolveApproverSpec}'s directory catch reports as a failed read,
2906+
// never "expanded to nobody". A stack with no `sys_team_member` has none.
2907+
const users = await this.readHoldersToCompletion(
2908+
'sys_team_member', { team_id: teamId }, `the members of team '${teamId}'`,
2909+
);
29302910
// #10547: the TEAM proved its tenancy above; its members have not proved
29312911
// theirs, and `sys_team_member` holds no fact that could. One read.
29322912
return await this.dropMembersProvablyOutsideOrg(teamId, users, organizationId);
@@ -3303,18 +3283,16 @@ export class ApprovalService implements IApprovalService {
33033283
*/
33043284
private async expandPositionUsers(positionName: string, organizationId?: string | null): Promise<string[]> {
33053285
if (!positionName) return [];
3306-
const users = new Set<string>();
3307-
const filter: any = { position: positionName };
3286+
const filter: Record<string, unknown> = { position: positionName };
33083287
if (organizationId) filter.organization_id = organizationId;
3309-
try {
3310-
const rows = await this.engine.find('sys_user_position', {
3311-
filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX,
3312-
} as any);
3313-
for (const r of (rows ?? []) as any[]) {
3314-
const uid = String(r.user_id ?? '');
3315-
if (uid) users.add(uid);
3316-
}
3317-
} catch { /* table may not exist on minimal stacks — union source below still applies */ }
3288+
// [#29503] Every assignment, read to completion — or a refusal, never the
3289+
// tier limb below alone (a shrunk slate that looks complete). A stack with
3290+
// no `sys_user_position` has no assignment holders; the union source below
3291+
// still applies.
3292+
const users = new Set<string>(await this.readHoldersToCompletion(
3293+
'sys_user_position', filter,
3294+
`the assignments of position '${positionName}'${organizationId ? ` in organization '${organizationId}'` : ''}`,
3295+
));
33183296
// ADR-0057 D4 transition source: pre-migration stacks still carry the
33193297
// position name in better-auth's `sys_member.role` column, so the same
33203298
// lookup serves a position name here and a membership tier for
@@ -3402,7 +3380,7 @@ export class ApprovalService implements IApprovalService {
34023380
* change here changes position routing too.
34033381
*
34043382
* [#29362] Read to COMPLETION, or refused — never a shortened or an invented
3405-
* empty slate. Pages of {@link MEMBER_TIER_PAGE_ROWS} through the platform's
3383+
* empty slate. Pages of {@link HOLDER_PAGE_ROWS} through the platform's
34063384
* one keyset walk (`keysetWalk`, `@objectstack/types`), ordered by `id`, so a
34073385
* tier held past the bound routes to every holder rather than the first
34083386
* 10,000 rows. A read that fails, or a walk that cannot vouch for completion
@@ -3414,17 +3392,40 @@ export class ApprovalService implements IApprovalService {
34143392
* nobody", indistinguishable from a tier no one holds. A membership object
34153393
* that does not exist is the one failure that IS an answer (a stack that never
34163394
* materialises `sys_member` has no tier holders) and keeps answering `[]`;
3417-
* see {@link membershipObjectAbsent}.
3395+
* see {@link readHoldersToCompletion}.
34183396
*/
34193397
private async expandMembershipTierUsers(tier: string, organizationId?: string | null): Promise<string[]> {
34203398
if (!tier) return [];
34213399
const filter: Record<string, unknown> = { role: tier };
34223400
if (organizationId) filter.organization_id = organizationId;
3423-
const scope = `the holders of membership tier '${tier}'${organizationId ? ` in organization '${organizationId}'` : ''}`;
3401+
return this.readHoldersToCompletion(
3402+
'sys_member', filter,
3403+
`the holders of membership tier '${tier}'${organizationId ? ` in organization '${organizationId}'` : ''}`,
3404+
);
3405+
}
3406+
3407+
/**
3408+
* [#29362, #29503] The `user_id`s of every `object` row matching `where`,
3409+
* read to COMPLETION — or a refusal, never a shortened or an invented empty
3410+
* slate. The one read behind the membership tier, the position assignments
3411+
* and the team members.
3412+
*
3413+
* Pages of {@link HOLDER_PAGE_ROWS} through the platform's one keyset walk
3414+
* (`keysetWalk`, `@objectstack/types`), ordered by `id`, so a group held past
3415+
* the bound routes to every holder rather than the first 10,000 rows. A read
3416+
* that fails, or a walk that cannot vouch for completion (a row without an
3417+
* `id`, a page that did not honour the cursor), THROWS:
3418+
* {@link resolveApproverSpec}'s directory catch then lets the slot fall back
3419+
* to its literal and says the read failed. An object that does not exist on
3420+
* this stack is the one failure that IS an answer (no holders through it) and
3421+
* answers `[]` — `isObjectAbsentError` (`@objectstack/types`) decides that,
3422+
* attributed to `object`, so an absence of another object is still loud.
3423+
*/
3424+
private async readHoldersToCompletion(object: string, where: Record<string, unknown>, scope: string): Promise<string[]> {
34243425
const users = new Set<string>();
34253426
const walk = keysetWalk<Record<string, unknown>>(
3426-
(page) => this.engine.find('sys_member', { ...page, fields: ['id', 'user_id'], context: SYSTEM_CTX }),
3427-
{ where: filter, pageSize: MEMBER_TIER_PAGE_ROWS },
3427+
(page) => this.engine.find(object, { ...page, fields: ['id', 'user_id'], context: SYSTEM_CTX }),
3428+
{ where, pageSize: HOLDER_PAGE_ROWS },
34283429
);
34293430
try {
34303431
for await (const page of walk.pages()) {
@@ -3434,7 +3435,7 @@ export class ApprovalService implements IApprovalService {
34343435
}
34353436
}
34363437
} catch (err) {
3437-
if (membershipObjectAbsent(err)) return [];
3438+
if (isObjectAbsentError(err, object)) return [];
34383439
throw Object.assign(new Error(
34393440
`[approvals] ${scope} could not be read: ${err instanceof Error ? err.message : String(err)}. `
34403441
+ 'Routing to a shortened slate would leave holders unasked, so the expansion refuses instead.',

‎packages/plugins/plugin-sharing/src/ownership-queue-service.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,12 +365,12 @@ export class OwnershipQueueService implements IOwnershipQueueService {
365365
if (spec.value === userId) return true;
366366
break;
367367
case 'team':
368-
if (await teamHasMember(engine, spec.value, userId)) return true;
368+
if (await this.holderCheck(spec, () => teamHasMember(engine, spec.value, userId))) return true;
369369
break;
370370
case 'position': {
371371
if (!(await this.positionActive(spec.value, pass))) break;
372372
const positions = new PositionGraphService({ engine, organizationId });
373-
if (await positions.holdsPosition(userId, spec.value, organizationId ?? undefined)) return true;
373+
if (await this.holderCheck(spec, () => positions.holdsPosition(userId, spec.value, organizationId ?? undefined))) return true;
374374
break;
375375
}
376376
default:
@@ -380,6 +380,28 @@ export class OwnershipQueueService implements IOwnershipQueueService {
380380
return false;
381381
}
382382

383+
/**
384+
* [#29503] A team or position holder check, answered in the posture this
385+
* service declares for a failed member-table read (module header): that
386+
* specification contributes nobody, logged once — the same answer
387+
* {@link expandSpec} gives the expansion, so the two twins cannot disagree.
388+
*
389+
* The checks themselves (`teamHasMember`, `PositionGraphService.holdsPosition`)
390+
* now refuse a failed read instead of answering `false`; this keeps the
391+
* queue's consumers where they were. Whether a queue should refuse too is not
392+
* decided by ADR-0142 and is left to a ruling rather than narrowed here.
393+
*/
394+
private async holderCheck(spec: QueueMemberSpec, check: () => Promise<boolean>): Promise<boolean> {
395+
try {
396+
return await check();
397+
} catch (err: any) {
398+
this.warnOnce(`holds::${spec.type}::${spec.value}`, '[queue] a member specification could not be read for a holder check — it contributes nobody until it can', {
399+
type: spec.type, value: spec.value, error: err?.message,
400+
});
401+
return false;
402+
}
403+
}
404+
383405
// ── Reads ──────────────────────────────────────────────────────────────────
384406

385407
private declaredItems(): DeclaredQueueItem[] {

0 commit comments

Comments
 (0)