diff --git a/.changeset/38965-list-drafts-bound.md b/.changeset/38965-list-drafts-bound.md new file mode 100644 index 00000000000..79d229cc28e --- /dev/null +++ b/.changeset/38965-list-drafts-bound.md @@ -0,0 +1,18 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): `list_drafts` answers in bounded time when many drafts are pending + +Clause-②: no +Metadata-protocol: none + +`list_drafts` on the MCP draft door (and on the in-process authoring tools that share it) used to judge every pending draft, one after another. Each verdict is a strict draft read and a publish judgement, and its cost grows with the size of the draft's package. With 500 drafts on a remote database the call never answered. Now: + +- Every pending draft is still listed, in the same order, with the same fields. +- One call judges at most 50 drafts, most recently saved first, and starts no new verdict once 20 seconds have passed since the call began. The verdict that is running when the time runs out still finishes. +- A draft that was not judged answers `verdict: null` with `verdictWithheld: { code: 'MAX_RECORDS_EXCEEDED', message, status: 400 }`. A withheld verdict already had this shape, and the console's draft review card shows it as "Verdict withheld". +- The answer gains `judged`, the number of drafts that were judged. When some were not, it also gains `notJudged`, a sentence that says how many were left out and to pass `package` to list fewer. +- The tool description says that verdicts are bounded and how to narrow the list. + +Nothing else changes: the input schema is the same, and a list under the bound answers as before, plus `judged`. diff --git a/packages/runtime/src/domains/mcp-authoring-38965-list-drafts-bound.test.ts b/packages/runtime/src/domains/mcp-authoring-38965-list-drafts-bound.test.ts new file mode 100644 index 00000000000..d598f698373 --- /dev/null +++ b/packages/runtime/src/domains/mcp-authoring-38965-list-drafts-bound.test.ts @@ -0,0 +1,148 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38965] `list_drafts` bounds its verdict work. With 500 pending drafts the + * door judged every one, one after another (a strict draft read and a publish + * judgement each), and on a remote database the call never answered. Every + * draft is still listed; at most `LIST_DRAFTS_VERDICT_CAP` are judged, most + * recently saved first, and none is started once + * `LIST_DRAFTS_VERDICT_BUDGET_MS` has passed. A draft past the bound answers + * `verdict: null` with a `verdictWithheld` reason, the shape the console's + * draft review row reads (`DraftReviewVerdictRefusalSchema`). + * + * The protocol is a stand-in that counts the two per-draft calls; the clock is + * `Date.now`, advanced by the stand-in, so no case sleeps. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { DraftReviewVerdictRefusalSchema } from '@objectstack/spec/ai'; +import { + LIST_DRAFTS_VERDICT_BUDGET_MS, + LIST_DRAFTS_VERDICT_CAP, + createOpenAuthoringRegistry, + type OpenAuthoringProtocol, + type OpenAuthoringReadGateSources, +} from './mcp-authoring.js'; + +const CONTEXT = { door: 'mcp' as const, principal: { userId: 'u1' }, environmentId: 'env_1' }; + +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(), +}); + +/** Draft `i` was saved at minute `i`: the last listed is the most recent. */ +const savedAt = (i: number) => new Date(Date.UTC(2026, 11, 1, 0, i)).toISOString(); + +/** + * `count` flow drafts, listed oldest first. `onRead` runs on every strict + * draft read, before it answers (the fake clock's tick). + */ +function standIn(count: number, onRead: () => void = () => {}) { + const reads: string[] = []; + const judgements: string[] = []; + const protocol: OpenAuthoringProtocol = { + async getMetaTypes() { + return { types: ['flow'] } as any; + }, + async listDrafts() { + return { + drafts: Array.from({ length: count }, (_, i) => ({ + type: 'flow', name: `flow_${i}`, label: `Flow ${i}`, packageId: 'com.acme.crm', updatedAt: savedAt(i), updatedBy: 'u1', + })), + } as any; + }, + async getMetaItem(request: any) { + reads.push(request.name); + onRead(); + return { type: 'flow', name: request.name, item: { name: request.name, label: request.name, _draft: true } } as any; + }, + async draftPublishJudgement(draft: any) { + judgements.push(draft.name); + return { refusals: [], advisories: [] }; + }, + }; + return { protocol, reads, judgements }; +} + +async function listDrafts(protocol: OpenAuthoringProtocol, input: unknown = {}) { + 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 }, CONTEXT); + return { isError: result.isError === true, body: JSON.parse(result.output.value) }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('[#38965] list_drafts bounds its verdict work and lists every draft', () => { + it('at 500 drafts it judges at most the cap, most recently saved first, and every other row says it was not judged', async () => { + const { protocol, reads, judgements } = standIn(500); + const listed = await listDrafts(protocol); + + expect(listed.isError).toBe(false); + // Every draft is listed, in the list's own order. + expect(listed.body.count).toBe(500); + expect(listed.body.drafts.map((d: any) => d.name)).toEqual(Array.from({ length: 500 }, (_, i) => `flow_${i}`)); + // The verdict work is bounded: one strict read and one judgement per judged draft. + expect(reads.length).toBe(LIST_DRAFTS_VERDICT_CAP); + expect(judgements.length).toBe(LIST_DRAFTS_VERDICT_CAP); + expect(listed.body.judged).toBe(LIST_DRAFTS_VERDICT_CAP); + expect(typeof listed.body.notJudged).toBe('string'); + + // The most recent drafts carry verdicts; the older ones do not. + const recent = new Set(Array.from({ length: LIST_DRAFTS_VERDICT_CAP }, (_, i) => `flow_${499 - i}`)); + expect(new Set(reads)).toEqual(recent); + for (const row of listed.body.drafts) { + if (recent.has(row.name)) { + expect(row.verdict, row.name).toEqual({ publishable: true, refusals: [], advisories: [] }); + expect('verdictWithheld' in row, row.name).toBe(false); + } else { + expect(row.verdict, row.name).toBeNull(); + expect(row.verdictWithheld, row.name).toMatchObject({ code: 'MAX_RECORDS_EXCEEDED', status: 400 }); + } + } + // A withheld row is one the console's draft review row accepts. + const withheld = listed.body.drafts.find((d: any) => d.verdict === null).verdictWithheld; + expect(DraftReviewVerdictRefusalSchema.safeParse(withheld).success).toBe(true); + }); + + it('starts no verdict once the time budget is spent, though the cap is not reached', async () => { + let now = 1_000_000; + vi.spyOn(Date, 'now').mockImplementation(() => now); + const tick = 3_000; + const { protocol, reads, judgements } = standIn(500, () => { now += tick; }); + const listed = await listDrafts(protocol); + + // Verdicts start at 0, 3, …, 18 s; at 21 s the budget is spent. + const started = Math.ceil(LIST_DRAFTS_VERDICT_BUDGET_MS / tick); + expect(started).toBeLessThan(LIST_DRAFTS_VERDICT_CAP); + expect(reads.length).toBe(started); + expect(judgements.length).toBe(started); + expect(listed.body.judged).toBe(started); + expect(listed.body.count).toBe(500); + expect(listed.body.drafts.filter((d: any) => d.verdict === null)).toHaveLength(500 - started); + for (const row of listed.body.drafts.filter((d: any) => d.verdict === null)) { + expect(row.verdictWithheld).toMatchObject({ code: 'MAX_RECORDS_EXCEEDED', status: 400 }); + } + expect(typeof listed.body.notJudged).toBe('string'); + }); + + it('under the bound every draft is judged and the answer carries no notJudged sentence', async () => { + const { protocol, reads } = standIn(3); + const listed = await listDrafts(protocol); + expect(listed.body).toMatchObject({ count: 3, judged: 3 }); + expect('notJudged' in listed.body).toBe(false); + expect(reads).toHaveLength(3); + expect(listed.body.drafts.every((d: any) => d.verdict !== null && !('verdictWithheld' in d))).toBe(true); + }); +}); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 3d9009bbfad..01bb9c76932 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -197,6 +197,32 @@ const VALIDATION_ERROR: ErrorCode = 'VALIDATION_ERROR'; const RESOURCE_NOT_FOUND: ErrorCode = 'RESOURCE_NOT_FOUND'; const SERVICE_UNAVAILABLE: ErrorCode = 'SERVICE_UNAVAILABLE'; const INTERNAL_ERROR: ErrorCode = 'INTERNAL_ERROR'; +/** + * [#38965] A listed draft `list_drafts` did not judge: the standard caller-side + * limit (the call asked for more verdicts than one call reads), whose remedy is + * the request's, a narrower list. + */ +const MAX_RECORDS_EXCEEDED: ErrorCode = 'MAX_RECORDS_EXCEEDED'; + +/** + * [#38965] The most drafts one `list_drafts` call judges. A verdict costs one + * strict draft read and one publish judgement, about 25 queries plus one per + * closure-relevant draft in its package (the strict read collects the package + * closure for its own `_diagnostics`), so the work of a whole list grows with + * the square of a package's size. The console's draft review card lists at + * most this many drafts a turn (`DRAFT_REVIEW_MAX`), so the drafts one turn + * saved fit under it, judged most recently saved first. + */ +export const LIST_DRAFTS_VERDICT_CAP = 50; + +/** + * [#38965] Once this many milliseconds have passed since the call began, + * `list_drafts` starts no new verdict. The cap alone is not a time bound: on a + * remote database a verdict in a large package takes seconds. The draft being + * judged when it runs out finishes, so the answer lands well inside an MCP + * client's default 60-second request timeout. + */ +export const LIST_DRAFTS_VERDICT_BUDGET_MS = 20_000; /** [#34774] The `@objectstack/spec` this process resolves (the version `initialize` states). */ const SERVER_SPEC_VERSION: string | undefined = (() => { @@ -329,7 +355,10 @@ const READ_TOOLS: readonly AIToolDefinition[] = Object.freeze([ 'List the pending metadata drafts in this environment: what was saved as a draft and is not ' + 'published yet. A person reviews and publishes drafts in Studio. Each draft carries its publish ' + 'verdict: `verdict.refusals` lists what a publish would refuse it on (rule id, path, hint), empty ' - + 'when it would publish. Pass `package` to list one package\'s drafts.', + + 'when it would publish. Pass `package` to list one package\'s drafts. ' + + `Every draft is listed, but one call judges at most ${LIST_DRAFTS_VERDICT_CAP} drafts, most recently ` + + `saved first, and starts none after ${LIST_DRAFTS_VERDICT_BUDGET_MS / 1000} seconds: \`judged\` counts them, ` + + 'and the rest answer `verdict: null` with `verdictWithheld`, so pass `package` to judge fewer.', parameters: { type: 'object', properties: { @@ -899,6 +928,8 @@ export function createOpenAuthoringRegistry(opts: { if (typeof protocol.draftPublishJudgement !== 'function' || typeof protocol.getMetaItem !== 'function') { return unavailable(); } + // [#38965] The verdict budget runs from here: the list read spends it too. + const began = Date.now(); const listed = await protocol.listDrafts(pkg ? { packageId: pkg } : {}); const drafts = Array.isArray(listed?.drafts) ? listed.drafts : []; // The list itself runs no item gate, as `/meta/_drafts` runs @@ -913,9 +944,59 @@ export function createOpenAuthoringRegistry(opts: { // The closure a draft is judged against is its package's alone, // so one map collects it once per package for the judgements. const packageClosures = new Map>(); - const judged = []; - for (const draft of drafts) judged.push({ ...draft, ...(await gatedDraftVerdict(protocol, draft, packageClosures)) }); - return answer({ count: judged.length, drafts: judged }); + // [#38965] That cost grows with a package's size, so a whole + // list of verdicts is bounded twice: at most + // LIST_DRAFTS_VERDICT_CAP drafts are judged, and none is + // started once LIST_DRAFTS_VERDICT_BUDGET_MS has passed. The + // most recently saved drafts are judged first (the ones the + // caller most likely just saved); a draft with no timestamp + // comes after every dated one, and ties keep the list's order. + // Verdicts run one after another: each reads the database, + // and running them side by side would multiply that load. + // Every draft is still listed, in the list's own order. + const recency = (draft: { updatedAt?: string | null }) => { + const at = typeof draft.updatedAt === 'string' ? Date.parse(draft.updatedAt) : Number.NaN; + return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at; + }; + const order = drafts.map((_, index) => index) + .sort((a, b) => (recency(drafts[b]!) - recency(drafts[a]!)) || a - b); + const verdicts: Array> | undefined> = []; + let judged = 0; + let budgetSpent = false; + for (const index of order) { + if (judged >= LIST_DRAFTS_VERDICT_CAP) break; + if (Date.now() - began >= LIST_DRAFTS_VERDICT_BUDGET_MS) { + budgetSpent = true; + break; + } + verdicts[index] = await gatedDraftVerdict(protocol, drafts[index]!, packageClosures); + judged += 1; + } + const unjudged = drafts.length - judged; + // A short reason on each row; the sentence that says how to + // get the rest is the answer's own, said once. + const notJudged = { + code: MAX_RECORDS_EXCEEDED, + message: budgetSpent + ? `Not judged: this call stopped starting verdicts after ${LIST_DRAFTS_VERDICT_BUDGET_MS / 1000} seconds.` + : `Not judged: one call judges at most ${LIST_DRAFTS_VERDICT_CAP} drafts.`, + status: 400, + }; + const rows = drafts.map((draft, index) => ({ ...draft, ...(verdicts[index] ?? { verdict: null, verdictWithheld: notJudged }) })); + // The counts ride ahead of the rows, so a reply cut short still says them. + return answer({ + count: rows.length, + judged, + ...(unjudged > 0 + ? { + notJudged: `${unjudged} of ${rows.length} drafts were not judged (${budgetSpent + ? `this call starts no verdict after ${LIST_DRAFTS_VERDICT_BUDGET_MS / 1000} seconds` + : `one call judges at most ${LIST_DRAFTS_VERDICT_CAP} drafts`}, most recently saved first): ` + + 'they answer `verdict: null` with `verdictWithheld`. Pass `package` to list fewer drafts and judge those.', + } + : {}), + drafts: rows, + }); } case 'save_metadata_draft': { if (typeof protocol?.saveMetaItem !== 'function' || typeof protocol.draftPublishJudgement !== 'function') {