Skip to content

Commit 73609d0

Browse files
test(mcp): drive the worker CPU-budget case from a stepping thread clock (#34853)
Fixes #34758 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:只改一个测试用例(`packages/mcp/src/mcp-file-tools.test.ts` 里 worker 的 CPU 预算用例),让它用"每读一次前进固定毫秒"的假线程时钟,不再和真实 CPU 赛跑;没有改任何会发布的代码。 - 为什么改:这个用例在不相关的 PR 上随机变红。实测红的原因不是 CPU 预算本身,而是 30 ms 预算带来的 150 ms 真实墙钟上限:机器一忙,worker 连第 1 页都没读完就被掐断,答出"after page 0 of 120"且没有文字。 - 风险与回滚:只涉及测试文件,生产行为逐字节不变;回滚即 revert 本 PR,用例回到原先会随负载变红的状态。 - 先看:`packages/mcp/src/mcp-file-tools.test.ts` 的 `steppingThreadCpuWorker` 辅助函数(注入点),以及紧随其后的用例里 3000 ms 预算与步长的取值说明。 - 两分钟验证:`pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-file-tools.test.ts -t 'out of CPU budget on the worker'`,预期 1 passed,且无论机器多忙,PDF 恒停在第 3 页、Word 恒停在 12800 段。 - 需要你做的:无,席位落地。 ## What changes The worker CPU-budget case in `packages/mcp/src/mcp-file-tools.test.ts` raced real time. It is now deterministic at the root, by a test-only seam that crosses the thread boundary, with no shipped file touched. - **What actually failed (measured).** CI's red (`content: "none"` at the case's first assertion) reproduces locally under synthetic load, and an instrumented run printed the answer: `Reading stopped at the CPU-time budget for one file (30 ms) after page 0 of 120, so the text is partial.` That is the pool's **wall-clock ceiling** (5 budgets of real time = 150 ms) cutting the read before page 1, not the CPU budget: a read stopped by the budget always carries page 1. So making the CPU clock controllable alone, at 30 ms, would leave the failure in place. - **The seam.** `steppingThreadCpuWorker(stepMs)` starts the source worker with one more `--import`: a `data:` URL preload that replaces `process.threadCpuUsage` **inside the worker thread** with a clock that advances `stepMs` on every read. It is the worker's twin of the in-process `steppingCpuClock`, which spies the request thread's `process.cpuUsage` and cannot reach a worker. `file-extraction-worker.ts` is unchanged and reads the clock it always reads. The preload is set per case through the existing `configureExtractionWorkerEntry`, which restarts the pool, and `afterEach` restores the built entry. - **The case now pins exact stop points**, not a 1..119 range: - PDF: budget 3000 ms, step 1000 ms. The budget is spent at the third checkpoint, so the answer is pages 1-3 with the exact note `(3000 ms) after page 3 of 120`. - Word: the same budget, step 15 ms. The budget is spent at the 200th checkpoint (every 64 paragraphs), so the read stops after 12800 paragraphs. That is past the 100,000-character cap, so the length-cap pin is real now. Before, it was a no-op whenever the count was small. - **Why 3000 ms and not 30.** The budget value no longer races anything: the stepping clock decides where the read stops. The value sets the real-time ceiling (15 s), far beyond any runner's stall. This does not widen the budget to get green. Truncation is pinned exactly, and the ablation below shows the case goes red without the clock. - The warm read is gone. A 1-page PDF never reaches a budget checkpoint, and worker start is outside the ceiling, so with a stepping clock it had nothing left to protect. No changeset: the only changed file is a `*.test.ts`. It is not a tsup entry and is excluded from the build tsconfig, and `@objectstack/mcp` ships `files: ["dist", "README.md", "CHANGELOG.md"]`. `skip-changeset` is declared on create. ## Tests <details><summary>Package suite and typecheck (head a5821d8)</summary> - `pnpm --filter @objectstack/mcp test` (under the verify lock): `Test Files 68 passed (68)`, `Tests 1237 passed (1237)`, VERDICT command-exit 0. - `pnpm --filter @objectstack/mcp typecheck`: exit 0, `check:test-typecheck: OK — ... 6 file(s) / 53 error(s) / 8 pinned signature(s) held` (the ledger is unchanged). </details> <details><summary>Stress proof: 32 busy loops on a 4-core box</summary> The same harness ran both legs: 32 `node -e 'for(;;){}'` loops, then the case alone (`-t 'out of CPU budget on the worker'`) N times. - origin/main (dfbc316), original case: **pass=1 fail=5 of 6**. Every failure was the CI shape: `content: "none"`, where `content: "text"` was expected. - This branch (53d7c7f): **pass=12 fail=0 of 12**, each run `Tests 1 passed | 46 skipped`. - With 8 busy loops the original case passed 8/8, so CI's red needs heavier contention than a 2x oversubscription. </details> <details><summary>Ablation: remove the seam wiring, then restore it</summary> `node scripts/ablation-replace.mjs` replaced the helper's `execArgv` line with one that drops the `--import` of the clock preload. - Mutation landed: `anchor 1 -> 0, blob 58c2867 -> 98321a40db56`. - Case result: **red**. `Tests 1 failed`. The expected `note: ...after page 3 of 120...` and `truncated: true` were missing: on the real clock, a 3000 ms budget reads all 120 pages. - Restored: `blob == HEAD (58c2867) and git diff HEAD is empty`. - No `dist/` is involved: vitest runs the test from source, and the worker runs `file-extraction-worker.ts` from source through `tsx`. </details> ## Acceptance notes - **Finding (reported to the seat, not fixed here).** When the ceiling cuts a worker before its first page, `read_file` answers `content: "none"`. Its reason is the budget sentence, which says "after page 0 of N, so the text is partial", but no text comes back. See `stoppedExtractionAnswer`, then `pdfAnswer([], ...)`, in `file-content.ts`. Measured through `read_file` in this suite, under load. - **Sibling worker cases, observed only.** These still use real wall-clock time: the ceiling case (40 ms budget, so a 200 ms ceiling before page 1 must arrive), the request-thread tick count, and the default-budget full reads. None has failed in CI that I know of, and none was stress-run here. They are noted only, with no carrier. - **Production budget read unchanged:** `git diff origin/main -- packages/mcp/src/file-extraction-worker.ts packages/mcp/src/file-content.ts packages/mcp/src/file-extraction-pool.ts` is empty. The CONTROL is the rest of the worker describe block, which runs on the real thread clock. ## Verification <details><summary>Local gate subset (derived by dispatch-gates --commands at a5821d8)</summary> - 50 derived; 49 ran locally with exit 0 (exit captured before any pipe): `node scripts/check-closing-keyword-parity.mjs`, `node scripts/check-closing-keyword-parity.mjs --self-test`, `node scripts/check-comment-mask-adoption.mjs`, `node scripts/check-comment-mask-adoption.mjs --self-test`, `node scripts/check-comment-mask-corpus.mjs`, `node scripts/check-dts-emitted.mjs --self-test`, `node scripts/check-issue-citations.mjs`, `node scripts/check-plugin-teardown-shape.mjs`, `node scripts/check-plugin-teardown-shape.mjs --self-test`, `node scripts/ci/assert-turbo-remote-cache.mjs --self-test`, `node scripts/ci/plan-test-core-shards.mjs --self-test`, `node scripts/ci/prune-turbo-cache.mjs --self-test`, `node scripts/docs-audit/check-affected-docs.mjs`, `node scripts/docs-audit/check-drift-comment.mjs`, `pnpm --filter @objectstack/spec run check:duration-unit-keys`, `pnpm check:adr-anchors`, `pnpm check:ci-filter-parity`, `pnpm check:closed-ceremony-text`, `pnpm check:cross-package-test-inputs`, `pnpm check:doc-authoring`, `pnpm check:driver-memory-census`, `pnpm check:dts-closure`, `pnpm check:engine-double-contract`, `pnpm check:gitlink-declared`, `pnpm check:issue-citations`, `pnpm check:keyed-text-bounds`, `pnpm check:lean-entry-closure`, `pnpm check:logger-receiver-detach`, `pnpm check:nul-bytes`, `pnpm check:objectql-double-limit`, `pnpm check:org-identifier`, `pnpm check:page-declaration-shape`, `pnpm check:platform-object-tenancy-census`, `pnpm check:published-files`, `pnpm check:query-options-erasure`, `pnpm check:refd-timer-probe`, `pnpm check:registry-log-declared`, `pnpm check:rest-log-spy-declared`, `pnpm check:slot-lookup`, `pnpm check:sourcemap-no-sources-content`, `pnpm check:system-context-census`, `pnpm check:test-source-alias`, `pnpm check:tier-file-adoption`, `pnpm check:type-check-coverage`, `pnpm check:type-check-debt`, `pnpm check:undeclared-dep-imports`, `pnpm check:vouch-for-reference-callers`, `pnpm check:watch-hint-literal`, `pnpm check:where-matcher`. - `pnpm check:dual-build-cjs-loads`: **NOT MEASURED**. It exited 3 with `PREREQUISITE NOT MET — this gate reads built output, and some package has no dist/` (78 packages unbuilt in this worktree). This is a declared narrowing: the gate reads built output of every package, and this diff changes no built file. CI's `Lint & Repo Gates` runs it. - `dispatch-gates --ran` reconciliation: `50 derived, 49 run, 0 NOT-MEASURED, 1 UNRUN` (the one above). - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` (merges cleanly into origin/main e9f65a3). - Every family CI runs is read from this PR's check-runs; the seat reads CI convergence. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent d947a93 commit 73609d0

1 file changed

Lines changed: 46 additions & 17 deletions

File tree

‎packages/mcp/src/mcp-file-tools.test.ts‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -939,33 +939,62 @@ describe('read_file extracts PDF and Word text on a worker pool, off the request
939939
expect({ ticks, enough: ticks >= 20 && ticks >= wallMs / 4 }).toMatchObject({ enough: true });
940940
});
941941

942+
/**
943+
* The worker started with a preload that replaces `process.threadCpuUsage`
944+
* IN THE WORKER THREAD with a clock advancing `stepMs` on every read: the
945+
* worker's twin of the in-process `steppingCpuClock`, which spies the
946+
* request thread's `process.cpuUsage` and cannot reach a worker. "The budget
947+
* is spent" is then decided by how many checkpoints the extractor reached,
948+
* never by how fast, or how loaded, this machine is. The worker's own code
949+
* is unchanged: it reads the clock it always reads.
950+
*/
951+
function steppingThreadCpuWorker(stepMs: number): ExtractionWorkerEntry {
952+
const clock = `let now = 0; process.threadCpuUsage = () => { now += ${stepMs * 1000}; return { user: now, system: 0 }; };`;
953+
return {
954+
...SOURCE_WORKER,
955+
execArgv: [...(SOURCE_WORKER.execArgv ?? []), '--import', `data:text/javascript,${encodeURIComponent(clock)}`],
956+
};
957+
}
958+
942959
it('out of CPU budget on the worker: the pages read so far, truncated, with the budget note, as in-process', async () => {
943-
configureReadFileExtraction({ cpuBudgetMs: 30, maxConcurrent: 4 });
960+
// The budget is spent at the third checkpoint (3 x 1000 ms of the stepping
961+
// clock), so the read stops after page 3, whatever the runner's load. The
962+
// budget is 3000 ms, not a few tens, because the pool's wall-clock ceiling
963+
// is 5 budgets of REAL time: at 30 ms that ceiling (150 ms) cut a loaded
964+
// runner's read before page 1, answering "after page 0" with no text.
965+
configureReadFileExtraction({ cpuBudgetMs: 3000, maxConcurrent: 4 });
966+
configureExtractionWorkerEntry(steppingThreadCpuWorker(1000));
944967
const pdf = heavyPdf(120, () => 2250);
945968
const bridge = fullBridge();
946-
const file = { name: 'heavy.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf };
947-
await readFile(bridge, minimalPdfFile()); // warm, so unpdf's load is not charged here
948-
const result = await readFile(bridge, file);
969+
const result = await readFile(bridge, { name: 'heavy.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf });
949970
const facts = factsOf(result);
950-
expect(facts).toMatchObject({ content: 'text', format: 'application/pdf', truncated: true });
951-
const read = /^Reading stopped at the CPU-time budget for one file \(30 ms\) after page (\d+) of 120, so the text is partial\. Download the file with the link for the rest\.$/.exec(facts.note);
952-
expect(read).not.toBeNull();
953-
const pages = Number(read![1]);
954-
expect(pages).toBeGreaterThanOrEqual(1);
955-
expect(pages).toBeLessThan(120);
956-
expect(textOf(result.content[1])).toBe(pageTexts(pages).join('\n\n'));
971+
expect(facts).toMatchObject({
972+
content: 'text',
973+
format: 'application/pdf',
974+
truncated: true,
975+
note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after page 3 of 120, so the text is partial. '
976+
+ 'Download the file with the link for the rest.',
977+
});
978+
expect(textOf(result.content[1])).toBe(pageTexts(3).join('\n\n'));
957979
expect(facts.download).toBeTruthy();
958980

981+
// Word: the budget is checked every 64 paragraphs. A 15 ms step spends the
982+
// same 3000 ms budget at the 200th checkpoint, 12,800 paragraphs in, which
983+
// is past the length cap, so the cap is what cuts the text that was read.
984+
configureExtractionWorkerEntry(steppingThreadCpuWorker(15));
959985
const paragraphs = Array.from({ length: 60_000 }, (_, i) => `Paragraph ${i + 1}`);
960986
const docx = zip({ 'word/document.xml': docxBody(paragraphs) });
961987
const word = await readFile(bridge, { name: 'long.docx', mimeType: DOCX, size: docx.length, bytes: docx });
962-
const wordFacts = factsOf(word);
963-
expect(wordFacts).toMatchObject({ content: 'text', format: DOCX, truncated: true });
964-
const count = Number(/after (\d+) paragraphs, so the text is partial/.exec(wordFacts.note)?.[1]);
965-
expect(count % 64).toBe(0);
966-
expect(count).toBeLessThan(paragraphs.length);
988+
expect(factsOf(word)).toMatchObject({
989+
content: 'text',
990+
format: DOCX,
991+
truncated: true,
992+
note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after 12800 paragraphs, so the text is partial. '
993+
+ 'Download the file with the link for the rest.',
994+
});
967995
// The length cap still applies to what was read.
968-
expect(textOf(word.content[1])).toBe(paragraphs.slice(0, count).join('\n').slice(0, 100_000));
996+
expect(paragraphs.slice(0, 12_800).join('\n').length).toBeGreaterThan(100_000);
997+
expect(textOf(word.content[1])).toBe(paragraphs.slice(0, 12_800).join('\n').slice(0, 100_000));
969998
});
970999

9711000
function minimalPdfFile(text = 'Small') {

0 commit comments

Comments
 (0)