From 27c97354c648096bd24ac0a379c009eadb17c948 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:39:28 +0000 Subject: [PATCH 1/6] wip: memoize the on-behalf-of delegator resolution per context Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- .../src/security-plugin-field-readers.ts | 9 +- .../src/security-plugin-object-admission.ts | 7 +- .../plugin-security/src/security-plugin.ts | 83 ++++++++++++++++++- 3 files changed, 92 insertions(+), 7 deletions(-) diff --git a/packages/plugins/plugin-security/src/security-plugin-field-readers.ts b/packages/plugins/plugin-security/src/security-plugin-field-readers.ts index b34c529a74b..10ac6ae00fe 100644 --- a/packages/plugins/plugin-security/src/security-plugin-field-readers.ts +++ b/packages/plugins/plugin-security/src/security-plugin-field-readers.ts @@ -67,7 +67,7 @@ import type { SecurityPlugin } from './security-plugin.js'; import type { PermissionSet } from '@objectstack/spec/security'; import type { FieldMaskingRule } from '@objectstack/spec/data'; -import { delegatedOrganizationRefusal, intersectFieldMasks, resolveDelegatorContext } from './explain-engine.js'; +import { delegatedOrganizationRefusal, intersectFieldMasks } from './explain-engine.js'; /** * The `SecurityPlugin` members the functions below read — every one of them, @@ -89,6 +89,7 @@ export interface FieldReadersHost { getObjectFieldNames: SecurityPlugin['getObjectFieldNames']; getObjectSecurityMeta: SecurityPlugin['getObjectSecurityMeta']; resolveCallerPosture: SecurityPlugin['resolveCallerPosture']; + resolveDelegatorForContext: SecurityPlugin['resolveDelegatorForContext']; resolveFallbackPermissionSets: SecurityPlugin['resolveFallbackPermissionSets']; resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext']; resolveProjectionFieldMask: SecurityPlugin['resolveProjectionFieldMask']; @@ -134,7 +135,7 @@ export async function computeReadableFields( /** The body of `SecurityPlugin#resolveProjectionFieldMask`; the method's docblock there is its contract. */ export async function resolveProjectionFieldMask( - this: Pick, + this: Pick, object: string, context: any, options: { fallbackOnEmptySets: boolean }, @@ -208,7 +209,9 @@ export async function resolveProjectionFieldMask( let delBasePerms: Record | null = null; let delegatorSets: PermissionSet[] | null = null; if (permissionSets.length > 0 && context?.onBehalfOf?.userId) { - const del = await resolveDelegatorContext(this.ql, context); + // Once per context while no write intervenes (`resolveDelegatorForContext`): + // a schema-serving door asks this of every object it serves. + const del = await this.resolveDelegatorForContext(context); if (del.kind === 'missing') return { kind: 'answer', fields: [] }; if (del.kind === 'resolved') { if (delegatedOrganizationRefusal(context, del.context, this.tenancyPosture) !== undefined) { diff --git a/packages/plugins/plugin-security/src/security-plugin-object-admission.ts b/packages/plugins/plugin-security/src/security-plugin-object-admission.ts index 85f239bb7fb..5af4cf882fa 100644 --- a/packages/plugins/plugin-security/src/security-plugin-object-admission.ts +++ b/packages/plugins/plugin-security/src/security-plugin-object-admission.ts @@ -91,12 +91,13 @@ export interface ObjectAdmissionHost { getObjectSecurityMeta: SecurityPlugin['getObjectSecurityMeta']; objectReadAdmission: SecurityPlugin['objectReadAdmission']; organizationWallRefusal: SecurityPlugin['organizationWallRefusal']; + resolveDelegatorForContext: SecurityPlugin['resolveDelegatorForContext']; resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext']; } /** The body of `SecurityPlugin#canReadObject`; the method's docblock there is its contract. */ export async function canReadObject( - this: Pick, + this: Pick, object: string, context?: any, ): Promise { @@ -121,7 +122,9 @@ export async function canReadObject( // ({@link delegatedOrganizationRefusal}). let delegatorSets: PermissionSet[] | null = null; if (context?.onBehalfOf?.userId) { - const del = await resolveDelegatorContext(this.ql, context); + // Once per context while no write intervenes (`resolveDelegatorForContext`): + // a schema-serving door asks this of every object it serves. + const del = await this.resolveDelegatorForContext(context); if (del.kind === 'missing') return false; if (del.kind === 'resolved') { if (delegatedOrganizationRefusal(context, del.context, this.tenancyPosture) !== undefined) return false; diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 4f449c4c11a..88646abbe3e 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -191,6 +191,9 @@ import { objectReadAdmission, type ObjectAdmissionHost, } from './security-plugin-object-admission.js'; +// The ADR-0090 D10 delegator resolution the two object-schema read sites ask +// through {@link SecurityPlugin.resolveDelegatorForContext}. +import { resolveDelegatorContext, type DelegatorResolution } from './explain-engine.js'; // [#25223 cut 10] The `everyone` anchor's declarations: the anchor's // definition a started kernel derives, and the built-in positions `init()` // declares; the methods of the same names below hand each body the members it @@ -3343,7 +3346,7 @@ export class SecurityPlugin implements Plugin { const readPermissionEvaluator = () => this.permissionEvaluator; const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; - const host: Pick = { + const host: Pick = { computeForbiddenFieldWrites: (...a) => this.computeForbiddenFieldWrites(...a), computeQueryGuardFieldPerms: (...a) => this.computeQueryGuardFieldPerms(...a), computeReadPartialMaskRules: (...a) => this.computeReadPartialMaskRules(...a), @@ -3353,6 +3356,7 @@ export class SecurityPlugin implements Plugin { get permissionEvaluator() { return readPermissionEvaluator(); }, get ql() { return readQl(); }, resolveCallerPosture: (...a) => this.resolveCallerPosture(...a), + resolveDelegatorForContext: (...a) => this.resolveDelegatorForContext(...a), resolveFallbackPermissionSets: (...a) => this.resolveFallbackPermissionSets(...a), resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), get tenancyPosture() { return readTenancyPosture(); }, @@ -3476,11 +3480,12 @@ export class SecurityPlugin implements Plugin { const readLogger = () => this.logger; const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; - const host: Pick = { + const host: Pick = { get delegatedAdminGate() { return readDelegatedAdminGate(); }, get logger() { return readLogger(); }, objectReadAdmission: (...a) => this.objectReadAdmission(...a), get ql() { return readQl(); }, + resolveDelegatorForContext: (...a) => this.resolveDelegatorForContext(...a), resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), get tenancyPosture() { return readTenancyPosture(); }, }; @@ -3763,6 +3768,80 @@ export class SecurityPlugin implements Plugin { return permissionSetMemoKey(context); } + /** + * The ADR-0090 D10 delegator resolutions {@link resolveDelegatorForContext} + * has made, per live execution context — the {@link permissionSetMemo} + * discipline, for the second question an on-behalf-of read asks. + */ + private readonly delegatorMemo = new WeakMap< + object, + { epoch: number; key: string; resolution: Promise } + >(); + + /** + * [ADR-0090 D10] The delegator behind an on-behalf-of `context` + * ({@link resolveDelegatorContext}), resolved once per context while no + * write intervenes. Asked by the two object-schema read questions — + * {@link canReadObject} and the field projection + * ({@link resolveProjectionFieldMask}) — which a schema-serving door asks + * once PER OBJECT: `/meta` lists and MCP `list_objects` ask both of every + * object in the environment. + * + * ## The duplicate it removes + * + * Each ask re-read the delegator (`sys_user`, memberships, grants, + * positions) and handed back a context object nobody had seen, so the + * delegator's sets missed {@link permissionSetMemo} too: one OAuth client's + * `list_objects` issued 22 statements per object (two questions x 11) for + * one unchanged answer, measured on a real kernel. Against a database a + * network hop away that is the listing's whole latency. + * + * ## Why it is not a cache + * + * Exactly the {@link permissionSetMemo} argument, unchanged: keyed on the + * context OBJECT, which a door builds once per request (the `/mcp` door, + * REST's per-`req` memo), so nothing outlives the caller it was resolved + * for; reused only while {@link epoch} stands, so any write in this process + * — a grant revoked, a membership removed — retires it; and keyed on the + * three members the resolution reads off the context (`onBehalfOf.userId`, + * `tenantId`, `org_user_ids`), so a context edited in place resolves again. + * Every kind is kept (`none`, `missing`, `resolved`); a rejection is not. + * + * One consequence, stated: `resolveDelegatorContext`'s clock is read at the + * first resolution, so one request judges the delegator's time-limited + * grants (ADR-0091) at one instant rather than at each object's — which + * makes one listing coherent, and moves no answer except one whose grant + * window closes inside the request. + * + * The resolved context is FROZEN (shallowly, with its arrays): every asker + * shares it, and the two sites only read it — the organization check + * ({@link delegatedOrganizationRefusal}, still asked at each site, every + * call) and the delegator's sets. ⛔ Not for a site that carries the + * delegator context onward into a filter or a write (the read filter, the + * operation prologue, explain): those keep resolving their own. + */ + private resolveDelegatorForContext(context: any): Promise { + if (!context || typeof context !== 'object') return resolveDelegatorContext(this.ql, context); + const key = JSON.stringify([ + context.onBehalfOf?.userId ?? null, + context.tenantId ?? null, + context.org_user_ids ?? null, + ]); + const hit = this.delegatorMemo.get(context); + if (hit && hit.epoch === this.epoch.current && hit.key === key) return hit.resolution; + const resolution = resolveDelegatorContext(this.ql, context).then((resolved) => { + if (resolved.kind !== 'resolved') return Object.freeze(resolved); + for (const value of Object.values(resolved.context)) if (Array.isArray(value)) Object.freeze(value); + return Object.freeze({ kind: 'resolved' as const, context: Object.freeze(resolved.context) }); + }); + const entry = { epoch: this.epoch.current, key, resolution }; + this.delegatorMemo.set(context, entry); + resolution.catch(() => { + if (this.delegatorMemo.get(context) === entry) this.delegatorMemo.delete(context); + }); + return resolution; + } + /** * [#18783] `ISecurityService.getEffectiveObjectPermissions` — the subject's * EFFECTIVE object-permission map, object name -> `EffectiveObjectPermission`. From d34cd4714d2116e5708396c53432db3568832d8d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:40:40 +0000 Subject: [PATCH 2/6] wip: pin list_objects statements, answers and delegator invalidation Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- .../mcp-list-objects-statements.pin.test.ts | 361 ++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 packages/runtime/src/mcp-list-objects-statements.pin.test.ts diff --git a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts new file mode 100644 index 00000000000..6e75acabb2c --- /dev/null +++ b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts @@ -0,0 +1,361 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * MCP `list_objects` statements per call, pinned on a REAL kernel (the plugin + * set `default-organization-statements.golden.test.ts` composes), for the + * caller hosted MCP clients are: an OAuth client acting on behalf of a person + * (ADR-0090 D10 — `onBehalfOf`, the `mcp_agent_data_read` ceiling, no + * system permission), whose every object-schema read is the INTERSECTION of + * the agent's grants and the person's. + * + * ## What grew + * + * The bridge (`buildMcpBridge`, `domains/mcp.ts`) serves each listed object + * through the `/meta` object door's masker, which asks the security service + * two questions per object: `canReadObject` and `getMetadataReadableFields`. + * For an on-behalf-of caller each of those resolved the delegator afresh — + * the person's `sys_user` row, memberships, grants and positions, and then the + * person's permission sets for a context object nobody had seen before, so the + * per-context set memo never hit. Measured on `origin/main` 68972cd2 with this + * composition: 26 statements per listed object (2 questions x 13), so an + * environment owner listing about 170 objects paid thousands of round trips — + * tens of seconds against a remote database. + * + * ## What this pins + * + * 1. ⭐ Statements per `list_objects` do not grow with the object count: the + * same call, the same callers, before and after the environment gains + * 140 objects, differ by at most {@link STATEMENT_SLACK}. + * 2. ⭐ The answers are the ones `origin/main` gave, byte for byte + * ({@link GOLDEN}, measured there): every caller, both sizes — the same + * objects, the same field counts, the same order, the same `sys_*` + * read opt-in verdicts. + * 3. CONTROL — `describe_object` answers the same, and costs no more. + * + * Counted: every statement the SQL driver issues inside the call's own async + * context (knex's `query` event), as the statements golden counts them. + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { createHash } from 'node:crypto'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel, assembleExecutionContext, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; +import { createRestApiPlugin } from '@objectstack/rest'; +import { AuthPlugin } from '@objectstack/plugin-auth'; +import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; +import { scopesToAgentPermissionSets } from '@objectstack/spec/ai'; +import { AppPlugin } from './app-plugin.js'; +import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; +import { createDispatcherPlugin } from './dispatcher-plugin.js'; +import { HttpDispatcher } from './http-dispatcher.js'; + +const BOOT_TIMEOUT = 180_000; +const ORIGIN = 'http://localhost:3000'; +const API = '/api/v1'; +/** `AuthPlugin`'s dev-admin defaults (`OS_SEED_ADMIN_*` unset): the environment's owner. */ +const OWNER = { email: 'admin@objectos.ai', password: 'admin123' }; +const MEMBER = { email: 'member@pin.test', password: 'member-pin-password-33179', name: 'Pin member' }; +const SCOPES = ['openid', 'offline_access', 'data:read']; +/** The listing reads that do not depend on the object count (the merged listing). */ +const STATEMENT_SLACK = 2; + +const objectsOf = (prefix: string, from: number, count: number) => + Array.from({ length: count }, (_, i) => ({ + name: `${prefix}_${String(from + i).padStart(3, '0')}`, + label: `Object ${from + i}`, + fields: Object.fromEntries(Array.from({ length: 6 }, (_, f) => [`f_${f}`, { type: 'text', label: `F ${f}` }])), + })); + +const PIN_APP: any = { + manifest: { id: 'com.pin.listobjects33179', name: 'list_objects statement pins', version: '1.0.0' }, + objects: objectsOf('pin_lo', 0, 10), +}; +/** Installed after the first reading: the environment grows from 10 to 150 objects. */ +const GROWTH: any = { + id: 'com.pin.listobjects33179.growth', + name: 'list_objects statement pins (growth)', + version: '1.0.0', + type: 'app', + objects: objectsOf('pin_lo', 10, 140), +}; + +const statements = new AsyncLocalStorage(); +let kernel: any; +let engine: any; +let app: any; +let prevNodeEnv: string | undefined; +let prevMcp: string | undefined; + +/** The MCP service: records the bridge and caller the real `/mcp` entry hands it. */ +const mcp: any = { + lastOpts: undefined, + handleHttpRequest: async (_req: Request, opts: any) => { + mcp.lastOpts = opts; + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + }, +}; + +async function signIn(who: { email: string; password: string }): Promise { + const res = await app.request(`${ORIGIN}${API}/auth/sign-in/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(who), + }); + expect(res.status, await res.clone().text()).toBe(200); + return ((await res.json()) as { token: string }).token; +} + +/** The person's own execution context, as the real `/mcp` entry resolved it for their session. */ +async function personContext(token: string): Promise> { + const res = await app.request(`${ORIGIN}${API}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}` }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), + }); + expect(res.status, 'precondition: the /mcp entry served the session').toBe(200); + return mcp.lastOpts.caller.executionContext; +} + +/** + * The context an OAuth MCP client holding `data:read` acts under for + * `person`, assembled by the shared assembler the `/mcp` door calls + * (`assembleExecutionContext`, ADR-0090 D10): its ceiling, no system + * permission, `onBehalfOf` the person. + */ +function agentFor(person: Record): Record { + const ctx = assembleExecutionContext({ + authz: person as any, + oauth: { + userId: person.userId, + clientId: 'pin_mcp_client', + scopes: SCOPES, + scopePermissions: scopesToAgentPermissionSets(SCOPES), + delegatesActions: false, + } as any, + localization: undefined, + requestLocale: undefined, + accessToken: undefined, + authGate: undefined, + }) as Record; + expect(ctx.onBehalfOf?.userId, 'precondition: an on-behalf-of agent').toBe(person.userId); + expect(ctx.systemPermissions).toEqual([]); + return ctx; +} + +/** The bridge the real `/mcp` entry builds for `executionContext`. */ +async function bridgeFor(executionContext: Record): Promise { + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const res = await dispatcher.handleMcp({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { + request: new Request(`${ORIGIN}${API}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: '{}', + }), + response: {}, + environmentId: undefined, + executionContext: { ...executionContext }, + } as any); + expect(res.response?.status, 'precondition: the /mcp entry served the caller').toBe(200); + return mcp.lastOpts.bridge; +} + +/** + * One `list_objects`, as the tool reads the bridge (`registerHttpTools`, + * `@objectstack/mcp`): the diagnosed listing, then the read opt-in of each + * listed `sys_*` object. Answered with the statements it issued. + */ +async function listObjects(executionContext: Record) { + const bridge = await bridgeFor(executionContext); + const sql: string[] = []; + const answer = await statements.run(sql, async () => { + const diagnosed = await bridge.listObjectsDiagnosed(); + const aiReadable: string[] = []; + for (const o of diagnosed.objects) if (/^sys_/.test(o.name) && await bridge.aiReadExposed(o.name)) aiReadable.push(o.name); + return { diagnosed, aiReadable }; + }); + return { answer, statements: sql.length }; +} + +async function describeObject(executionContext: Record, name: string) { + const bridge = await bridgeFor(executionContext); + const sql: string[] = []; + const answer = await statements.run(sql, () => bridge.describeObject(name)); + return { answer, statements: sql.length }; +} + +const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex'); + +/** What a reading is compared on: how many objects, and the answer's bytes. */ +const fingerprint = (answer: { diagnosed: { objects: unknown[] } }) => ({ objects: answer.diagnosed.objects.length, sha256: digest(answer) }); + +let callers: Record<'owner' | 'member' | 'ownerAgent' | 'memberAgent', Record>; +const readings: Record> = {}; +const described: Record> = {}; + +async function read(size: string) { + readings[size] = {}; + described[size] = {}; + for (const [who, ctx] of Object.entries(callers)) { + await listObjects(ctx); // warm: the session, the served metadata and the listing caches + const { answer, statements: n } = await listObjects(ctx); + readings[size][who] = { ...fingerprint(answer), statements: n }; + const d = await describeObject(ctx, 'pin_lo_000'); + described[size][who] = { sha256: digest(d.answer), statements: d.statements }; + } +} + +beforeAll(async () => { + prevNodeEnv = process.env.NODE_ENV; + prevMcp = process.env.OS_MCP_SERVER_ENABLED; + process.env.NODE_ENV = 'development'; // the dev-admin seed, as `objectstack dev` arms it + process.env.OS_MCP_SERVER_ENABLED = 'true'; + kernel = new ObjectKernel(); + const recorder: Plugin = { name: 'pin.mcp-recorder', init: async (ctx: PluginContext) => { ctx.registerService('mcp', mcp); } }; + await kernel.use(recorder); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new DefaultDatasourcePlugin({ driver: 'sqlite-wasm', config: { filename: ':memory:' } })); + await kernel.use(new HonoServerPlugin({ port: 0 })); + await kernel.use(new AppPlugin(PIN_APP)); + await kernel.use(new PlatformObjectsPlugin()); + await kernel.use(new AuthPlugin({ secret: 'list-objects-statements-33179-pin-secret' })); + await kernel.use(new SecurityPlugin(appSecurityPluginOptions(PIN_APP))); + await kernel.use(new SharingServicePlugin()); + await kernel.use(createRestApiPlugin({})); + await kernel.use(createDispatcherPlugin({})); + await kernel.bootstrap(); + engine = await kernel.getServiceAsync('objectql'); + app = (await kernel.getServiceAsync('http-server')).getRawApp(); + (engine as any).getDriver('sys_user').knex.on('query', (q: { sql?: unknown }) => { + statements.getStore()?.push(String(q?.sql ?? '')); + }); + const owner = await personContext(await signIn(OWNER)); + // The default audience posture is invite_only: the member enters the + // owner's organization through a pending invitation. + await engine.insert('sys_invitation', { + id: 'inv_pin_33179', email: MEMBER.email, status: 'pending', organization_id: owner.tenantId, + role: 'member', inviter_id: owner.userId, expires_at: new Date(Date.now() + 3_600_000), + }, { context: { isSystem: true } }); + const signUp = await app.request(`${ORIGIN}${API}/auth/sign-up/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...MEMBER, invitationId: 'inv_pin_33179' }), + }); + expect(signUp.status, await signUp.clone().text()).toBe(200); + const member = await personContext(await signIn(MEMBER)); + callers = { owner, member, ownerAgent: agentFor(owner), memberAgent: agentFor(member) }; + + await read('10'); + await kernel.getService('manifest').register(GROWTH, { source: 'marketplace' }); + await engine.syncSchemas(); + await read('150'); +}, BOOT_TIMEOUT); + +afterAll(async () => { + try { await kernel?.shutdown?.(); } catch { /* best-effort */ } + if (prevNodeEnv === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = prevNodeEnv; + if (prevMcp === undefined) delete process.env.OS_MCP_SERVER_ENABLED; + else process.env.OS_MCP_SERVER_ENABLED = prevMcp; +}, 60_000); + +/** + * The answers `origin/main` 68972cd2 gave on this composition, before the + * delegator memo: per caller and size, the listed object count and the + * sha256 of the whole answer (the diagnosed listing and the `sys_*` read + * opt-in verdicts) — and, for `describe_object`, of its answer. Measured by + * this file's own readings at that commit. + * + * The statements `origin/main` paid there, for the record (not asserted — + * {@link STATEMENT_SLACK} is): `ownerAgent` 1540 at 10 objects and 4620 at + * 150, `memberAgent` 1260 and 3780; `describe_object` 22 and 18; the two + * session callers 0. + */ +const GOLDEN = { + list: { + 10: { + owner: { objects: 68, sha256: '304fb285b8c37106383843881c205155106c18037979f0720a0e3e921e196332' }, + member: { objects: 29, sha256: '1c5b772ff78f4bc882df5692d40800ad5f130e2cab755e4227f027b8590da93d' }, + ownerAgent: { objects: 49, sha256: 'f4e77a4d252e88493df36c4d01369efeb8ad5c431edeaa2bc3ec9c014e1800dc' }, + memberAgent: { objects: 23, sha256: '6e73539aaedd9f3612896c867f621327273103a626633c62b14eb41735af2a1c' }, + }, + 150: { + owner: { objects: 208, sha256: '9edb5243e5bcdf3fa149420ad5799e6360ec8eea1df5349368678058c2c58e0d' }, + member: { objects: 29, sha256: '1c5b772ff78f4bc882df5692d40800ad5f130e2cab755e4227f027b8590da93d' }, + ownerAgent: { objects: 189, sha256: 'd03424429fc1b2502e1c07604d17689b22b6adce7991282935a52e38902e9fd6' }, + memberAgent: { objects: 23, sha256: '6e73539aaedd9f3612896c867f621327273103a626633c62b14eb41735af2a1c' }, + }, + }, + describe: { + owner: 'f61a6720fe797e325ff07a4fdf61571fe993ed13d1e3cc40743b4ae7712fb705', + member: '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', + ownerAgent: 'f61a6720fe797e325ff07a4fdf61571fe993ed13d1e3cc40743b4ae7712fb705', + memberAgent: '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', + }, + /** `describe_object`'s statements on `origin/main` for the two delegated callers. */ + describeStatements: { ownerAgent: 22, memberAgent: 18 }, +} as const; + +const WHO = ['owner', 'member', 'ownerAgent', 'memberAgent'] as const; + +describe('[ADR-0090 D10] MCP list_objects statements do not grow with the object count (real kernel)', () => { + it('precondition: the environment grew from 10 to 150 objects, and the owner\'s agent is listed every one', () => { + expect(readings['150'].owner.objects - readings['10'].owner.objects).toBe(140); + expect(readings['150'].ownerAgent.objects - readings['10'].ownerAgent.objects).toBe(140); + }); + + for (const who of WHO) { + it(`⭐ ${who}: statements per list_objects at 150 objects are those at 10, within ${STATEMENT_SLACK}`, () => { + const grown = readings['150'][who].statements - readings['10'][who].statements; + expect(Math.abs(grown), JSON.stringify({ 10: readings['10'][who], 150: readings['150'][who] })).toBeLessThanOrEqual(STATEMENT_SLACK); + }); + } + + it('⭐ the delegated callers pay their delegator once, not once per object: at most one describe_object\'s worth', () => { + for (const who of ['ownerAgent', 'memberAgent'] as const) { + expect(readings['150'][who].statements, who).toBeLessThanOrEqual(GOLDEN.describeStatements[who]); + } + }); +}); + +describe('[ADR-0106 D1/D5, ruling record 6787890900] the answers are origin/main\'s, byte for byte', () => { + for (const size of ['10', '150'] as const) { + for (const who of WHO) { + it(`⭐ ${who} at ${size} objects: list_objects lists what it listed before, in the same order`, () => { + const { objects, sha256 } = readings[size][who]; + expect({ objects, sha256 }).toEqual(GOLDEN.list[size][who]); + }); + } + } +}); + +describe('CONTROL — describe_object', () => { + for (const who of WHO) { + it(`${who}: the same answer at both sizes, the one origin/main gave, for no more statements`, () => { + expect(described['10'][who].sha256).toBe(GOLDEN.describe[who]); + expect(described['150'][who].sha256).toBe(GOLDEN.describe[who]); + expect(described['150'][who].statements).toBe(described['10'][who].statements); + }); + } +}); + +describe('[ADR-0090 D10] a write retires the delegator resolution inside one request', () => { + it('⭐ the delegator\'s membership removed between two listings of ONE bridge: the second is narrower', async () => { + const bridge = await bridgeFor(callers.memberAgent); + const before: string[] = (await bridge.listObjects()).map((o: any) => o.name); + expect(before.length, 'precondition: the member\'s agent is listed objects').toBeGreaterThan(0); + const sys = { isSystem: true }; + const memberships: any[] = await engine.find('sys_member', { + where: { user_id: callers.member.userId, organization_id: callers.member.tenantId }, context: sys, + }); + expect(memberships.length, 'precondition: the member belongs to the organization').toBeGreaterThan(0); + for (const m of memberships) await engine.delete('sys_member', { where: { id: m.id }, context: sys } as any); + try { + const after: string[] = (await bridge.listObjects()).map((o: any) => o.name); + expect(after.length).toBeLessThan(before.length); + for (const name of after) expect(before).toContain(name); + } finally { + for (const m of memberships) await engine.insert('sys_member', m, { context: sys }); + } + }); +}); From be9659bdb53e2c7a7edc243a329319f5c3c16d74 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:44:33 +0000 Subject: [PATCH 3/6] wip: changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- .changeset/33179-list-objects-round-trips.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/33179-list-objects-round-trips.md diff --git a/.changeset/33179-list-objects-round-trips.md b/.changeset/33179-list-objects-round-trips.md new file mode 100644 index 00000000000..ff89ee45832 --- /dev/null +++ b/.changeset/33179-list-objects-round-trips.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security): an OAuth MCP client's `list_objects` resolves the person it acts for once per request, not once per object + +Clause-②: no +Metadata-protocol: none + +An MCP client signed in with OAuth acts on behalf of a person (ADR-0090 D10). Every object-schema read such a caller makes is the intersection of the client's grants and that person's. `list_objects` asks two questions of every object in the environment: may this caller read the object, and which of its fields. Each question re-read the person's user row, memberships, grants and positions, so one listing cost about 22 database statements per object. Measured on a real kernel, 150 objects took 4620 statements. An environment owner with about 170 objects on a remote database waited tens of seconds, close to a client's 60-second timeout. + +The security service now resolves that person once per request and reuses the answer for every object, so the same listing costs 11 statements whatever the object count. `describe_object` drops from 22 statements to 11. The answers are byte for byte the same for every caller: the same objects, field counts and order. Signed-in sessions and API keys act for nobody and were not affected. + +The reuse lasts only as long as the request's context and only until the next write. Revoking a grant or removing a membership retires it at once, inside the same request too. One request now judges the person's time-limited grants at one instant, its first resolution, instead of at each object, so one listing is coherent. No answer moves except one whose grant window closes inside that request. From b8a43708932f44010a75243412e66ed7fa8fd77e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:51:39 +0000 Subject: [PATCH 4/6] wip: one resolution site in the delegator memo; census counts its askers Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- .../src/delegated-organization-membership.test.ts | 13 ++++++++++++- .../plugins/plugin-security/src/security-plugin.ts | 14 +++++++------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts b/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts index b7f30b5a9d2..d5d987a5bd1 100644 --- a/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts +++ b/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts @@ -847,13 +847,24 @@ describe('[#25107] every reader in this package that resolves a delegator asks t const SRC = dirname(fileURLToPath(import.meta.url)); const calls = (text: string, name: string) => (text.match(new RegExp(`\\b${name}\\(`, 'g')) ?? []).length - (text.match(new RegExp(`function ${name}\\(`, 'g')) ?? []).length; + // The per-context memo (`SecurityPlugin.resolveDelegatorForContext`) resolves + // in ONE place for the readers that ask it, and asks nothing itself: each of + // its askers asks the check beside its own call, so an ask of the memo counts + // as a resolution in the asker's file, and the memo's one resolution counts + // in none. + const MEMO_FILE = 'security-plugin.ts'; + const memoAsks = (text: string) => (text.match(/\bthis\.resolveDelegatorForContext\(context\b/g) ?? []).length; it('per source file, the asks equal the resolutions — and the seven files that resolve one are all counted', () => { const counted: Record = {}; for (const file of readdirSync(SRC, { recursive: true }) as string[]) { if (!file.endsWith('.ts') || file.endsWith('.test.ts') || file.includes('.testkit.')) continue; const text = readFileSync(join(SRC, file), 'utf8'); - const resolutions = calls(text, 'resolveDelegatorContext'); + let resolutions = calls(text, 'resolveDelegatorContext') + memoAsks(text); + if (file === MEMO_FILE) { + expect(calls(text, 'resolveDelegatorContext'), 'the memo resolves in exactly one place').toBe(1); + resolutions -= 1; + } if (resolutions === 0) continue; counted[file] = [resolutions, calls(text, 'delegatedOrganizationRefusal')]; } diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 88646abbe3e..1f0b8a78456 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -3821,19 +3821,19 @@ export class SecurityPlugin implements Plugin { * operation prologue, explain): those keep resolving their own. */ private resolveDelegatorForContext(context: any): Promise { - if (!context || typeof context !== 'object') return resolveDelegatorContext(this.ql, context); - const key = JSON.stringify([ - context.onBehalfOf?.userId ?? null, - context.tenantId ?? null, - context.org_user_ids ?? null, - ]); - const hit = this.delegatorMemo.get(context); + // A primitive/absent context has no identity to key on: resolved, not kept. + const keyed = !!context && typeof context === 'object'; + const key = keyed + ? JSON.stringify([context.onBehalfOf?.userId ?? null, context.tenantId ?? null, context.org_user_ids ?? null]) + : ''; + const hit = keyed ? this.delegatorMemo.get(context) : undefined; if (hit && hit.epoch === this.epoch.current && hit.key === key) return hit.resolution; const resolution = resolveDelegatorContext(this.ql, context).then((resolved) => { if (resolved.kind !== 'resolved') return Object.freeze(resolved); for (const value of Object.values(resolved.context)) if (Array.isArray(value)) Object.freeze(value); return Object.freeze({ kind: 'resolved' as const, context: Object.freeze(resolved.context) }); }); + if (!keyed) return resolution; const entry = { epoch: this.epoch.current, key, resolution }; this.delegatorMemo.set(context, entry); resolution.catch(() => { From 04753f4b7aa41e3fff9d77182e0715d1c7d13d80 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 01:25:30 +0000 Subject: [PATCH 5/6] wip: pay the metadata load at collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- packages/runtime/src/mcp-list-objects-statements.pin.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts index 6e75acabb2c..9af31d8cc5f 100644 --- a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts +++ b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts @@ -52,6 +52,8 @@ import { AppPlugin } from './app-plugin.js'; import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; import { createDispatcherPlugin } from './dispatcher-plugin.js'; import { HttpDispatcher } from './http-dispatcher.js'; +// Paid at collection, not inside the boot's clock: the app plugin's reach loads it lazily. +import '@objectstack/metadata'; const BOOT_TIMEOUT = 180_000; const ORIGIN = 'http://localhost:3000'; From 1bf877186c3a56a634b4e56104d9924ddeb74210 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 02:29:43 +0000 Subject: [PATCH 6/6] test: compare list_objects answers with the delegator memo bypassed, in the same tree The answer-identity pin compared each caller's listing against sha256 values frozen from one main commit, so any later label, field or read opt-in change on main broke it. It now reads every caller twice in the tree under test, as shipped and with the delegator memo bypassed, and requires deep-equal answers. A CONTROL shows the bypassed readings still grow with the object count. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzmMRNkjCwvFhzunNc --- .../mcp-list-objects-statements.pin.test.ts | 166 ++++++++++-------- 1 file changed, 96 insertions(+), 70 deletions(-) diff --git a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts index 9af31d8cc5f..9bee500acd3 100644 --- a/packages/runtime/src/mcp-list-objects-statements.pin.test.ts +++ b/packages/runtime/src/mcp-list-objects-statements.pin.test.ts @@ -17,7 +17,7 @@ * the person's `sys_user` row, memberships, grants and positions, and then the * person's permission sets for a context object nobody had seen before, so the * per-context set memo never hit. Measured on `origin/main` 68972cd2 with this - * composition: 26 statements per listed object (2 questions x 13), so an + * composition: 22 statements per listed object (2 questions x 11), so an * environment owner listing about 170 objects paid thousands of round trips — * tens of seconds against a remote database. * @@ -26,18 +26,24 @@ * 1. ⭐ Statements per `list_objects` do not grow with the object count: the * same call, the same callers, before and after the environment gains * 140 objects, differ by at most {@link STATEMENT_SLACK}. - * 2. ⭐ The answers are the ones `origin/main` gave, byte for byte - * ({@link GOLDEN}, measured there): every caller, both sizes — the same - * objects, the same field counts, the same order, the same `sys_*` - * read opt-in verdicts. - * 3. CONTROL — `describe_object` answers the same, and costs no more. + * 2. ⭐ The answers are the ones the per-object resolution gives, in THIS + * tree: every caller, both sizes, is read twice — once as shipped and once + * with the delegator memo bypassed ({@link bypassingDelegatorMemo}, the + * per-object resolution `origin/main` 68972cd2 ran) — and the two answers + * are deep-equal: the same objects, the same field counts, the same order, + * the same `sys_*` read opt-in verdicts. Compared within one tree, not + * against a frozen hash, so a label or object `main` adds later moves + * both readings alike. + * 3. CONTROL — with the memo bypassed the delegated callers' statements DO + * grow with the object count, so pin 1 measures the memo and not a rig + * that cannot see the growth; `describe_object` answers the same both + * ways, at both sizes, and costs no more. * * Counted: every statement the SQL driver issues inside the call's own async * context (knex's `query` event), as the statements golden counts them. */ import { AsyncLocalStorage } from 'node:async_hooks'; -import { createHash } from 'node:crypto'; import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { ObjectKernel, assembleExecutionContext, type Plugin, type PluginContext } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; @@ -91,6 +97,30 @@ let engine: any; let app: any; let prevNodeEnv: string | undefined; let prevMcp: string | undefined; +let security: SecurityPlugin; + +/** + * Runs `fn` with the delegator memo bypassed: every + * `resolveDelegatorForContext` ask forgets what the context held and resolves + * afresh, as each object-schema read site did before the memo — the + * per-object resolution, in this tree, for the answer-identity comparison. + * Both read sites ask through the plugin instance, so an own-property + * override on it reaches them; it is removed whatever `fn` does. + */ +async function bypassingDelegatorMemo(fn: () => Promise): Promise { + const plugin = security as any; + const shipped = Object.getPrototypeOf(plugin).resolveDelegatorForContext; + expect(typeof shipped, 'precondition: the memo this bypasses exists').toBe('function'); + plugin.resolveDelegatorForContext = function (this: any, context: any) { + if (context && typeof context === 'object') this.delegatorMemo.delete(context); + return shipped.call(this, context); + }; + try { + return await fn(); + } finally { + delete plugin.resolveDelegatorForContext; + } +} /** The MCP service: records the bridge and caller the real `/mcp` entry hands it. */ const mcp: any = { @@ -187,24 +217,29 @@ async function describeObject(executionContext: Record, name: strin return { answer, statements: sql.length }; } -const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex'); +type Who = 'owner' | 'member' | 'ownerAgent' | 'memberAgent'; +type Mode = 'memo' | 'bypass'; +type Reading = { answer: any; statements: number }; -/** What a reading is compared on: how many objects, and the answer's bytes. */ -const fingerprint = (answer: { diagnosed: { objects: unknown[] } }) => ({ objects: answer.diagnosed.objects.length, sha256: digest(answer) }); +let callers: Record>; +/** `list_objects` per size, caller and mode. */ +const readings: Record>> = {}; +/** `describe_object pin_lo_000` per size, caller and mode. */ +const described: Record>> = {}; -let callers: Record<'owner' | 'member' | 'ownerAgent' | 'memberAgent', Record>; -const readings: Record> = {}; -const described: Record> = {}; +async function readOnce(ctx: Record) { + await listObjects(ctx); // warm: the session, the served metadata and the listing caches + return { list: await listObjects(ctx), describe: await describeObject(ctx, 'pin_lo_000') }; +} async function read(size: string) { readings[size] = {}; described[size] = {}; for (const [who, ctx] of Object.entries(callers)) { - await listObjects(ctx); // warm: the session, the served metadata and the listing caches - const { answer, statements: n } = await listObjects(ctx); - readings[size][who] = { ...fingerprint(answer), statements: n }; - const d = await describeObject(ctx, 'pin_lo_000'); - described[size][who] = { sha256: digest(d.answer), statements: d.statements }; + const memo = await readOnce(ctx); + const bypass = await bypassingDelegatorMemo(() => readOnce(ctx)); + readings[size][who] = { memo: memo.list, bypass: bypass.list }; + described[size][who] = { memo: memo.describe, bypass: bypass.describe }; } } @@ -222,7 +257,8 @@ beforeAll(async () => { await kernel.use(new AppPlugin(PIN_APP)); await kernel.use(new PlatformObjectsPlugin()); await kernel.use(new AuthPlugin({ secret: 'list-objects-statements-33179-pin-secret' })); - await kernel.use(new SecurityPlugin(appSecurityPluginOptions(PIN_APP))); + security = new SecurityPlugin(appSecurityPluginOptions(PIN_APP)); + await kernel.use(security); await kernel.use(new SharingServicePlugin()); await kernel.use(createRestApiPlugin({})); await kernel.use(createDispatcherPlugin({})); @@ -261,71 +297,58 @@ afterAll(async () => { else process.env.OS_MCP_SERVER_ENABLED = prevMcp; }, 60_000); -/** - * The answers `origin/main` 68972cd2 gave on this composition, before the - * delegator memo: per caller and size, the listed object count and the - * sha256 of the whole answer (the diagnosed listing and the `sys_*` read - * opt-in verdicts) — and, for `describe_object`, of its answer. Measured by - * this file's own readings at that commit. - * - * The statements `origin/main` paid there, for the record (not asserted — - * {@link STATEMENT_SLACK} is): `ownerAgent` 1540 at 10 objects and 4620 at - * 150, `memberAgent` 1260 and 3780; `describe_object` 22 and 18; the two - * session callers 0. +/* + * The statements `origin/main` 68972cd2 paid on this composition, for the + * record (not asserted — the bypassed readings below re-measure them in the + * tree under test): `ownerAgent` 1540 at 10 objects and 4620 at 150, + * `memberAgent` 1260 and 3780; `describe_object` 22 and 18; the two session + * callers 0. */ -const GOLDEN = { - list: { - 10: { - owner: { objects: 68, sha256: '304fb285b8c37106383843881c205155106c18037979f0720a0e3e921e196332' }, - member: { objects: 29, sha256: '1c5b772ff78f4bc882df5692d40800ad5f130e2cab755e4227f027b8590da93d' }, - ownerAgent: { objects: 49, sha256: 'f4e77a4d252e88493df36c4d01369efeb8ad5c431edeaa2bc3ec9c014e1800dc' }, - memberAgent: { objects: 23, sha256: '6e73539aaedd9f3612896c867f621327273103a626633c62b14eb41735af2a1c' }, - }, - 150: { - owner: { objects: 208, sha256: '9edb5243e5bcdf3fa149420ad5799e6360ec8eea1df5349368678058c2c58e0d' }, - member: { objects: 29, sha256: '1c5b772ff78f4bc882df5692d40800ad5f130e2cab755e4227f027b8590da93d' }, - ownerAgent: { objects: 189, sha256: 'd03424429fc1b2502e1c07604d17689b22b6adce7991282935a52e38902e9fd6' }, - memberAgent: { objects: 23, sha256: '6e73539aaedd9f3612896c867f621327273103a626633c62b14eb41735af2a1c' }, - }, - }, - describe: { - owner: 'f61a6720fe797e325ff07a4fdf61571fe993ed13d1e3cc40743b4ae7712fb705', - member: '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', - ownerAgent: 'f61a6720fe797e325ff07a4fdf61571fe993ed13d1e3cc40743b4ae7712fb705', - memberAgent: '74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b', - }, - /** `describe_object`'s statements on `origin/main` for the two delegated callers. */ - describeStatements: { ownerAgent: 22, memberAgent: 18 }, -} as const; -const WHO = ['owner', 'member', 'ownerAgent', 'memberAgent'] as const; +const WHO: readonly Who[] = ['owner', 'member', 'ownerAgent', 'memberAgent']; +const DELEGATED = ['ownerAgent', 'memberAgent'] as const; +const count = (r: Reading) => r.answer.diagnosed.objects.length; +const record = (who: string) => JSON.stringify(Object.fromEntries(['10', '150'].map((s) => [s, { + memo: { objects: count(readings[s][who].memo), statements: readings[s][who].memo.statements }, + bypass: { objects: count(readings[s][who].bypass), statements: readings[s][who].bypass.statements }, +}]))); describe('[ADR-0090 D10] MCP list_objects statements do not grow with the object count (real kernel)', () => { it('precondition: the environment grew from 10 to 150 objects, and the owner\'s agent is listed every one', () => { - expect(readings['150'].owner.objects - readings['10'].owner.objects).toBe(140); - expect(readings['150'].ownerAgent.objects - readings['10'].ownerAgent.objects).toBe(140); + expect(count(readings['150'].owner.memo) - count(readings['10'].owner.memo)).toBe(140); + expect(count(readings['150'].ownerAgent.memo) - count(readings['10'].ownerAgent.memo)).toBe(140); }); for (const who of WHO) { it(`⭐ ${who}: statements per list_objects at 150 objects are those at 10, within ${STATEMENT_SLACK}`, () => { - const grown = readings['150'][who].statements - readings['10'][who].statements; - expect(Math.abs(grown), JSON.stringify({ 10: readings['10'][who], 150: readings['150'][who] })).toBeLessThanOrEqual(STATEMENT_SLACK); + const grown = readings['150'][who].memo.statements - readings['10'][who].memo.statements; + expect(Math.abs(grown), record(who)).toBeLessThanOrEqual(STATEMENT_SLACK); }); } - it('⭐ the delegated callers pay their delegator once, not once per object: at most one describe_object\'s worth', () => { - for (const who of ['ownerAgent', 'memberAgent'] as const) { - expect(readings['150'][who].statements, who).toBeLessThanOrEqual(GOLDEN.describeStatements[who]); + it('CONTROL: with the memo bypassed, the delegated callers\' statements grow with the object count', () => { + // The owner's agent is listed 140 more objects, two delegator reads each. + expect(readings['150'].ownerAgent.bypass.statements - readings['10'].ownerAgent.bypass.statements, record('ownerAgent')) + .toBeGreaterThanOrEqual(140 * 2); + // The member's agent is listed no new object, yet is still asked of each. + expect(readings['150'].memberAgent.bypass.statements, record('memberAgent')) + .toBeGreaterThan(readings['10'].memberAgent.bypass.statements + STATEMENT_SLACK); + }); + + it('⭐ the delegated callers pay their delegator once, not once per object: at most one bypassed describe_object\'s worth', () => { + for (const who of DELEGATED) { + expect(readings['150'][who].memo.statements, record(who)).toBeLessThanOrEqual(described['150'][who].bypass.statements); } }); }); -describe('[ADR-0106 D1/D5, ruling record 6787890900] the answers are origin/main\'s, byte for byte', () => { +describe('[ADR-0106 D1/D5, ruling record 6787890900] the answers are the per-object resolution\'s, in this tree', () => { for (const size of ['10', '150'] as const) { for (const who of WHO) { - it(`⭐ ${who} at ${size} objects: list_objects lists what it listed before, in the same order`, () => { - const { objects, sha256 } = readings[size][who]; - expect({ objects, sha256 }).toEqual(GOLDEN.list[size][who]); + it(`⭐ ${who} at ${size} objects: list_objects lists what the per-object resolution lists, in the same order`, () => { + const { memo, bypass } = readings[size][who]; + expect(count(memo), 'precondition: the caller is listed objects').toBeGreaterThan(0); + expect(memo.answer).toEqual(bypass.answer); }); } } @@ -333,10 +356,13 @@ describe('[ADR-0106 D1/D5, ruling record 6787890900] the answers are origin/main describe('CONTROL — describe_object', () => { for (const who of WHO) { - it(`${who}: the same answer at both sizes, the one origin/main gave, for no more statements`, () => { - expect(described['10'][who].sha256).toBe(GOLDEN.describe[who]); - expect(described['150'][who].sha256).toBe(GOLDEN.describe[who]); - expect(described['150'][who].statements).toBe(described['10'][who].statements); + it(`${who}: the same answer with and without the memo, at both sizes, for no more statements`, () => { + for (const size of ['10', '150'] as const) { + expect(described[size][who].memo.answer, size).toEqual(described[size][who].bypass.answer); + expect(described[size][who].memo.statements, size).toBeLessThanOrEqual(described[size][who].bypass.statements); + } + expect(described['150'][who].memo.answer).toEqual(described['10'][who].memo.answer); + expect(described['150'][who].memo.statements).toBe(described['10'][who].memo.statements); }); } });