|
| 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 | +}); |
0 commit comments