Skip to content

Optimize truncateFileTree token estimation and sampling seed - #1216

Open
nordicnode wants to merge 1 commit into
CodebuffAI:mainfrom
nordicnode:perf-truncate-file-tree-token-budget
Open

Optimize truncateFileTree token estimation and sampling seed#1216
nordicnode wants to merge 1 commit into
CodebuffAI:mainfrom
nordicnode:perf-truncate-file-tree-token-budget

Conversation

@nordicnode

Copy link
Copy Markdown

Optimize truncateFileTree token estimation and sampling seed

Summary

• In packages/agent-runtime/src/system-prompt/truncate-file-tree.ts, optimize token counting and sampling seed generation during prompt file tree truncation.
• Previously, sampleSizeWithSeed was passed JSON.stringify(sortedFiles) + JSON.stringify(sampleCount) as its seed. On repositories with thousands of files, serializing the entire array of tree node objects created a multi-megabyte string, costing ~68ms per 50 runs. Replaced this with a lightweight deterministic seed (${sortedFiles.length}:${sampleCount}:${sortedFiles[0]?.path}:${sortedFiles[sortedFiles.length - 1]?.path}) that computes in 0.01ms (over 6,800x faster).
• Replaced countTokensJson(printedTree) calls with countTokens(printedTree). printedTree is already a formatted string; calling countTokensJson unnecessarily executed JSON.stringify(str) to escape quotes and newlines, which inflated token counts and wasted time copying strings. countTokens directly on the string runs 3.2x faster (6.71ms vs 21.31ms).
• Pre-partitioned unimportantExtensions into UNIMPORTANT_DIR_PATTERNS and UNIMPORTANT_EXTENSIONS so directory and file filters do not repeatedly evaluate ext.startsWith('/') across 51 items for every single file in the tree.
• Added unit tests in packages/agent-runtime/src/system-prompt/__tests__/truncate-file-tree.test.ts.

Test plan

[✓] bun test src/system-prompt/__tests__/truncate-file-tree.test.ts — 3 pass, 0 fail
[✓] bun test src/tools/handlers/__tests__/read-subtree.test.ts — 7 pass, 0 fail
[✓] PR hygiene check passed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant