Skip to content

Commit 5ee0c46

Browse files
committed
test(plugins): pin the team and position recipient reads past 10,000 rows and on a failed read
Reds first, against origin/main code: sharing team and position expansions, the user-scoped holder checks, the per-user recompute, the queue posture, and the approvals team and position expansions. Claude-Session: https://claude.ai/code/session_01ADHkmT6XzrVS2iPpNyXNYL Co-authored-by: Claude <noreply@anthropic.com>
1 parent dbca3ef commit 5ee0c46

5 files changed

Lines changed: 665 additions & 0 deletions

File tree

Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29503] The approver `team` expansion (`sys_team_member`) and the
5+
* assignment limb of the `position` expansion (`sys_user_position`) answer
6+
* EVERY holder, or refuse — never a shortened or an invented empty slate. The
7+
* close-out of the family #29362 opened with the `sys_member` tier read.
8+
*
9+
* Both read once at a 10,000-row bound and took that read as the holder list,
10+
* and both turned a read that threw into nothing:
11+
*
12+
* - past 10,000 holders the slate was missing the holders past the 10,000th
13+
* row, with no signal;
14+
* - a failed `sys_team_member` read logged "expanded to nobody",
15+
* indistinguishable from an empty team;
16+
* - a failed `sys_user_position` read routed a `position` approver to its
17+
* `sys_member.role` holders ALONE — a shrunk slate that looks complete.
18+
*
19+
* What a caller sees now: the expansion throws, the approver-spec resolver's
20+
* directory catch takes it, and the slot falls back to its literal with the
21+
* warning that names the failed read and carries its `error`. A membership
22+
* object that does not exist is still no holders.
23+
*
24+
* Measured on a REAL engine (ObjectQL + SqlDriver over in-memory SQLite)
25+
* carrying the shipped `SysTeamMember` and `SysMember`; `sys_user_position` is
26+
* plugin-security's object and is declared here with the columns it ships.
27+
*/
28+
29+
import { describe, it, expect, afterEach, vi } from 'vitest';
30+
import { ObjectQL } from '@objectstack/objectql';
31+
import { SqlDriver } from '@objectstack/driver-sql';
32+
import { ObjectSchema, Field } from '@objectstack/spec/data';
33+
import { SysMember, SysOrganization, SysTeamMember } from '@objectstack/platform-objects/identity';
34+
import { ApprovalService } from './approval-service.js';
35+
36+
const ORG = 'org_large';
37+
const ELSEWHERE = 'org_elsewhere';
38+
const TEAM = 'team_large';
39+
const POSITION = 'cfo_office';
40+
/** The bound each read is paged at. */
41+
const PAGE = 10000;
42+
43+
const pad = (n: number) => String(n).padStart(6, '0');
44+
45+
const SysUserPosition = ObjectSchema.create({
46+
name: 'sys_user_position',
47+
label: 'User Position',
48+
isSystem: true,
49+
fields: {
50+
id: Field.text({ label: 'Assignment ID', required: true }),
51+
user_id: Field.text({ label: 'User', required: true }),
52+
position: Field.text({ label: 'Position', required: true }),
53+
organization_id: Field.text({ label: 'Organization' }),
54+
valid_from: Field.datetime({ label: 'Valid From' }),
55+
valid_until: Field.datetime({ label: 'Valid Until' }),
56+
},
57+
});
58+
59+
interface Rig {
60+
engine: ObjectQL;
61+
driver: SqlDriver;
62+
svc: ApprovalService;
63+
warn: ReturnType<typeof vi.fn>;
64+
holders: string[];
65+
reads: (table: 'sys_team_member' | 'sys_user_position') => number;
66+
failReadsOf: (object: string) => void;
67+
}
68+
69+
const engines: ObjectQL[] = [];
70+
afterEach(async () => {
71+
vi.restoreAllMocks();
72+
while (engines.length) {
73+
try { await engines.pop()?.destroy(); } catch { /* noop */ }
74+
}
75+
});
76+
77+
async function boot(seeded: 'team' | 'position', n: number, opts: { omit?: string[] } = {}): Promise<Rig> {
78+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
79+
const engine = new ObjectQL();
80+
engine.registerDriver(driver as never, true);
81+
await engine.init();
82+
const omit = new Set(opts.omit ?? []);
83+
engine.registerApp({
84+
id: 'com.objectstack.qa.team-position-holders-complete',
85+
name: 'team position holders complete',
86+
version: '1.0.0',
87+
type: 'plugin',
88+
scope: 'system',
89+
objects: [SysOrganization, SysMember, SysTeamMember, SysUserPosition].filter((o) => !omit.has(o.name)),
90+
} as never);
91+
await engine.syncSchemas();
92+
engines.push(engine);
93+
94+
const e = engine as any;
95+
await e.insert('sys_organization', { id: ORG, name: ORG, slug: 'large' }, { context: { isSystem: true } });
96+
await e.insert('sys_organization', { id: ELSEWHERE, name: ELSEWHERE, slug: 'elsewhere' }, { context: { isSystem: true } });
97+
const holders = Array.from({ length: n }, (_, i) => `usr_${pad(i)}`);
98+
const id = (prefix: string, i: number) => `${prefix}_${pad((i * 7919) % 1000003)}`;
99+
const seed = async (object: string, rows: Record<string, unknown>[]) => {
100+
const d = e.getDriverForObject(object);
101+
for (let i = 0; i < rows.length; i += 250) await d.bulkCreate(object, rows.slice(i, i + 250));
102+
};
103+
if (seeded === 'team' && !omit.has('sys_team_member')) {
104+
const rows: Record<string, unknown>[] = holders.map((user_id, i) => ({ id: id('tm', i), team_id: TEAM, user_id }));
105+
rows.push({ id: 'tm_other_team', team_id: 'team_other', user_id: 'usr_other_team' });
106+
await seed('sys_team_member', rows);
107+
}
108+
if (seeded === 'position' && !omit.has('sys_user_position')) {
109+
const rows: Record<string, unknown>[] = holders.map((user_id, i) => ({
110+
id: id('up', i), user_id, position: POSITION, organization_id: ORG,
111+
}));
112+
rows.push({ id: 'up_elsewhere', user_id: 'usr_elsewhere', position: POSITION, organization_id: ELSEWHERE });
113+
await seed('sys_user_position', rows);
114+
}
115+
116+
const counts = { sys_team_member: 0, sys_user_position: 0 };
117+
(driver as any).knex.on('query', (q: { sql: string }) => {
118+
const m = /^select .* from [`"](sys_team_member|sys_user_position)[`"]/i.exec(q.sql);
119+
if (m) counts[m[1] as keyof typeof counts] += 1;
120+
});
121+
const failReadsOf = (object: string) => {
122+
const d = e.getDriverForObject(object);
123+
const real = d.find.bind(d);
124+
vi.spyOn(d, 'find').mockImplementation(((obj: string, ...rest: unknown[]) =>
125+
obj === object
126+
? Promise.reject(Object.assign(new Error('SQLITE_IOERR: disk I/O error'), { code: 'SQLITE_IOERR' }))
127+
: real(obj, ...rest)) as never);
128+
};
129+
const warn = vi.fn();
130+
const svc = new ApprovalService({
131+
engine: engine as any,
132+
logger: { warn, info: () => {}, error: () => {}, debug: () => {} } as any,
133+
});
134+
return { engine, driver, svc, warn, holders: [...holders].sort(), reads: (t) => counts[t], failReadsOf };
135+
}
136+
137+
/** The private expansions and the resolver, as the request opener calls them. */
138+
const team = (rig: Rig, value = TEAM) => (rig.svc as any).expandTeamUsers(value, ORG) as Promise<string[]>;
139+
const position = (rig: Rig, value = POSITION) => (rig.svc as any).expandPositionUsers(value, ORG) as Promise<string[]>;
140+
const resolveSpec = (rig: Rig, a: { type: string; value: string }) =>
141+
(rig.svc as any).resolveApproverSpec(a, undefined, ORG, Date.now()) as Promise<string[]>;
142+
const failureWarnings = (rig: Rig) => rig.warn.mock.calls.filter(([, meta]) => typeof meta?.error === 'string');
143+
144+
describe('[#29503] approvals team expansion reads every member (driver-sql, shipped SysTeamMember)', () => {
145+
it('⭐ past the 10,000-row bound: every member is on the slate, and no one else', async () => {
146+
const rig = await boot('team', PAGE + 1);
147+
const users = await team(rig);
148+
149+
expect([...users].sort()).toEqual(rig.holders);
150+
expect(users).not.toContain('usr_other_team');
151+
expect(rig.reads('sys_team_member')).toBe(2);
152+
}, 30_000);
153+
154+
it('⭐ a team approver routes to every member past the bound', async () => {
155+
const rig = await boot('team', PAGE + 1);
156+
const slate = await resolveSpec(rig, { type: 'team', value: TEAM });
157+
158+
expect([...slate].sort()).toEqual(rig.holders);
159+
}, 30_000);
160+
161+
it('control — under the bound: one read, the same slate as before', async () => {
162+
const rig = await boot('team', PAGE - 1);
163+
const users = await team(rig);
164+
165+
expect([...users].sort()).toEqual(rig.holders);
166+
expect(rig.reads('sys_team_member')).toBe(1);
167+
}, 30_000);
168+
169+
it('⛔ a team read that fails refuses — it never answers an invented empty set', async () => {
170+
const rig = await boot('team', 3);
171+
rig.failReadsOf('sys_team_member');
172+
173+
await expect(team(rig)).rejects.toThrow(/members of team 'team_large'.*could not be read/);
174+
});
175+
176+
it('⛔ what the caller sees: the team slot falls back to its literal, and the warning names the failed read', async () => {
177+
const rig = await boot('team', 3);
178+
rig.failReadsOf('sys_team_member');
179+
180+
expect(await resolveSpec(rig, { type: 'team', value: TEAM })).toEqual([`team:${TEAM}`]);
181+
const failed = failureWarnings(rig);
182+
expect(failed.map(([, meta]) => meta.type)).toEqual(['team']);
183+
expect(failed[0][0]).toMatch(/could not be expanded — a directory or read-filter lookup failed/);
184+
expect(failed[0][1].error).toMatch(/SQLITE_IOERR/);
185+
});
186+
187+
it('a composition that never registers sys_team_member has no members: the literal, with no failure warning', async () => {
188+
const rig = await boot('team', 0, { omit: ['sys_team_member'] });
189+
190+
expect(await team(rig)).toEqual([]);
191+
expect(await resolveSpec(rig, { type: 'team', value: TEAM })).toEqual([`team:${TEAM}`]);
192+
expect(failureWarnings(rig)).toEqual([]);
193+
});
194+
});
195+
196+
describe('[#29503] approvals position expansion reads every assignment (driver-sql)', () => {
197+
it('⭐ past the 10,000-row bound: every assignment holder is on the slate, and no one else', async () => {
198+
const rig = await boot('position', PAGE + 1);
199+
const users = await position(rig);
200+
201+
expect([...users].sort()).toEqual(rig.holders);
202+
expect(users).not.toContain('usr_elsewhere');
203+
expect(rig.reads('sys_user_position')).toBe(2);
204+
}, 30_000);
205+
206+
it('control — under the bound: one read, the same slate as before', async () => {
207+
const rig = await boot('position', PAGE - 1);
208+
const users = await position(rig);
209+
210+
expect([...users].sort()).toEqual(rig.holders);
211+
expect(rig.reads('sys_user_position')).toBe(1);
212+
}, 30_000);
213+
214+
it('⛔ an assignment read that fails refuses rather than route to the membership-tier limb alone', async () => {
215+
const rig = await boot('position', 3);
216+
await (rig.engine as any).getDriverForObject('sys_member').bulkCreate('sys_member', [
217+
{ id: 'mem_tier', user_id: 'usr_tier', organization_id: ORG, role: POSITION },
218+
]);
219+
rig.failReadsOf('sys_user_position');
220+
221+
await expect(position(rig)).rejects.toThrow(/assignments of position 'cfo_office'.*could not be read/);
222+
});
223+
224+
it('⛔ what the caller sees: the position slot falls back to its literal, never the tier holders alone', async () => {
225+
const rig = await boot('position', 3);
226+
await (rig.engine as any).getDriverForObject('sys_member').bulkCreate('sys_member', [
227+
{ id: 'mem_tier', user_id: 'usr_tier', organization_id: ORG, role: POSITION },
228+
]);
229+
rig.failReadsOf('sys_user_position');
230+
231+
expect(await resolveSpec(rig, { type: 'position', value: POSITION })).toEqual([`position:${POSITION}`]);
232+
const failed = failureWarnings(rig);
233+
expect(failed.map(([, meta]) => meta.type)).toEqual(['position']);
234+
expect(failed[0][1].error).toMatch(/SQLITE_IOERR/);
235+
});
236+
237+
it('a composition that never registers sys_user_position routes to the membership-tier limb, with no failure warning', async () => {
238+
const rig = await boot('position', 0, { omit: ['sys_user_position'] });
239+
await (rig.engine as any).getDriverForObject('sys_member').bulkCreate('sys_member', [
240+
{ id: 'mem_tier', user_id: 'usr_tier', organization_id: ORG, role: POSITION },
241+
]);
242+
243+
expect(await resolveSpec(rig, { type: 'position', value: POSITION })).toEqual(['usr_tier']);
244+
expect(failureWarnings(rig)).toEqual([]);
245+
});
246+
247+
it('a stack whose sys_user_position table was never created routes to the membership-tier limb', async () => {
248+
const rig = await boot('position', 0);
249+
await (rig.driver as any).knex.schema.dropTable('sys_user_position');
250+
await (rig.engine as any).getDriverForObject('sys_member').bulkCreate('sys_member', [
251+
{ id: 'mem_tier', user_id: 'usr_tier', organization_id: ORG, role: POSITION },
252+
]);
253+
254+
expect(await position(rig)).toEqual(['usr_tier']);
255+
});
256+
});

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,23 @@ describe('[ADR-0142 D2] OwnershipQueueService — the one expander', () => {
196196
expect(warn.mock.calls[0][0]).toMatch(/sys_queue_member read failed/);
197197
});
198198

199+
it('[#29503] a failed team or position holder read keeps the queue\'s declared posture: that specification contributes nobody, logged once', async () => {
200+
// The team and position reads now refuse a failed read instead of answering
201+
// "nobody"; the queue service keeps answering for its own consumers exactly
202+
// as its header declares (a failed member-table read contributes nobody),
203+
// on the expansion and on the holder check alike. Whether the queue should
204+
// refuse too is left to a ruling (ADR-0142 does not declare this posture).
205+
for (const failed of ['sys_team_member', 'sys_user_position'] as const) {
206+
const warn = vi.fn();
207+
const svc = service(makeEngine({ declared: SUPPORT_DECLARED, tables: BASE_TABLES(), failOn: [failed] }), { warn });
208+
const expected = failed === 'sys_team_member' ? ['u_a', 'u_b'] : ['u_a', 'u_d'];
209+
expect(await svc.expandMembers('support_tier1', 'org_a')).toEqual(expected);
210+
expect(await svc.isMember(failed === 'sys_team_member' ? 'u_d' : 'u_b', 'support_tier1', 'org_a')).toBe(false);
211+
expect(await svc.isMember(failed === 'sys_team_member' ? 'u_b' : 'u_d', 'support_tier1', 'org_a')).toBe(true);
212+
expect(warn.mock.calls.some(([line]) => /could not be (expanded|read)/.test(String(line)))).toBe(true);
213+
}
214+
});
215+
199216
it('a failed ledger read leaves the declared default — on — and says so', async () => {
200217
const warn = vi.fn();
201218
const svc = service(makeEngine({ declared: SUPPORT_DECLARED, tables: BASE_TABLES(), failOn: [METADATA_ACTIVATION_TABLE] }), { warn });

‎packages/plugins/plugin-sharing/src/recipient-membership-recompute.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,62 @@ describe('team membership writes re-evaluate team-recipient rules, and the trans
384384
});
385385
});
386386

387+
/**
388+
* [#29503] The holder check the per-user pass asks reads the membership table
389+
* again, and a failed read used to answer "not a holder": the pass then revoked
390+
* the user's grants on an outage. It now refuses, the pass's catch logs, and
391+
* the grants stay until the read succeeds. Only the holder check's reads fail
392+
* here (a read filtered on the recipient column), so the write itself and its
393+
* pre-image read go through as they would in an outage of that index.
394+
*/
395+
describe('[#29503] a failed holder read keeps the user\'s grants instead of revoking them', () => {
396+
const failHolderReads = (t: Awaited<ReturnType<typeof boot>>, table: string, column: string) => {
397+
const real = t.driver.find.bind(t.driver);
398+
return vi.spyOn(t.driver, 'find').mockImplementation(((obj: string, query: unknown, ...rest: unknown[]) =>
399+
obj === table && JSON.stringify(query ?? {}).includes(`"${column}"`)
400+
? Promise.reject(Object.assign(new Error('SQLITE_IOERR: disk I/O error'), { code: 'SQLITE_IOERR' }))
401+
: real(obj as never, query as never, ...(rest as []))) as never);
402+
};
403+
404+
it('⛔ team: a member still on the team through a second row keeps the grants when the holder read fails', async () => {
405+
const t = await boot();
406+
await t.ql.insert('sys_team_member', { id: 'tm_1', organization_id: ORG_A, team_id: 'team_eu', user_id: 'u_team' }, { context: SYSTEM } as never);
407+
await t.ql.insert('sys_team_member', { id: 'tm_2', organization_id: ORG_A, team_id: 'team_eu', user_id: 'u_team' }, { context: SYSTEM } as never);
408+
expect(await t.grantsOf('u_team', 'srule_team')).toEqual(['acct_eu_1:read', 'acct_eu_2:read']);
409+
410+
failHolderReads(t, 'sys_team_member', 'team_id');
411+
await t.ql.delete('sys_team_member', { where: { id: 'tm_2' }, context: SYSTEM } as never);
412+
vi.restoreAllMocks();
413+
414+
expect(await t.grantsOf('u_team', 'srule_team')).toEqual(['acct_eu_1:read', 'acct_eu_2:read']);
415+
expect(t.warn.mock.calls.some(([line]) => /recipient membership re-evaluation failed/.test(String(line)))).toBe(true);
416+
});
417+
418+
it('⛔ position: a holder still assigned through a second row keeps the grants when the assignment read fails', async () => {
419+
const t = await boot();
420+
await t.assign('up_1', 'u_pos', 'eu_sales');
421+
await t.assign('up_2', 'u_pos', 'eu_sales');
422+
expect(await t.grantsOf('u_pos')).toEqual(EU_GRANTS);
423+
424+
failHolderReads(t, 'sys_user_position', 'position');
425+
await t.ql.delete('sys_user_position', { where: { id: 'up_2' }, context: SYSTEM } as never);
426+
vi.restoreAllMocks();
427+
428+
expect(await t.grantsOf('u_pos')).toEqual(EU_GRANTS);
429+
expect(t.warn.mock.calls.some(([line]) => /recipient membership re-evaluation failed/.test(String(line)))).toBe(true);
430+
});
431+
432+
it('control — the same delete with the reads healthy keeps the grants too (the user still holds the recipient)', async () => {
433+
const t = await boot();
434+
await t.ql.insert('sys_team_member', { id: 'tm_1', organization_id: ORG_A, team_id: 'team_eu', user_id: 'u_team' }, { context: SYSTEM } as never);
435+
await t.ql.insert('sys_team_member', { id: 'tm_2', organization_id: ORG_A, team_id: 'team_eu', user_id: 'u_team' }, { context: SYSTEM } as never);
436+
437+
await t.ql.delete('sys_team_member', { where: { id: 'tm_2' }, context: SYSTEM } as never);
438+
439+
expect(await t.grantsOf('u_team', 'srule_team')).toEqual(['acct_eu_1:read', 'acct_eu_2:read']);
440+
});
441+
});
442+
387443
describe('binding and write classification', () => {
388444
const fakeEngine = () => {
389445
const hooks: Array<{ event: string; options: Record<string, any> }> = [];

0 commit comments

Comments
 (0)