diff --git a/.changeset/39001-strict-read-closure.md b/.changeset/39001-strict-read-closure.md new file mode 100644 index 00000000000..67e1033e643 --- /dev/null +++ b/.changeset/39001-strict-read-closure.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +--- + +fix(metadata-protocol): a `list_drafts` verdict no longer re-collects its package for every draft + +Clause-②: yes (widening: the exported `ObjectStackProtocolImplementation#getMetaItem` request type gains one optional in-process member, `packageClosures`; a caller that omits it behaves exactly as before) +Metadata-protocol: none + +The open MCP draft door's `list_drafts` judges each draft with a strict draft read and a publish judgement. The judgements already shared one publish closure per package (the package's other drafts), but the strict draft read folded its own publish verdict into `_diagnostics` without it, so it collected the whole package again for every draft. One verdict cost about 25 + P queries, where P is the number of drafts in the package, and a whole list P × (25 + P). + +`ObjectStackProtocolImplementation#getMetaItem` now takes an in-process `packageClosures` map, the one `draftPublishJudgement` already takes, and hands it to the strict draft read's folded judgement. The door passes the map its judgements use, so the closure is collected once per package per `list_drafts` call. Measured on SQLite, one package: 10 drafts 352 → 242 queries, 50 drafts 3752 → 1202, 100 drafts (50 judged under the door's cap) 6302 → 1252; about 23 queries per verdict whatever the package's size, plus one collection of the package. + +Nothing a caller can send over the wire changes. The key is not read from any HTTP or MCP request, and only a `Map` is taken, which no JSON body or query string decodes to. A `/meta` draft read names no map: it collects its own closure on every read and folds the same `_diagnostics` as before. A map lives for one `list_drafts` call; nothing is kept between calls. diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 8109df4c61f..ecce0fb16d9 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -43,6 +43,7 @@ import { withViewLintWarnings, } from './metadata-diagnostics.js'; import { noPendingDraftError } from './protocol-authoring-refusals.js'; +import type { RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { bundleMemberDiscriminator, memberOption, @@ -656,6 +657,8 @@ export async function getMetaItem(host: Pick>, }) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. Folded // HERE, at each face's boundary, as {@link getMetaItems} folds. @@ -782,6 +785,18 @@ export async function readMetaItem(host: Pick>, }, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. request = canonicalizeMetaRequestType(request); @@ -916,6 +931,12 @@ export async function readMetaItem(host: Pick(resolved: T, row: { metadata?: unknown; package_id?: string | null }): Promise => { const served = await serveViewLint(serveItem(resolved)); if (execution || !served || typeof served !== 'object') return served; @@ -925,6 +946,7 @@ export async function readMetaItem(host: Pick>, }) { // [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`. // [ADR-0159 D7] A `view` read serves lists only, in every state it serves (`getServedMetaItem`). diff --git a/packages/runtime/src/domains/mcp-authoring-39001-strict-read-closure.test.ts b/packages/runtime/src/domains/mcp-authoring-39001-strict-read-closure.test.ts new file mode 100644 index 00000000000..62ba44accc1 --- /dev/null +++ b/packages/runtime/src/domains/mcp-authoring-39001-strict-read-closure.test.ts @@ -0,0 +1,201 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39001] A `list_drafts` verdict costs a bounded number of queries per draft, + * whatever the size of the draft's package. + * + * Each verdict is a strict draft read (`getMetaItem` with `state: 'draft'`), + * which folds its own publish verdict into `_diagnostics`, then the door's + * publish judgement. Both judge the draft against its package's publish + * closure (the package's other drafts: one `listDrafts` and one `repo.get` per + * closure-relevant draft). The door shared one closure per package between its + * judgements, but the strict read collected the closure again on every draft, + * so one verdict cost about 25 + P queries and a whole list P × (25 + P). The + * door now hands its map to the strict read too: the closure is collected once + * per `list_drafts` call, and each further draft adds the same number of + * queries. + * + * A single `/meta` draft read names no map: it collects its own closure on + * every read, as before, and folds the same `_diagnostics`. + * + * The metadata protocol is the real one over a real SQLite store; the queries + * counted are the driver's `find`, `findOne` and `count`. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { + SysMetadataAuditObject, + SysMetadataCommitObject, + SysMetadataHistoryObject, + SysMetadataObject, +} from '@objectstack/metadata-core'; +import { + createOpenAuthoringRegistry, + type OpenAuthoringProtocol, + type OpenAuthoringReadGateSources, +} from './mcp-authoring.js'; + +const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' }; +const STUDIO = 'com.example.crm_studio'; + +const AUTHOR_READ_GATE: OpenAuthoringReadGateSources = (protocol) => ({ + resolveCaller: async () => ({ userId: 'u1', systemPermissions: ['manage_metadata'], mayWriteItem: true }), + resolveSecurityService: async () => undefined, + listMetaItems: (type) => protocol.getMetaItems?.({ type }), + serviceProbe: () => null, + navPruneLogged: new Set(), +}); + +let cleanup: Array<() => void> = []; +afterEach(() => { + for (const c of cleanup.reverse()) c(); + cleanup = []; + vi.restoreAllMocks(); +}); + +/** The real protocol over SQLite, an authored package installed, the driver's reads counted. */ +async function realProtocol() { + const dir = mkdtempSync(join(tmpdir(), 'os-39001-')); + cleanup.push(() => rmSync(dir, { recursive: true, force: true })); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + const platform = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject] as any[]; + await driver.initObjects(platform); + const engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + for (const o of platform) engine.registry.registerObject(o, '@objectstack/platform-objects'); + engine.registry.installPackage({ id: STUDIO, name: 'CRM Studio', version: '1.0.0', type: 'app' } as any, 'authored'); + cleanup.push(() => { void engine.destroy(); }); + const protocol = new ObjectStackProtocolImplementation(engine as any) as unknown as OpenAuthoringProtocol; + let queries = 0; + for (const method of ['find', 'findOne', 'count'] as const) { + const original = (driver as any)[method].bind(driver); + (driver as any)[method] = (...args: unknown[]) => { + queries += 1; + return original(...args); + }; + } + return { protocol, queries: () => queries }; +} + +async function saveDraft(protocol: OpenAuthoringProtocol, type: string, name: string, item: Record) { + const saved: any = await protocol.saveMetaItem!({ type, name, item, packageId: STUDIO, mode: 'draft', actor: 'u1' } as any); + expect(saved?.state, JSON.stringify(saved)).toBe('draft'); +} + +/** `count` object drafts in the authored package. */ +async function saveObjectDrafts(protocol: OpenAuthoringProtocol, count: number) { + for (let i = 0; i < count; i++) { + const name = `crm_studio_thing_${i}`; + await saveDraft(protocol, 'object', name, { name, label: `Thing ${i}`, fields: { name: { type: 'text', label: 'Name' } } }); + } +} + +/** A list view draft bound to `object`. */ +async function saveViewDraft(protocol: OpenAuthoringProtocol, object: string) { + const name = `${object}.all`; + await saveDraft(protocol, 'view', name, { name, label: name, object, viewKind: 'list', config: { type: 'grid', columns: ['name'] } }); + return name; +} + +/** The strict draft read of one view, as `/meta` reads it. */ +async function readDraftView(protocol: OpenAuthoringProtocol, name: string, extra: Record = {}) { + const read: any = await protocol.getMetaItem!({ type: 'view', name, state: 'draft', packageId: STUDIO, ...extra } as any); + return read.item._diagnostics; +} + +async function listDrafts(protocol: OpenAuthoringProtocol) { + const registry = createOpenAuthoringRegistry({ + admitted: true, + userId: 'u1', + getProtocol: async () => protocol, + readGate: AUTHOR_READ_GATE, + logger: { warn: () => {} }, + }); + const result = await registry.execute({ toolCallId: 't', toolName: 'list_drafts', input: { package: STUDIO } }, CONTEXT); + return JSON.parse(result.output.value); +} + +/** The queries one `list_drafts` call over `count` drafts in one package makes. */ +async function listQueries(count: number) { + const { protocol, queries } = await realProtocol(); + await saveObjectDrafts(protocol, count); + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + const before = queries(); + const listed = await listDrafts(protocol); + const spent = queries() - before; + expect(listed.count).toBe(count); + expect(listed.judged).toBe(count); + return { spent, collected: collect.mock.calls.length, listed }; +} + +describe('[#39001] a list_drafts verdict costs the same queries whatever the size of its package', () => { + it('each further draft in the package adds the same number of queries, and the closure is collected once', async () => { + const small = await listQueries(4); + const medium = await listQueries(8); + const large = await listQueries(16); + // A cost that grows with the package grows faster than the package: the + // second step (8 → 16 drafts) would cost more than twice the first (4 → 8). + const firstStep = medium.spent - small.spent; + const secondStep = large.spent - medium.spent; + expect(secondStep, `4 → ${small.spent}, 8 → ${medium.spent}, 16 → ${large.spent} queries`).toBe(2 * firstStep); + // One collection of the package's closure per call, shared by the strict + // reads and the judgements. + for (const run of [small, medium, large]) expect(run.collected).toBe(1); + }); +}); + +describe('[#39001] a single /meta draft read, which names no map, folds the verdict it folded before', () => { + /** + * A view draft bound to an object that exists only as a draft of the same + * package is inside the package's closure; one bound to an object nowhere is + * outside it. Both verdicts come from the closure the read collects. + */ + async function fixture() { + const { protocol } = await realProtocol(); + await saveObjectDrafts(protocol, 2); + const inside = await saveViewDraft(protocol, 'crm_studio_thing_0'); + const outside = await saveViewDraft(protocol, 'crm_studio_nowhere'); + return { protocol, inside, outside }; + } + + it('collects its own closure on every read, and folds the closure\'s verdict', async () => { + const { protocol, inside, outside } = await fixture(); + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + + expect(await readDraftView(protocol, inside)).toEqual({ valid: true }); + const refused = await readDraftView(protocol, outside); + expect(refused.valid).toBe(false); + expect(refused.errors.map((e: any) => [e.code, e.path])).toEqual([['list-view-object-outside-closure', 'object']]); + // One collection per read: nothing is kept from one read to the next. + expect(collect).toHaveBeenCalledTimes(2); + expect(await readDraftView(protocol, inside)).toEqual({ valid: true }); + expect(collect).toHaveBeenCalledTimes(3); + }); + + it('a read handed a map folds the same verdict, and a second read takes the closure the first collected', async () => { + const { protocol, inside, outside } = await fixture(); + const alone = { inside: await readDraftView(protocol, inside), outside: await readDraftView(protocol, outside) }; + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + const packageClosures = new Map(); + expect(await readDraftView(protocol, inside, { packageClosures })).toEqual(alone.inside); + expect(await readDraftView(protocol, outside, { packageClosures })).toEqual(alone.outside); + expect(collect).toHaveBeenCalledTimes(1); + expect([...packageClosures.keys()]).toEqual([STUDIO]); + }); + + it('a packageClosures value that is not a Map, as a decoded body would carry, is not taken', async () => { + const { protocol, inside, outside } = await fixture(); + const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); + expect(await readDraftView(protocol, inside, { packageClosures: {} })).toEqual({ valid: true }); + expect((await readDraftView(protocol, outside, { packageClosures: 'x' })).errors.map((e: any) => e.code)) + .toEqual(['list-view-object-outside-closure']); + expect(collect).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index 82048aaeee3..9c152c3d391 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -1353,9 +1353,9 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations'); const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE }); expect(listed.body.count).toBe(3); - // Each strict draft read collects for the verdict it folds into its own - // `_diagnostics`; the door's judgements share one collection per package. - expect(collect).toHaveBeenCalledTimes(names.length + 1); + // [#39001] The strict draft reads (for the verdict each folds into its own + // `_diagnostics`) and the door's judgements share one collection per package. + expect(collect).toHaveBeenCalledTimes(1); // Each draft judged alone, one closure collection per call: the same verdict. collect.mockClear(); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 7a84b160715..b2f2ef0cdbb 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -1178,12 +1178,17 @@ export function createOpenAuthoringRegistry(opts: { if (typeRefused) return { verdict: null, verdictWithheld: typeRefused }; // A package-unbound draft is read without a package: the strict // draft read's own address resolution then names it. + // [#39001] The read folds its own publish verdict into + // `_diagnostics` against the same package closure as the + // judgement below, so it takes the same map: one collection + // per package for the whole list, not one per draft read. const read = await p.getMetaItem!({ type: draft.type, name: draft.name, state: 'draft', ...(draft.packageId ? { packageId: draft.packageId } : {}), ...(draft.member !== undefined ? { member: draft.member } : {}), + packageClosures, } as Parameters>[0]); if (read?.item === undefined || read.item === null) { return { verdict: null, verdictWithheld: { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } };