Skip to content

Commit 7814822

Browse files
fix(metadata-protocol): a list_drafts verdict no longer re-collects its package closure per draft (#39048)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBG4YD4RMAt72Ga5PdYYZDAQ)_ Fixes #39001 Claim for this branch: #39001 comment 7334650660 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 ## 维护者速读 - 用户能看到什么变化:助手调用「列出草稿」时,每份草稿的发布检查不再把整个应用包的草稿重读一遍;包越大省得越多,同样 20 秒内能检查完的草稿更多(见下表)。检查结论与改动前完全一样。 - 为什么做:云端搭建能力的「列出草稿」第二阶段修复,替在一个包里积累了大量草稿的客户去掉查询数随包大小成平方增长的问题;上一轮已给检查加了数量与时间上限,这一轮去掉上限之下的重复读取。 - 出错会怎样:最坏情况是列出草稿时的检查结论与单独打开草稿时不一致;测试已逐份比对两者相同。改动只在服务端,撤回这个合并即可恢复原样。 - 要你做什么:无。 | 包内草稿数 | 改动前查询数 | 改动后查询数 | 每份草稿(前 → 后) | |--:|--:|--:|--:| | 10 | 352 | 242 | 35.2 → 24.2 | | 50 | 3752 | 1202 | 75.0 → 24.0 | | 100(上限只检查 50 份) | 6302 | 1252 | 126.0 → 25.0 | ## What changes `list_drafts` judges each draft with `gatedDraftVerdict`: type admission, a strict draft read (`getMetaItem` with `state: 'draft'`), the item gate, then `draftPublishJudgement`. The judgement already took the door's per-call `packageClosures` map, so the package's publish closure (one `listDrafts` plus one `repo.get` per closure-relevant draft) was collected once for the judgements. The strict read did not: its `serveDraft` folds its own publish verdict into `_diagnostics` by calling `draftPublishJudgement` with no map, so it collected the closure again for every draft. One verdict cost about 25 + P queries. - `packages/metadata-protocol`: `getMetaItem` (the public method, and the `getMetaItem` / `readMetaItem` bodies in `protocol-meta-item-reads.ts`) takes an optional in-process `packageClosures` map, the same type `draftPublishJudgement` takes. `serveDraft` hands it to its folded judgement. Only a `Map` instance is taken. Absent, the read collects its own closure, as before. - `packages/runtime` (`gatedDraftVerdict` only): the strict draft read gets the same map the judgement gets. ### Design points 1. **Route: (a).** The strict read takes the caller's map. (b), reusing the read's folded verdict instead of judging twice, would need the read to hand back the raw judgement: `_diagnostics` holds the refusals as diagnostics without their `hint`, and the door answers each finding whole (`verdictOf`). That means a new key on the read's answer (an output widening on a wire-served method) or parsing `_diagnostics` back, so (b) and (c) are out. What remains per verdict, traced on the driver for one draft: 1 served-row read for the strict read, 1 write-head read plus 1 stored-row read (`repo.get`) for the door's body-less judgement, and 10 stored-collection reads for each of the two judgements (`foldStoredCollection`: object, permission, book, dataset, flow, each in singular and plural spelling): about 23 per draft. Plus, once per call, the list read and the closure (1 + P). None of the per-draft part depends on P. 2. **Reach.** No wire door can state the key. Every `/meta` read (`packages/rest` `meta-item-read-routes.ts`, `rest-server.ts`, `meta-qualified-item-route.ts`; `packages/runtime` `domains/meta.ts`) and the MCP `get_metadata_item` read builds its `getMetaItem` request from named keys; none spreads a query or body into it (checked with `git grep` over `packages/**`). On top of that, `serveDraft` takes the value only when it is a `Map`, which no JSON body or query string decodes to; a test pins that `{}` and a string are not taken. No tool or route input changes. The exported TypeScript request type of `getMetaItem` does gain the optional member, so Clause-② reads `yes (widening)` (L1 review 7335931058). 3. **Staleness.** The map is created inside one `list_drafts` call and dropped with it, as before. The strict draft read is never served from the compiled-answer cache (`cacheableRequest` refuses any request with `state`), and a read with no map collects on every read (pinned: three reads, three collections). 4. **Ordering with #39022.** `overlap-check.mjs` on this head: the branch merges textually clean with origin/main and with #39022's head (they share `mcp-authoring.ts` and `mcp-authoring.test.ts`; this branch edits only `gatedDraftVerdict` and the closure-count pin, #39022 the `get_metadata_item` description and branch). I expect no conflict. The branch merges origin/main again once #39022 lands, before it leaves draft. ### Read first (by risk) 1. `packages/metadata-protocol/src/protocol-meta-item-reads.ts`: the `packageClosures` guard and the `serveDraft` judgement call. The risky part is the read-path change for every strict draft read; with no map the call is byte-for-byte the old one. 2. `packages/runtime/src/domains/mcp-authoring.ts`: `gatedDraftVerdict`'s `getMetaItem` call now carries the map. 3. `packages/runtime/src/domains/mcp-authoring-39001-strict-read-closure.test.ts`: the per-draft query pin and the single-read pins. ### Two-minute check `pnpm --filter @objectstack/metadata-protocol build && pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/mcp-authoring-39001-strict-read-closure.test.ts`, expected: 4 passed. On origin/main the first case fails with `4 → 118, 8 → 266, 16 → 658 queries: expected 392 to be 296`. ## Tests - New `packages/runtime/src/domains/mcp-authoring-39001-strict-read-closure.test.ts`, the real `ObjectStackProtocolImplementation` over better-sqlite3, through `createOpenAuthoringRegistry`, counting the driver's `find` / `findOne` / `count`: - the per-draft cost is constant: going from 8 to 16 drafts costs exactly twice what going from 4 to 8 costs, and the closure is collected once per call. On origin/main: 4 → 118, 8 → 266, 16 → 658 (red). On this branch: green. - a single `/meta` draft read with no map: a view draft bound to an object that exists only as a sibling draft folds `{ valid: true }`; one bound to an object nowhere folds `list-view-object-outside-closure` on `object`; each read collects its own closure (3 reads, 3 collections). Green on origin/main and on this branch: the verdict did not change. - a read handed a map folds the same `_diagnostics` as without one, and a second read takes the closure the first collected. - a `packageClosures` value that is not a `Map` is not taken. - `mcp-authoring.test.ts`: the existing closure-count pin goes from `names.length + 1` collections to `1`. Its other half, each listed verdict equal to the draft judged alone, still holds. <details><summary>Ablation (fix removed from the protocol, rebuilt)</summary> - Mutation: `node scripts/ablation-replace.mjs --delete --hold` on the `...(packageClosures ? { packageClosures } : {}),` line of `serveDraft` (anchor 1 → 0, blob ecce0fb → e48c568c5204); `pnpm --filter @objectstack/metadata-protocol build`; `ablation-dist-preflight.mjs --absent` passed (the runtime suite reads metadata-protocol through `dist/`). - Result: 2 failed, 2 passed. `4 → 118, 8 → 266, 16 → 658 queries: expected 392 to be 296` and `expected "collectBatchPendingDeclarations" to be called 1 times, but got 2 times`. The two single-read pins stayed green, as they should. - Restore: `ablation-replace.mjs --restore`: blob == HEAD (ecce0fb), `git diff HEAD` empty; rebuilt; `ablation-dist-preflight.mjs` found the marker present in 2 built files. </details> <details><summary>Measurement (P object drafts in one authored package, one list_drafts call)</summary> | P | judged | queries before | queries after | per verdict before | per verdict after | closure collections before → after | |--:|--:|--:|--:|--:|--:|--:| | 10 | 10 | 352 | 242 | 35.2 | 24.2 | 11 → 1 | | 50 | 50 | 3752 | 1202 | 75.0 | 24.0 | 51 → 1 | | 100 | 50 (door cap) | 6302 | 1252 | 126.0 | 25.0 | 51 → 1 | After: total = 1 (list) + (1 + P) (closure, once) + 23 × judged. </details> ## Verification Readings on `926ce2d055` unless noted (the test and gate runs were taken on `66622c7a64`; the one commit merged since then is origin/main's `c748e7dfd6`, which changes two gate scripts and no package). <details><summary>Package tests and typecheck</summary> - `pnpm --filter @objectstack/metadata-protocol typecheck`: exit 0. - `pnpm --filter @objectstack/metadata-protocol test`: 381 files passed, 9 skipped; 23940 tests passed, 45 skipped; exit 0. - `pnpm --filter @objectstack/runtime typecheck` (tsc plus `check:test-typecheck`): exit 0. - `pnpm --filter @objectstack/runtime exec vitest run --project local --maxWorkers=2 src/domains/mcp-authoring`: 3 files, 86 tests passed. - NOT MEASURED: the full `@objectstack/runtime` local suite. It did not finish inside the container's 10-minute foreground limit. `Test Core` runs it. </details> <details><summary>Derived gate families (dispatch-gates --commands, 76)</summary> - 75 run, exit 0. `check:closed-ceremony-text` exited 1 on the first run (`ENOBUFS`: its `git ls-files` read past the 1 MiB default buffer; origin/main lists 1048565 bytes, 11 under the limit, and this diff's two new files pushed it over). origin/main's `c748e7dfd6` fixed that script; re-run after the merge: exit 0. - NOT MEASURED: `check:dual-build-cjs-loads` (PREREQUISITE NOT MET: it reads every package's `dist/`, and 41 packages outside this diff are not built here). CI runs it. - `dispatch-gates --ran`: 76 derived, 75 run, 1 NOT-MEASURED, 0 UNRUN. </details> ## Acceptance notes - The list branch's comment in `list_drafts` ("one map collects it once per package for the judgements") is now incomplete: the reads take the map too. It sits outside `gatedDraftVerdict`, so this PR leaves it alone. - The 20 per-draft stored-collection reads (two judgements, 10 each) read environment-wide active rows that do not change during one `list_drafts` call. They do not grow with P; sharing them across a pass would be a separate change. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ)_ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzeatqKfTRUzTJVa9jQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 431f880 commit 7814822

6 files changed

Lines changed: 253 additions & 3 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
fix(metadata-protocol): a `list_drafts` verdict no longer re-collects its package for every draft
7+
8+
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)
9+
Metadata-protocol: none
10+
11+
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).
12+
13+
`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.
14+
15+
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.

‎packages/metadata-protocol/src/protocol-meta-item-reads.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
withViewLintWarnings,
4444
} from './metadata-diagnostics.js';
4545
import { noPendingDraftError } from './protocol-authoring-refusals.js';
46+
import type { RuntimePendingDeclarations } from './runtime-authoring-gate.js';
4647
import {
4748
bundleMemberDiscriminator,
4849
memberOption,
@@ -656,6 +657,8 @@ export async function getMetaItem(host: Pick<ProtocolHost, 'engine' | 'getServic
656657
member?: string,
657658
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
658659
userTextLocales?: readonly string[],
660+
/** [#39001] In-process only: the caller's per-pass publish closures (see {@link readMetaItem}). */
661+
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
659662
}) {
660663
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. Folded
661664
// HERE, at each face's boundary, as {@link getMetaItems} folds.
@@ -782,6 +785,18 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
782785
member?: string,
783786
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
784787
userTextLocales?: readonly string[],
788+
/**
789+
* [#39001] One map per pass, for an in-process caller that reads several
790+
* drafts in one answer (the open MCP door's draft list): the strict
791+
* draft read's folded publish verdict takes its package's closure from
792+
* it, collected on the first draft and reused for the rest, exactly as
793+
* the caller's own judgements do (`draftPublishJudgement`'s
794+
* `packageClosures`). Absent ⇒ collected on this read, as before. No
795+
* wire door states it: every `/meta` and MCP read builds its request
796+
* from named keys, and only a `Map` is honoured, which no JSON body or
797+
* query string decodes to.
798+
*/
799+
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
785800
}, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) {
786801
// #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}.
787802
request = canonicalizeMetaRequestType(request);
@@ -916,6 +931,12 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
916931
// would still SAY: the gate's advisories, folded into
917932
// `_diagnostics.warnings` ({@link withPublishAdvisories}) in the user
918933
// sentence the request's locales pick, from the same single judgement.
934+
// [#39001] …against the package closure the caller's map holds, when an
935+
// in-process caller that judges several drafts in one pass hands one:
936+
// the closure is a function of the package alone, so the verdict is the
937+
// one this read folds without it, at one collection per package per pass
938+
// instead of one per draft read.
939+
const packageClosures = request.packageClosures instanceof Map ? request.packageClosures : undefined;
919940
const serveDraft = async <T>(resolved: T, row: { metadata?: unknown; package_id?: string | null }): Promise<T> => {
920941
const served = await serveViewLint(serveItem(resolved));
921942
if (execution || !served || typeof served !== 'object') return served;
@@ -925,6 +946,7 @@ export async function readMetaItem(host: Pick<ProtocolHost, 'artifactLockLayerAt
925946
body: storedRowDocument(row),
926947
packageId: row.package_id ?? null,
927948
...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}),
949+
...(packageClosures ? { packageClosures } : {}),
928950
});
929951
const before = (served as { _diagnostics?: MetadataDiagnostics })._diagnostics;
930952
const refused = withPublishVerdict(request.type, request.name, before, judgement.refusals);

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4162,6 +4162,13 @@ export class ObjectStackProtocolImplementation implements
41624162
member?: string,
41634163
/** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */
41644164
userTextLocales?: readonly string[],
4165+
/**
4166+
* [#39001] In-process only, never a wire key: a caller judging several
4167+
* drafts in one pass hands its per-pass closure map, so the strict
4168+
* draft read's folded verdict collects each package's closure once
4169+
* (`readMetaItem`'s `packageClosures`). Absent ⇒ as before.
4170+
*/
4171+
packageClosures?: Map<string, Promise<RuntimePendingDeclarations | undefined>>,
41654172
}) {
41664173
// [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`.
41674174
// [ADR-0159 D7] A `view` read serves lists only, in every state it serves (`getServedMetaItem`).
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#39001] A `list_drafts` verdict costs a bounded number of queries per draft,
5+
* whatever the size of the draft's package.
6+
*
7+
* Each verdict is a strict draft read (`getMetaItem` with `state: 'draft'`),
8+
* which folds its own publish verdict into `_diagnostics`, then the door's
9+
* publish judgement. Both judge the draft against its package's publish
10+
* closure (the package's other drafts: one `listDrafts` and one `repo.get` per
11+
* closure-relevant draft). The door shared one closure per package between its
12+
* judgements, but the strict read collected the closure again on every draft,
13+
* so one verdict cost about 25 + P queries and a whole list P × (25 + P). The
14+
* door now hands its map to the strict read too: the closure is collected once
15+
* per `list_drafts` call, and each further draft adds the same number of
16+
* queries.
17+
*
18+
* A single `/meta` draft read names no map: it collects its own closure on
19+
* every read, as before, and folds the same `_diagnostics`.
20+
*
21+
* The metadata protocol is the real one over a real SQLite store; the queries
22+
* counted are the driver's `find`, `findOne` and `count`.
23+
*/
24+
25+
import { afterEach, describe, expect, it, vi } from 'vitest';
26+
import { mkdtempSync, rmSync } from 'node:fs';
27+
import { tmpdir } from 'node:os';
28+
import { join } from 'node:path';
29+
import { ObjectQL } from '@objectstack/objectql';
30+
import { SqlDriver } from '@objectstack/driver-sql';
31+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
32+
import {
33+
SysMetadataAuditObject,
34+
SysMetadataCommitObject,
35+
SysMetadataHistoryObject,
36+
SysMetadataObject,
37+
} from '@objectstack/metadata-core';
38+
import {
39+
createOpenAuthoringRegistry,
40+
type OpenAuthoringProtocol,
41+
type OpenAuthoringReadGateSources,
42+
} from './mcp-authoring.js';
43+
44+
const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' };
45+
const STUDIO = 'com.example.crm_studio';
46+
47+
const AUTHOR_READ_GATE: OpenAuthoringReadGateSources = (protocol) => ({
48+
resolveCaller: async () => ({ userId: 'u1', systemPermissions: ['manage_metadata'], mayWriteItem: true }),
49+
resolveSecurityService: async () => undefined,
50+
listMetaItems: (type) => protocol.getMetaItems?.({ type }),
51+
serviceProbe: () => null,
52+
navPruneLogged: new Set<string>(),
53+
});
54+
55+
let cleanup: Array<() => void> = [];
56+
afterEach(() => {
57+
for (const c of cleanup.reverse()) c();
58+
cleanup = [];
59+
vi.restoreAllMocks();
60+
});
61+
62+
/** The real protocol over SQLite, an authored package installed, the driver's reads counted. */
63+
async function realProtocol() {
64+
const dir = mkdtempSync(join(tmpdir(), 'os-39001-'));
65+
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
66+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true });
67+
const platform = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject] as any[];
68+
await driver.initObjects(platform);
69+
const engine = new ObjectQL();
70+
engine.registerDriver(driver as any, true);
71+
await engine.init();
72+
for (const o of platform) engine.registry.registerObject(o, '@objectstack/platform-objects');
73+
engine.registry.installPackage({ id: STUDIO, name: 'CRM Studio', version: '1.0.0', type: 'app' } as any, 'authored');
74+
cleanup.push(() => { void engine.destroy(); });
75+
const protocol = new ObjectStackProtocolImplementation(engine as any) as unknown as OpenAuthoringProtocol;
76+
let queries = 0;
77+
for (const method of ['find', 'findOne', 'count'] as const) {
78+
const original = (driver as any)[method].bind(driver);
79+
(driver as any)[method] = (...args: unknown[]) => {
80+
queries += 1;
81+
return original(...args);
82+
};
83+
}
84+
return { protocol, queries: () => queries };
85+
}
86+
87+
async function saveDraft(protocol: OpenAuthoringProtocol, type: string, name: string, item: Record<string, unknown>) {
88+
const saved: any = await protocol.saveMetaItem!({ type, name, item, packageId: STUDIO, mode: 'draft', actor: 'u1' } as any);
89+
expect(saved?.state, JSON.stringify(saved)).toBe('draft');
90+
}
91+
92+
/** `count` object drafts in the authored package. */
93+
async function saveObjectDrafts(protocol: OpenAuthoringProtocol, count: number) {
94+
for (let i = 0; i < count; i++) {
95+
const name = `crm_studio_thing_${i}`;
96+
await saveDraft(protocol, 'object', name, { name, label: `Thing ${i}`, fields: { name: { type: 'text', label: 'Name' } } });
97+
}
98+
}
99+
100+
/** A list view draft bound to `object`. */
101+
async function saveViewDraft(protocol: OpenAuthoringProtocol, object: string) {
102+
const name = `${object}.all`;
103+
await saveDraft(protocol, 'view', name, { name, label: name, object, viewKind: 'list', config: { type: 'grid', columns: ['name'] } });
104+
return name;
105+
}
106+
107+
/** The strict draft read of one view, as `/meta` reads it. */
108+
async function readDraftView(protocol: OpenAuthoringProtocol, name: string, extra: Record<string, unknown> = {}) {
109+
const read: any = await protocol.getMetaItem!({ type: 'view', name, state: 'draft', packageId: STUDIO, ...extra } as any);
110+
return read.item._diagnostics;
111+
}
112+
113+
async function listDrafts(protocol: OpenAuthoringProtocol) {
114+
const registry = createOpenAuthoringRegistry({
115+
admitted: true,
116+
userId: 'u1',
117+
getProtocol: async () => protocol,
118+
readGate: AUTHOR_READ_GATE,
119+
logger: { warn: () => {} },
120+
});
121+
const result = await registry.execute({ toolCallId: 't', toolName: 'list_drafts', input: { package: STUDIO } }, CONTEXT);
122+
return JSON.parse(result.output.value);
123+
}
124+
125+
/** The queries one `list_drafts` call over `count` drafts in one package makes. */
126+
async function listQueries(count: number) {
127+
const { protocol, queries } = await realProtocol();
128+
await saveObjectDrafts(protocol, count);
129+
const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations');
130+
const before = queries();
131+
const listed = await listDrafts(protocol);
132+
const spent = queries() - before;
133+
expect(listed.count).toBe(count);
134+
expect(listed.judged).toBe(count);
135+
return { spent, collected: collect.mock.calls.length, listed };
136+
}
137+
138+
describe('[#39001] a list_drafts verdict costs the same queries whatever the size of its package', () => {
139+
it('each further draft in the package adds the same number of queries, and the closure is collected once', async () => {
140+
const small = await listQueries(4);
141+
const medium = await listQueries(8);
142+
const large = await listQueries(16);
143+
// A cost that grows with the package grows faster than the package: the
144+
// second step (8 → 16 drafts) would cost more than twice the first (4 → 8).
145+
const firstStep = medium.spent - small.spent;
146+
const secondStep = large.spent - medium.spent;
147+
expect(secondStep, `4 → ${small.spent}, 8 → ${medium.spent}, 16 → ${large.spent} queries`).toBe(2 * firstStep);
148+
// One collection of the package's closure per call, shared by the strict
149+
// reads and the judgements.
150+
for (const run of [small, medium, large]) expect(run.collected).toBe(1);
151+
});
152+
});
153+
154+
describe('[#39001] a single /meta draft read, which names no map, folds the verdict it folded before', () => {
155+
/**
156+
* A view draft bound to an object that exists only as a draft of the same
157+
* package is inside the package's closure; one bound to an object nowhere is
158+
* outside it. Both verdicts come from the closure the read collects.
159+
*/
160+
async function fixture() {
161+
const { protocol } = await realProtocol();
162+
await saveObjectDrafts(protocol, 2);
163+
const inside = await saveViewDraft(protocol, 'crm_studio_thing_0');
164+
const outside = await saveViewDraft(protocol, 'crm_studio_nowhere');
165+
return { protocol, inside, outside };
166+
}
167+
168+
it('collects its own closure on every read, and folds the closure\'s verdict', async () => {
169+
const { protocol, inside, outside } = await fixture();
170+
const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations');
171+
172+
expect(await readDraftView(protocol, inside)).toEqual({ valid: true });
173+
const refused = await readDraftView(protocol, outside);
174+
expect(refused.valid).toBe(false);
175+
expect(refused.errors.map((e: any) => [e.code, e.path])).toEqual([['list-view-object-outside-closure', 'object']]);
176+
// One collection per read: nothing is kept from one read to the next.
177+
expect(collect).toHaveBeenCalledTimes(2);
178+
expect(await readDraftView(protocol, inside)).toEqual({ valid: true });
179+
expect(collect).toHaveBeenCalledTimes(3);
180+
});
181+
182+
it('a read handed a map folds the same verdict, and a second read takes the closure the first collected', async () => {
183+
const { protocol, inside, outside } = await fixture();
184+
const alone = { inside: await readDraftView(protocol, inside), outside: await readDraftView(protocol, outside) };
185+
const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations');
186+
const packageClosures = new Map();
187+
expect(await readDraftView(protocol, inside, { packageClosures })).toEqual(alone.inside);
188+
expect(await readDraftView(protocol, outside, { packageClosures })).toEqual(alone.outside);
189+
expect(collect).toHaveBeenCalledTimes(1);
190+
expect([...packageClosures.keys()]).toEqual([STUDIO]);
191+
});
192+
193+
it('a packageClosures value that is not a Map, as a decoded body would carry, is not taken', async () => {
194+
const { protocol, inside, outside } = await fixture();
195+
const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations');
196+
expect(await readDraftView(protocol, inside, { packageClosures: {} })).toEqual({ valid: true });
197+
expect((await readDraftView(protocol, outside, { packageClosures: 'x' })).errors.map((e: any) => e.code))
198+
.toEqual(['list-view-object-outside-closure']);
199+
expect(collect).toHaveBeenCalledTimes(2);
200+
});
201+
});

‎packages/runtime/src/domains/mcp-authoring.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1353,9 +1353,9 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl
13531353
const collect = vi.spyOn(protocol as any, 'collectBatchPendingDeclarations');
13541354
const listed = await call(authoring, 'list_drafts', { package: STUDIO_BASE });
13551355
expect(listed.body.count).toBe(3);
1356-
// Each strict draft read collects for the verdict it folds into its own
1357-
// `_diagnostics`; the door's judgements share one collection per package.
1358-
expect(collect).toHaveBeenCalledTimes(names.length + 1);
1356+
// [#39001] The strict draft reads (for the verdict each folds into its own
1357+
// `_diagnostics`) and the door's judgements share one collection per package.
1358+
expect(collect).toHaveBeenCalledTimes(1);
13591359

13601360
// Each draft judged alone, one closure collection per call: the same verdict.
13611361
collect.mockClear();

‎packages/runtime/src/domains/mcp-authoring.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,12 +1178,17 @@ export function createOpenAuthoringRegistry(opts: {
11781178
if (typeRefused) return { verdict: null, verdictWithheld: typeRefused };
11791179
// A package-unbound draft is read without a package: the strict
11801180
// draft read's own address resolution then names it.
1181+
// [#39001] The read folds its own publish verdict into
1182+
// `_diagnostics` against the same package closure as the
1183+
// judgement below, so it takes the same map: one collection
1184+
// per package for the whole list, not one per draft read.
11811185
const read = await p.getMetaItem!({
11821186
type: draft.type,
11831187
name: draft.name,
11841188
state: 'draft',
11851189
...(draft.packageId ? { packageId: draft.packageId } : {}),
11861190
...(draft.member !== undefined ? { member: draft.member } : {}),
1191+
packageClosures,
11871192
} as Parameters<NonNullable<OpenAuthoringProtocol['getMetaItem']>>[0]);
11881193
if (read?.item === undefined || read.item === null) {
11891194
return { verdict: null, verdictWithheld: { code: RESOURCE_NOT_FOUND, message: `No '${draft.type}' draft named '${draft.name}' is readable here.`, status: 404 } };

0 commit comments

Comments
 (0)