Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/39001-strict-read-closure.md
Original file line number Diff line number Diff line change
@@ -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.
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol-meta-item-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -656,6 +657,8 @@ export async function getMetaItem(host: Pick<ProtocolHost, 'engine' | 'getServic
member?: string,
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
userTextLocales?: readonly string[],
/** [#39001] In-process only: the caller's per-pass publish closures (see {@link readMetaItem}). */
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
}) {
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. Folded
// HERE, at each face's boundary, as {@link getMetaItems} folds.
Expand Down Expand Up @@ -782,6 +785,18 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
member?: string,
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
userTextLocales?: readonly string[],
/**
* [#39001] One map per pass, for an in-process caller that reads several
* drafts in one answer (the open MCP door's draft list): the strict
* draft read's folded publish verdict takes its package's closure from
* it, collected on the first draft and reused for the rest, exactly as
* the caller's own judgements do (`draftPublishJudgement`'s
* `packageClosures`). Absent ⇒ collected on this read, as before. No
* wire door states it: every `/meta` and MCP read builds its request
* from named keys, and only a `Map` is honoured, which no JSON body or
* query string decodes to.
*/
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
}, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) {
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}.
request = canonicalizeMetaRequestType(request);
Expand Down Expand Up @@ -916,6 +931,12 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
// would still SAY: the gate's advisories, folded into
// `_diagnostics.warnings` ({@link withPublishAdvisories}) in the user
// sentence the request's locales pick, from the same single judgement.
// [#39001] …against the package closure the caller's map holds, when an
// in-process caller that judges several drafts in one pass hands one:
// the closure is a function of the package alone, so the verdict is the
// one this read folds without it, at one collection per package per pass
// instead of one per draft read.
const packageClosures = request.packageClosures instanceof Map ? request.packageClosures : undefined;
const serveDraft = async <T>(resolved: T, row: { metadata?: unknown; package_id?: string | null }): Promise<T> => {
const served = await serveViewLint(serveItem(resolved));
if (execution || !served || typeof served !== 'object') return served;
Expand All @@ -925,6 +946,7 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
body: storedRowDocument(row),
packageId: row.package_id ?? null,
...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}),
...(packageClosures ? { packageClosures } : {}),
});
const before = (served as { _diagnostics?: MetadataDiagnostics })._diagnostics;
const refused = withPublishVerdict(request.type, request.name, before, judgement.refusals);
Expand Down
7 changes: 7 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4162,6 +4162,13 @@ export class ObjectStackProtocolImplementation implements
member?: string,
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
userTextLocales?: readonly string[],
/**
* [#39001] In-process only, never a wire key: a caller judging several
* drafts in one pass hands its per-pass closure map, so the strict
* draft read's folded verdict collects each package's closure once
* (`readMetaItem`'s `packageClosures`). Absent ⇒ as before.
*/
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
}) {
// [#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`).
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string>(),
});

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<string, unknown>) {
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<string, unknown> = {}) {
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);
});
});
6 changes: 3 additions & 3 deletions packages/runtime/src/domains/mcp-authoring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime/src/domains/mcp-authoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<NonNullable<OpenAuthoringProtocol['getMetaItem']>>[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 } };
Expand Down
Loading