Skip to content

Commit 97eb8f9

Browse files
committed
fix(plugins): an unregistered sys_member still answers no holders; changeset
The engine refuses an unregistered object with OBJECT_NOT_FOUND before any driver is asked; that is the same absence as a missing table. Error causes are attached without the ES2022 constructor option. position-graph.test's fake sys_member rows carry their id, as stored rows do. Claude-Session: https://claude.ai/code/session_01ADHkmS2E1xdkLMJPnabYgC Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2737ac6 commit 97eb8f9

6 files changed

Lines changed: 102 additions & 27 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/plugin-sharing': patch
3+
'@objectstack/plugin-approvals': patch
4+
---
5+
6+
fix(plugins)!: a role or membership tier held by more than 10,000 members reaches every holder in sharing and approvals, and a membership read that fails is refused loudly instead of answered with an empty set
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export, type or metadata changes: two expansions read a list they already read, to completion. No author has anything to rewrite; the one new refusal is a membership read that already failed, which used to answer an empty list. -->
12+
13+
**BREAKING** only where a `sys_member` read fails: the role expansion in sharing and the membership-tier expansion in approvals used to answer an empty list then, and now refuse.
14+
15+
Both expansions read `sys_member` once with a 10,000-row bound and took that read as the whole holder list. They also turned any read error into `[]`.
16+
17+
- **Every holder, nobody else.** `TeamGraphService.expandRoleUsers` (plugin-sharing: the `sys_member.role` limb of every `position` sharing recipient, and `expandPrincipal('role')`) and the approvals membership-tier expansion (an `org_membership_level` approver, and the second limb of every `position` approver) now read `sys_member` in pages of 10,000 ordered by id until the holders are exhausted. Past 10,000 holders, a sharing rule used to grant nothing to the holders past the 10,000th row, and an approval used to route without them. Both now reach every holder.
18+
- **Smaller roles are unchanged.** A role or tier held by fewer than 10,000 members issues one read, as before, and answers the same set.
19+
- **Loud, never short or empty.** A read that fails, or a page the driver returned without honouring the id cursor, now throws instead of answering `[]`.
20+
- Sharing: 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 as they were. Before, the retired-recipient revoke compared a rule's materialised grants against that empty answer and revoked every one of them.
21+
- Approvals: the approver slot falls back to its literal (`position:NAME`, which whoever holds the position can still act on, or `org_membership_level:NAME`), and the warning now says the directory read failed and carries its `error`. Before, a `position` approver routed to its assignment-table holders alone, which looked like a complete slate, and an `org_membership_level` approver logged "expanded to nobody".
22+
- **A missing table is still no holders.** A stack that never creates `sys_member` keeps answering `[]`, judged by the shared missing-table predicate rather than by swallowing every error.
23+
24+
**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.

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

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,23 @@ const MEMBER_SCREEN_READ_LIMIT = 50000;
11261126
*/
11271127
const MEMBER_TIER_PAGE_ROWS = 10000;
11281128

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+
}
1145+
11291146
/**
11301147
* Approver types resolved by QUERYING a graph rather than by taking `value`
11311148
* literally (#3807). Each can legitimately come back empty — an unstaffed
@@ -3393,10 +3410,10 @@ export class ApprovalService implements IApprovalService {
33933410
* to its literal and says the read failed. Answering `[]` instead routed a
33943411
* `position` approver to its assignment holders alone — a shrunk slate that
33953412
* 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.
3413+
* nobody", indistinguishable from a tier no one holds. A membership object
3414+
* that does not exist is the one failure that IS an answer (a stack that never
3415+
* materialises `sys_member` has no tier holders) and keeps answering `[]`;
3416+
* see {@link membershipObjectAbsent}.
34003417
*/
34013418
private async expandMembershipTierUsers(tier: string, organizationId?: string | null): Promise<string[]> {
34023419
if (!tier) return [];
@@ -3416,12 +3433,11 @@ export class ApprovalService implements IApprovalService {
34163433
}
34173434
}
34183435
} catch (err) {
3419-
if (isMissingTableError(err, 'sys_member')) return [];
3420-
throw new Error(
3436+
if (membershipObjectAbsent(err)) return [];
3437+
throw Object.assign(new Error(
34213438
`[approvals] ${scope} could not be read: ${err instanceof Error ? err.message : String(err)}. `
34223439
+ 'Routing to a shortened slate would leave holders unasked, so the expansion refuses instead.',
3423-
{ cause: err },
3424-
);
3440+
), { cause: err });
34253441
}
34263442
if (walk.truncated) {
34273443
throw new Error(

‎packages/plugins/plugin-approvals/src/member-tier-holders-complete.integration.test.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ afterEach(async () => {
6767
* rows the predicate must keep out. Membership ids are scrambled against the
6868
* user ids, so an unordered first read is not the lowest ids.
6969
*/
70-
async function boot(n: number): Promise<Rig> {
70+
async function boot(n: number, opts: { registerMember?: boolean } = {}): Promise<Rig> {
7171
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
7272
const engine = new ObjectQL();
7373
engine.registerDriver(driver as never, true);
@@ -78,7 +78,7 @@ async function boot(n: number): Promise<Rig> {
7878
version: '1.0.0',
7979
type: 'plugin',
8080
scope: 'system',
81-
objects: [SysOrganization, SysMember],
81+
objects: opts.registerMember === false ? [SysOrganization] : [SysOrganization, SysMember],
8282
} as never);
8383
await engine.syncSchemas();
8484
engines.push(engine);
@@ -92,8 +92,10 @@ async function boot(n: number): Promise<Rig> {
9292
}));
9393
rows.push({ id: 'mem_elsewhere', user_id: 'usr_elsewhere', organization_id: ELSEWHERE, role: TIER });
9494
rows.push({ id: 'mem_other_tier', user_id: 'usr_other_tier', organization_id: ORG, role: 'member' });
95-
const memberDriver = e.getDriverForObject('sys_member');
96-
for (let i = 0; i < rows.length; i += 250) await memberDriver.bulkCreate('sys_member', rows.slice(i, i + 250));
95+
if (opts.registerMember !== false) {
96+
const memberDriver = e.getDriverForObject('sys_member');
97+
for (let i = 0; i < rows.length; i += 250) await memberDriver.bulkCreate('sys_member', rows.slice(i, i + 250));
98+
}
9799

98100
let reads = 0;
99101
(driver as any).knex.on('query', (q: { sql: string }) => {
@@ -158,6 +160,14 @@ describe('[#29362] approvals membership-tier expansion reads every holder (drive
158160
await expect(position(rig, TIER)).rejects.toThrow(/could not be read/);
159161
});
160162

163+
it('a composition that never registers sys_member holds no tier: [] as before, and the position keeps its literal', async () => {
164+
const rig = await boot(0, { registerMember: false });
165+
166+
expect(await tier(rig, TIER)).toEqual([]);
167+
expect(await resolveSpec(rig, { type: 'position', value: TIER })).toEqual([`position:${TIER}`]);
168+
expect(rig.warn.mock.calls.some(([, meta]) => typeof meta?.error === 'string')).toBe(false);
169+
});
170+
161171
it('⛔ what the caller sees: the slot falls back to its literal, and the warning names the failed read', async () => {
162172
const rig = await boot(3);
163173
failMemberReads(rig, new Error('SQLITE_IOERR: disk I/O error'));

‎packages/plugins/plugin-sharing/src/position-graph.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,11 @@ const ASSIGNMENTS = [
3232
{ position: 'sales_rep', user_id: 'u_rep1' },
3333
{ position: 'sales_rep', user_id: 'u_rep2' },
3434
];
35+
// Every `sys_member` row carries its `id`, as a stored one does: the role read
36+
// pages by it (#29362) and refuses a row it cannot resume after.
3537
const MEMBERS = [
36-
{ role: 'sales_rep', user_id: 'u_legacy_rep' }, // better-auth transition source
37-
{ role: 'exec', user_id: 'u_exec' },
38+
{ id: 'm_legacy_rep', role: 'sales_rep', user_id: 'u_legacy_rep' }, // better-auth transition source
39+
{ id: 'm_exec', role: 'exec', user_id: 'u_exec' },
3840
];
3941

4042
describe('PositionGraphService (ADR-0090 D3 — flat expansion)', () => {
@@ -111,8 +113,8 @@ describe('PositionGraphService.holdsPosition — the user-scoped twin of the exp
111113
{ position: 'mgr', user_id: 'u_a', organization_id: 'org_a' },
112114
];
113115
const MEMBER = [
114-
{ role: 'rep', user_id: 'u_role_a', organization_id: 'org_a' },
115-
{ role: 'rep', user_id: 'u_role_b', organization_id: 'org_b' },
116+
{ id: 'm_role_a', role: 'rep', user_id: 'u_role_a', organization_id: 'org_a' },
117+
{ id: 'm_role_b', role: 'rep', user_id: 'u_role_b', organization_id: 'org_b' },
116118
];
117119
/** Honours every predicate key both reads send: position / role, organization_id, user_id. */
118120
const engine = {

‎packages/plugins/plugin-sharing/src/team-graph-role-holders-complete.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@
2222
* (`id > cursor`, ordered by `id`): a hand-written double that ignores the
2323
* cursor or the order cannot tell a completed read from a repeated page.
2424
*
25-
* A table that does not exist is still no holders: a stack that never
26-
* materialises `sys_member` has no role holders to lose, and the driver's
27-
* missing-table refusal is the one failure that says so.
25+
* A membership object that does not exist is still no holders: a stack that
26+
* never materialises `sys_member` has no role holders to lose. The driver's
27+
* missing-table refusal and the engine's `OBJECT_NOT_FOUND` for `sys_member`
28+
* are the two failures that say so; every other failure is loud.
2829
*/
2930

3031
import { describe, it, expect, afterEach, vi } from 'vitest';
@@ -164,6 +165,12 @@ describe('[#29362] TeamGraphService.expandRoleUsers reads every holder (driver-s
164165
await expect(positions.expandPositionUsers(ROLE, ORG)).rejects.toThrow(/could not be read/);
165166
});
166167

168+
it('a composition that never registers sys_member holds no role: [] as before', async () => {
169+
const rig = await boot(0, { registerMember: false });
170+
171+
expect(await graph(rig.engine).expandRoleUsers(ROLE, ORG)).toEqual([]);
172+
});
173+
167174
it('a stack whose sys_member table was never created holds no role: [] as before', async () => {
168175
const rig = await boot(0);
169176
await (rig.driver as any).knex.schema.dropTable('sys_member');

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

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -151,22 +151,38 @@ const ROLE_HOLDER_PAGE_ROWS = 10000;
151151
* - a read that fails throws, carrying the driver's error as `cause`;
152152
* - a walk that cannot vouch for completion (a row without an `id` to resume
153153
* 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.
154+
* - a membership object that does not exist is the one failure that IS an
155+
* answer — a stack that never materialises `sys_member` has no role
156+
* holders — and answers `[]` as it always did; see
157+
* {@link membershipObjectAbsent}.
158158
*/
159+
/**
160+
* [#29362] Did the role read fail because this stack has no `sys_member` at
161+
* all — the one failure whose empty answer is the truth? Two spellings of the
162+
* same absence, each attributed to `sys_member` so a failure about another
163+
* object is not evidence about this one: the driver's missing-table refusal
164+
* (the shared `isMissingTableError`, the table registered but never created),
165+
* and the engine's `OBJECT_NOT_FOUND` (a composition that never registers the
166+
* object, refused before any driver is asked — the reading
167+
* `sys-metadata-repository.ts` gives its own history object). Anything else
168+
* is an outage and stays loud.
169+
*/
170+
function membershipObjectAbsent(err: unknown): boolean {
171+
if (isMissingTableError(err, 'sys_member')) return true;
172+
const refused = err as { code?: unknown; object?: unknown } | null | undefined;
173+
return refused?.code === 'OBJECT_NOT_FOUND' && refused.object === 'sys_member';
174+
}
175+
159176
async function readRoleHoldersToCompletion(
160177
engine: SharingEngine,
161178
roleName: string,
162179
org: string | null | undefined,
163180
): Promise<string[]> {
164-
const refusal = (reason: string, cause?: unknown) => new Error(
181+
const refusal = (reason: string, cause?: unknown) => Object.assign(new Error(
165182
`[sharing] the holders of role '${roleName}'${org ? ` in organization '${org}'` : ''} could not be read: `
166183
+ `${reason}. A shortened or empty holder set would withhold or revoke the grants it confers, so the `
167184
+ 'expansion refuses instead.',
168-
cause === undefined ? undefined : { cause },
169-
);
185+
), cause === undefined ? {} : { cause });
170186
const users = new Set<string>();
171187
const walk = keysetWalk<Record<string, unknown>>(
172188
(page) => engine.find('sys_member', { ...page, fields: ['id', 'user_id'], context: SYSTEM_CTX }),
@@ -180,7 +196,7 @@ async function readRoleHoldersToCompletion(
180196
}
181197
}
182198
} catch (err) {
183-
if (isMissingTableError(err, 'sys_member')) return [];
199+
if (membershipObjectAbsent(err)) return [];
184200
throw refusal(err instanceof Error ? err.message : String(err), err);
185201
}
186202
if (walk.truncated) {

0 commit comments

Comments
 (0)