Skip to content

Commit b15e854

Browse files
committed
test(plugins): pin role and membership-tier holder reads past the bound and on a failed read (red)
Claude-Session: https://claude.ai/code/session_01ADHkmS2E1xdkLMJPnabYgC Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7b1ae33 commit b15e854

2 files changed

Lines changed: 347 additions & 0 deletions

File tree

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29362] The membership-tier expansion (`sys_member.role`) answers EVERY
5+
* holder of a tier, or refuses — never a shortened or an invented empty set.
6+
*
7+
* `expandMembershipTierUsers` is the whole of an `org_membership_level`
8+
* approver and the second limb of every `position` approver (ADR-0057 D4
9+
* transition source). It used to read `sys_member` once with a 10,000-row
10+
* bound and take that read as the holder list, and it turned a read that threw
11+
* into `[]`:
12+
*
13+
* - past 10,000 holders the request routed to a slate missing the holders
14+
* past the 10,000th row, with no signal;
15+
* - a read that failed routed a `position` approver to its assignment-table
16+
* holders ALONE — a shrunk slate that looks exactly like a complete one —
17+
* and an `org_membership_level` approver logged "expanded to nobody",
18+
* indistinguishable from a tier nobody holds.
19+
*
20+
* What a caller sees now: a failed read throws out of the expansion, the
21+
* approver-spec resolver's directory catch takes it, and the slot falls back
22+
* to its literal (`position:<p>`, acted on by whoever holds the position at
23+
* decision time; `org_membership_level:<t>`, decided by the override) with a
24+
* warning that names the failed read and carries its `error` — never a slate
25+
* cut down to the part that happened to read.
26+
*
27+
* Measured on a REAL engine (ObjectQL + SqlDriver over in-memory SQLite)
28+
* carrying the shipped `SysMember`, because the completion is a keyset read
29+
* (`id > cursor`, ordered by `id`) that a hand-written double cannot vouch for.
30+
*/
31+
32+
import { describe, it, expect, afterEach, vi } from 'vitest';
33+
import { ObjectQL } from '@objectstack/objectql';
34+
import { SqlDriver } from '@objectstack/driver-sql';
35+
import { SysMember, SysOrganization } from '@objectstack/platform-objects/identity';
36+
import { ApprovalService } from './approval-service.js';
37+
38+
const ORG = 'org_large';
39+
const ELSEWHERE = 'org_elsewhere';
40+
const TIER = 'admin';
41+
/** The bound the tier read is paged at. */
42+
const PAGE = 10000;
43+
44+
const pad = (n: number) => String(n).padStart(6, '0');
45+
46+
interface Rig {
47+
engine: ObjectQL;
48+
svc: ApprovalService;
49+
warn: ReturnType<typeof vi.fn>;
50+
/** Every holder of {@link TIER} in {@link ORG}, sorted. */
51+
holders: string[];
52+
/** The tier reads the driver ran (`… from sys_member where … role = ? …`). */
53+
tierReads: () => number;
54+
}
55+
56+
const engines: ObjectQL[] = [];
57+
afterEach(async () => {
58+
vi.restoreAllMocks();
59+
while (engines.length) {
60+
try { await engines.pop()?.destroy(); } catch { /* noop */ }
61+
}
62+
});
63+
64+
/**
65+
* `n` holders of {@link TIER} in {@link ORG}, plus a holder of the same tier in
66+
* another organization and a member of {@link ORG} in another tier — the two
67+
* rows the predicate must keep out. Membership ids are scrambled against the
68+
* user ids, so an unordered first read is not the lowest ids.
69+
*/
70+
async function boot(n: number): Promise<Rig> {
71+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
72+
const engine = new ObjectQL();
73+
engine.registerDriver(driver as never, true);
74+
await engine.init();
75+
engine.registerApp({
76+
id: 'com.objectstack.qa.member-tier-holders-complete',
77+
name: 'member tier holders complete',
78+
version: '1.0.0',
79+
type: 'plugin',
80+
scope: 'system',
81+
objects: [SysOrganization, SysMember],
82+
} as never);
83+
await engine.syncSchemas();
84+
engines.push(engine);
85+
86+
const e = engine as any;
87+
await e.insert('sys_organization', { id: ORG, name: ORG, slug: 'large' }, { context: { isSystem: true } });
88+
await e.insert('sys_organization', { id: ELSEWHERE, name: ELSEWHERE, slug: 'elsewhere' }, { context: { isSystem: true } });
89+
const holders = Array.from({ length: n }, (_, i) => `usr_${pad(i)}`);
90+
const rows = holders.map((user_id, i) => ({
91+
id: `mem_${pad((i * 7919) % 1000003)}`, user_id, organization_id: ORG, role: TIER,
92+
}));
93+
rows.push({ id: 'mem_elsewhere', user_id: 'usr_elsewhere', organization_id: ELSEWHERE, role: TIER });
94+
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));
97+
98+
let reads = 0;
99+
(driver as any).knex.on('query', (q: { sql: string }) => {
100+
if (/from [`"]sys_member[`"] where .*[`"]role[`"] = \?/.test(q.sql)) reads += 1;
101+
});
102+
const warn = vi.fn();
103+
const svc = new ApprovalService({
104+
engine: engine as any,
105+
logger: { warn, info: () => {}, error: () => {}, debug: () => {} } as any,
106+
});
107+
return { engine, svc, warn, holders: [...holders].sort(), tierReads: () => reads };
108+
}
109+
110+
/** The private expansions, as the approver-spec resolver calls them. */
111+
const tier = (rig: Rig, value: string) => (rig.svc as any).expandMembershipTierUsers(value, ORG) as Promise<string[]>;
112+
const position = (rig: Rig, value: string) => (rig.svc as any).expandPositionUsers(value, ORG) as Promise<string[]>;
113+
const resolveSpec = (rig: Rig, a: { type: string; value: string }) =>
114+
(rig.svc as any).resolveApproverSpec(a, undefined, ORG, Date.now()) as Promise<string[]>;
115+
116+
const failMemberReads = (rig: Rig, fault: Error) => {
117+
const memberDriver = (rig.engine as any).getDriverForObject('sys_member');
118+
return vi.spyOn(memberDriver, 'find').mockRejectedValue(fault);
119+
};
120+
121+
describe('[#29362] approvals membership-tier expansion reads every holder (driver-sql, shipped SysMember)', () => {
122+
it('⭐ past the 10,000-row bound: every holder is on the slate, and no one else', async () => {
123+
const rig = await boot(PAGE + 1);
124+
const users = await tier(rig, TIER);
125+
126+
expect([...users].sort()).toEqual(rig.holders);
127+
expect(users).not.toContain('usr_elsewhere');
128+
expect(users).not.toContain('usr_other_tier');
129+
expect(rig.tierReads()).toBe(2);
130+
}, 30_000);
131+
132+
it('⭐ an org_membership_level approver routes to every holder past the bound', async () => {
133+
const rig = await boot(PAGE + 1);
134+
const slate = await resolveSpec(rig, { type: 'org_membership_level', value: TIER });
135+
136+
expect([...slate].sort()).toEqual(rig.holders);
137+
}, 30_000);
138+
139+
it('control — under the bound: one read, the same slate as before', async () => {
140+
const rig = await boot(PAGE - 1);
141+
const users = await tier(rig, TIER);
142+
143+
expect([...users].sort()).toEqual(rig.holders);
144+
expect(rig.tierReads()).toBe(1);
145+
}, 30_000);
146+
147+
it('⛔ a tier read that fails refuses — it never answers an invented empty set', async () => {
148+
const rig = await boot(3);
149+
failMemberReads(rig, Object.assign(new Error('SQLITE_IOERR: disk I/O error'), { code: 'SQLITE_IOERR' }));
150+
151+
await expect(tier(rig, TIER)).rejects.toThrow(/holders of membership tier 'admin'.*could not be read/);
152+
});
153+
154+
it('⛔ a position whose tier limb fails refuses rather than route to the assignment limb alone', async () => {
155+
const rig = await boot(3);
156+
failMemberReads(rig, new Error('SQLITE_IOERR: disk I/O error'));
157+
158+
await expect(position(rig, TIER)).rejects.toThrow(/could not be read/);
159+
});
160+
161+
it('⛔ what the caller sees: the slot falls back to its literal, and the warning names the failed read', async () => {
162+
const rig = await boot(3);
163+
failMemberReads(rig, new Error('SQLITE_IOERR: disk I/O error'));
164+
165+
expect(await resolveSpec(rig, { type: 'position', value: TIER })).toEqual([`position:${TIER}`]);
166+
expect(await resolveSpec(rig, { type: 'org_membership_level', value: TIER })).toEqual([`org_membership_level:${TIER}`]);
167+
const failed = rig.warn.mock.calls.filter(([, meta]) => typeof meta?.error === 'string');
168+
expect(failed.map(([, meta]) => meta.type)).toEqual(['position', 'org_membership_level']);
169+
for (const [line, meta] of failed) {
170+
expect(line).toMatch(/could not be expanded/);
171+
expect(meta.error).toMatch(/SQLITE_IOERR/);
172+
}
173+
});
174+
});
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29362] `TeamGraphService.expandRoleUsers` answers EVERY holder of a role,
5+
* or refuses — never a shortened or an invented empty set.
6+
*
7+
* The role expansion is the `sys_member.role` limb of every position recipient
8+
* (`PositionGraphService.expandPositionUsers`, ADR-0057 D4 transition source)
9+
* and of `expandPrincipal('role')`. It used to read `sys_member` once with a
10+
* 10,000-row bound and take that read as the holder list, and it turned a read
11+
* that threw into `[]`:
12+
*
13+
* - past 10,000 holders the members past the 10,000th row were missing from
14+
* the set with no signal, so a sharing rule granted them nothing;
15+
* - a read that failed answered "nobody holds this role", and the
16+
* retired-recipient revoke (`revokeRuleGrantsForRetiredRecipients`) diffs
17+
* the grants a rule already materialised against that answer — an empty
18+
* answer revokes every one of them.
19+
*
20+
* Measured on a REAL engine (ObjectQL + SqlDriver over in-memory SQLite)
21+
* carrying the shipped `SysMember`, because the completion is a keyset read
22+
* (`id > cursor`, ordered by `id`): a hand-written double that ignores the
23+
* cursor or the order cannot tell a completed read from a repeated page.
24+
*
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.
28+
*/
29+
30+
import { describe, it, expect, afterEach, vi } from 'vitest';
31+
import { ObjectQL } from '@objectstack/objectql';
32+
import { SqlDriver } from '@objectstack/driver-sql';
33+
import { SysMember, SysOrganization } from '@objectstack/platform-objects/identity';
34+
import { TeamGraphService } from './team-graph.js';
35+
import { PositionGraphService } from './position-graph.js';
36+
37+
const ORG = 'org_large';
38+
const ELSEWHERE = 'org_elsewhere';
39+
const ROLE = 'sales_rep';
40+
/** The bound the role read is paged at. */
41+
const PAGE = 10000;
42+
43+
const pad = (n: number) => String(n).padStart(6, '0');
44+
45+
interface Rig {
46+
engine: ObjectQL;
47+
driver: SqlDriver;
48+
/** Every holder of {@link ROLE} in {@link ORG}, sorted. */
49+
holders: string[];
50+
/** The role reads the driver ran (`… from sys_member where role = ? …`). */
51+
roleReads: () => number;
52+
}
53+
54+
const engines: ObjectQL[] = [];
55+
afterEach(async () => {
56+
vi.restoreAllMocks();
57+
while (engines.length) {
58+
try { await engines.pop()?.destroy(); } catch { /* noop */ }
59+
}
60+
});
61+
62+
/**
63+
* `n` holders of {@link ROLE} in {@link ORG}, plus a holder of the same role in
64+
* another organization and a member of {@link ORG} holding another role — the
65+
* two rows the predicate must keep out. Membership ids are scrambled against
66+
* the user ids, so the 10,001st row by `sys_member.id` is not the 10,001st
67+
* user, and an unordered first read is not the lowest ids.
68+
*/
69+
async function boot(n: number, opts: { registerMember?: boolean } = {}): Promise<Rig> {
70+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
71+
const engine = new ObjectQL();
72+
engine.registerDriver(driver as never, true);
73+
await engine.init();
74+
engine.registerApp({
75+
id: 'com.objectstack.qa.team-graph-role-holders-complete',
76+
name: 'team graph role holders complete',
77+
version: '1.0.0',
78+
type: 'plugin',
79+
scope: 'system',
80+
objects: opts.registerMember === false ? [SysOrganization] : [SysOrganization, SysMember],
81+
} as never);
82+
await engine.syncSchemas();
83+
engines.push(engine);
84+
85+
const e = engine as any;
86+
await e.insert('sys_organization', { id: ORG, name: ORG, slug: 'large' }, { context: { isSystem: true } });
87+
await e.insert('sys_organization', { id: ELSEWHERE, name: ELSEWHERE, slug: 'elsewhere' }, { context: { isSystem: true } });
88+
const holders = Array.from({ length: n }, (_, i) => `usr_${pad(i)}`);
89+
if (opts.registerMember !== false) {
90+
const rows = holders.map((user_id, i) => ({
91+
id: `mem_${pad((i * 7919) % 1000003)}`, user_id, organization_id: ORG, role: ROLE,
92+
}));
93+
rows.push({ id: 'mem_elsewhere', user_id: 'usr_elsewhere', organization_id: ELSEWHERE, role: ROLE });
94+
rows.push({ id: 'mem_other_role', user_id: 'usr_other_role', organization_id: ORG, role: 'support' });
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));
97+
}
98+
99+
let reads = 0;
100+
(driver as any).knex.on('query', (q: { sql: string }) => {
101+
if (/from [`"]sys_member[`"] where .*[`"]role[`"] = \?/.test(q.sql)) reads += 1;
102+
});
103+
return { engine, driver, holders: [...holders].sort(), roleReads: () => reads };
104+
}
105+
106+
const graph = (engine: ObjectQL) => new TeamGraphService({ engine: engine as never, organizationId: ORG });
107+
108+
describe('[#29362] TeamGraphService.expandRoleUsers reads every holder (driver-sql, shipped SysMember)', () => {
109+
it('⭐ past the 10,000-row bound: every holder is in the set, and no one else', async () => {
110+
const rig = await boot(PAGE + 1);
111+
const users = await graph(rig.engine).expandRoleUsers(ROLE, ORG);
112+
113+
expect([...users].sort()).toEqual(rig.holders);
114+
expect(users).not.toContain('usr_elsewhere');
115+
expect(users).not.toContain('usr_other_role');
116+
expect(rig.roleReads()).toBe(2);
117+
}, 30_000);
118+
119+
it('⭐ a position recipient carries the completed role limb', async () => {
120+
const rig = await boot(PAGE + 1);
121+
const team = graph(rig.engine);
122+
const positions = new PositionGraphService({ engine: rig.engine as never, organizationId: ORG, teamGraph: team });
123+
const users = await positions.expandPositionUsers(ROLE, ORG);
124+
125+
expect([...users].sort()).toEqual(rig.holders);
126+
}, 30_000);
127+
128+
it('control — under the bound: one read, the same set as before', async () => {
129+
const rig = await boot(PAGE - 1);
130+
const users = await graph(rig.engine).expandRoleUsers(ROLE, ORG);
131+
132+
expect([...users].sort()).toEqual(rig.holders);
133+
expect(rig.roleReads()).toBe(1);
134+
}, 30_000);
135+
136+
it('⛔ a read that fails refuses — it never answers an invented empty set', async () => {
137+
const rig = await boot(3);
138+
const fault = Object.assign(new Error('SQLITE_IOERR: disk I/O error'), { code: 'SQLITE_IOERR' });
139+
const memberDriver = (rig.engine as any).getDriverForObject('sys_member');
140+
vi.spyOn(memberDriver, 'find').mockRejectedValue(fault);
141+
142+
await expect(graph(rig.engine).expandRoleUsers(ROLE, ORG)).rejects.toThrow(
143+
/holders of role 'sales_rep'.*could not be read/,
144+
);
145+
});
146+
147+
it('⛔ a failed role read is not cached: the next read answers the real holders', async () => {
148+
const rig = await boot(3);
149+
const memberDriver = (rig.engine as any).getDriverForObject('sys_member');
150+
vi.spyOn(memberDriver, 'find').mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));
151+
const team = graph(rig.engine);
152+
153+
await expect(team.expandRoleUsers(ROLE, ORG)).rejects.toThrow(/could not be read/);
154+
expect([...(await team.expandRoleUsers(ROLE, ORG))].sort()).toEqual(rig.holders);
155+
});
156+
157+
it('⛔ a position recipient whose role limb fails refuses rather than answer the assignment limb alone', async () => {
158+
const rig = await boot(3);
159+
const memberDriver = (rig.engine as any).getDriverForObject('sys_member');
160+
vi.spyOn(memberDriver, 'find').mockRejectedValue(new Error('SQLITE_IOERR: disk I/O error'));
161+
const team = graph(rig.engine);
162+
const positions = new PositionGraphService({ engine: rig.engine as never, organizationId: ORG, teamGraph: team });
163+
164+
await expect(positions.expandPositionUsers(ROLE, ORG)).rejects.toThrow(/could not be read/);
165+
});
166+
167+
it('a stack whose sys_member table was never created holds no role: [] as before', async () => {
168+
const rig = await boot(0);
169+
await (rig.driver as any).knex.schema.dropTable('sys_member');
170+
171+
expect(await graph(rig.engine).expandRoleUsers(ROLE, ORG)).toEqual([]);
172+
});
173+
});

0 commit comments

Comments
 (0)