Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@
"debug": "cross-env DEBUG=1 node --inspect-brk scripts/start.js",
"generate": "node scripts/generate-git-commit-info.js",
"generate:settings-schema": "node --import tsx/esm scripts/generate-settings-schema.ts",
"build": "node scripts/build.js",
"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" node scripts/build.js",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] cross-env NODE_OPTIONS="--max-old-space-size=3072" overwrites any existing NODE_OPTIONS the user or CI may have set. With the --parallel flag, each workspace worker inherits this 3GB heap limit — on memory-constrained CI runners, 3 parallel workers × 3GB = 9GB can cause system OOM (ironically, the very problem this PR aims to prevent). Consider appending instead of replacing, or limiting the heap flag to the build script only.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] cross-env NODE_OPTIONS="--max-old-space-size=3072" unconditionally replaces any NODE_OPTIONS set in the parent environment. Developers who export custom Node flags (e.g. --experimental-vm-modules, custom heap sizes) will have them silently discarded. The same pattern applies to lines 36 and 37.

Consider documenting this behavior in CONTRIBUTING.md, or using a separate env var (e.g. QWEN_NODE_MEMORY=3072) parsed inside the build scripts to avoid overwriting NODE_OPTIONS.

— claude-opus-4-7 via Qwen Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] cross-env NODE_OPTIONS="--max-old-space-size=3072" hardcodes a heap limit that overwrites any NODE_OPTIONS set in the user's or CI's environment. This can crash Node.js on machines with <4GB RAM (V8 exits if the requested heap size exceeds available physical memory). Consider moving this to CI config (.github/workflows/*.yml) so local developers and low-memory environments aren't affected.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cross-env NODE_OPTIONS="--max-old-space-size=3072" replaces any existing NODE_OPTIONS the user or CI environment has set. If a user has NODE_OPTIONS="--experimental-vm-modules --openssl-legacy-provider" already, this clobbers it.

Safer approach:

"build": "cross-env NODE_OPTIONS=\"${NODE_OPTIONS:-} --max-old-space-size=3072\" node scripts/build.js"

Or handle this in the build script itself where you can append to process.env.NODE_OPTIONS without overwriting.

"build-and-start": "npm run build && npm run start",
"build:vscode": "node scripts/build_vscode_companion.js",
"build:all": "npm run build && npm run build:sandbox && npm run build:vscode",
"build:packages": "npm run build --workspaces",
"build:sandbox": "node scripts/build_sandbox.js",
"bundle": "npm run generate && node esbuild.config.js && node scripts/copy_bundle_assets.js",
"test": "npm run test --workspaces --if-present --parallel",
"test:ci": "npm run test:ci --workspaces --if-present --parallel && npm run test:scripts",
"test": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" npm run test --workspaces --if-present --parallel",
"test:ci": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" npm run test:ci --workspaces --if-present --parallel && npm run test:scripts",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The second half of this script (npm run test:scripts after &&) does not inherit the --max-old-space-size=3072 flag. cross-env only sets NODE_OPTIONS for the immediate child process — the commands chained with && run without the increased heap limit.

Suggested change
"test:ci": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" npm run test:ci --workspaces --if-present --parallel && npm run test:scripts",
"test:ci": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" bash -c \"npm run test:ci --workspaces --if-present --parallel && npm run test:scripts\"",

— claude-opus-4-7 via Qwen Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] In test:ci, the npm run test:scripts after && does not inherit the NODE_OPTIONS flag set by cross-env (it only applies to the immediate child process). If test:scripts also needs the memory limit, it should be repeated: cross-env NODE_OPTIONS="..." npm run test:scripts.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

"test:scripts": "vitest run --config ./scripts/tests/vitest.config.ts",
"test:e2e": "cross-env VERBOSE=true KEEP_OUTPUT=true npm run test:integration:sandbox:none",
"test:integration:all": "npm run test:integration:sandbox:none && npm run test:integration:sandbox:docker && npm run test:integration:sandbox:podman",
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/services/fileReadCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ export type FileReadCheckResult =

export class FileReadCache {
private readonly byInode = new Map<string, FileReadEntry>();
private static readonly MAX_ENTRIES = 4096;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] private static readonly debugLogger = createDebugLogger(...) is the only class-level static debug logger in the codebase — all other 184 createDebugLogger calls use a module-level const. This breaks the established convention.

Suggested change
private static readonly MAX_ENTRIES = 4096;
const debugLogger = createDebugLogger('FILE_READ_CACHE');
export class FileReadCache {
private readonly byInode = new Map<string, FileReadEntry>();
private static readonly MAX_ENTRIES = 4096;

— gpt-5.5 via Qwen Code /review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @wenshao, thank you for the thorough review! All requested changes have been addressed in the latest commits:

TS2345 type error — fixed oldestKey narrowing: .get() now lives inside if (oldestKey) guard
Eviction bypass for existing keys — fixed: MAX_TOTAL_PATHS loop now computes totalPathsWithoutKey excluding the key being written, so updates to large existing entries correctly trigger eviction
Test coverage — added full eviction tests for MAX_CACHE_ENTRIES, MAX_TOTAL_PATHS, MAX_ENTRIES, timer cleanup on eviction, and FIFO bump (filling cache to capacity)
Constants exported — MAX_CACHE_ENTRIES, MAX_TOTAL_PATHS exported from crawlCache.ts; MAX_ENTRIES is public static on FileReadCache — tests reference them directly, no hardcoded literals
${NODE_OPTIONS:-} bash syntax — removed from all three scripts (build, test, test:ci)
JSDoc corrected — "LRU" → "FIFO by insertion order"
debugLogger — moved to module-level const, matching the rest of the codebase
delete + re-insert FIFO bump — upsert() removes and re-inserts the existing entry to refresh its Map position on every access
Please re-review when you get a chance. Thank you!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike crawlCache.read() which now bumps on read, fileReadCache.check() does not bump entries on access — only upsert() bumps. This means entries that are frequently read but rarely written will still be evicted oldest-first by write time.

This is a deliberate difference from crawlCache, but worth noting: check() is the hot-path method (called for every file tool invocation). If reads should also extend an entry's lifetime, check() would need the same delete-and-reinsert treatment. If not, the current behavior is fine — just make sure the 4096 limit is large enough for the working set.


/** Build the canonical key for a file from its Stats. */
static inodeKey(stats: Stats): string {
Expand Down Expand Up @@ -266,6 +267,13 @@ export class FileReadCache {
existing.sizeBytes = stats.size;
return existing;
}
// Evict oldest entry when cache exceeds MAX_ENTRIES (FIFO)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The upsert() method's existing branch above (lines 264-269) mutates in-place without delete+re-insert. Since Map.keys().next() always returns the oldest insertion-order key, a file read first in the session will be the FIRST evicted at 4096 entries — even if it's the most frequently accessed. This can cause priorReadEnforcement to reject edits with confusing "file not read" errors.

Suggested change
// Evict oldest entry when cache exceeds MAX_ENTRIES (FIFO)
if (existing) {
this.byInode.delete(key);
existing.realPath = absPath;
existing.mtimeMs = stats.mtimeMs;
existing.sizeBytes = stats.size;
this.byInode.set(key, existing);
return existing;
}

— DeepSeek/deepseek-v4-pro via Qwen Code /review

if (this.byInode.size >= FileReadCache.MAX_ENTRIES) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Cache eviction happens silently — no debug log. When priorReadEnforcement rejects an edit because an evicted file returns unknown from check(), there is no way to diagnose why a file the model read is now "not read in this session." This would be a 3AM debugging nightmare. Consider adding a rate-limited debug log for observability.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

const oldestKey = this.byInode.keys().next().value;
if (oldestKey) {
this.byInode.delete(oldestKey);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] The MAX_ENTRIES=4096 FIFO eviction logic added in this PR (lines 270-280) has zero test coverage. fileReadCache.test.ts was not modified — no test verifies that eviction fires, that the oldest entry is removed, or that recordRead/recordWrite/check behave correctly after eviction.

Impact: This is a blind OOM fix — 8 lines of new production code with no safety net. A future refactor of upsert() could silently break eviction and no test would catch it.

Suggested change
}
// Add to fileReadCache.test.ts a describe('eviction') block:
// - Fill cache to 4097 distinct inode entries via recordRead/recordWrite, verify oldest evicted
// - Verify cache.size() stays ≤ MAX_ENTRIES after overflow
// - Verify bumped entries (once bump is implemented) survive eviction

— DeepSeek/deepseek-v4-pro via Qwen Code /review

}
const entry: FileReadEntry = {
inodeKey: key,
realPath: absPath,
Expand Down
45 changes: 45 additions & 0 deletions packages/core/src/utils/filesearch/crawlCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import crypto from 'node:crypto';
const crawlCache = new Map<string, string[]>();
const cacheTimers = new Map<string, NodeJS.Timeout>();

// Limits to prevent heap exhaustion when many projects are crawled concurrently
const MAX_CACHE_ENTRIES = 256; // max distinct project roots cached
const MAX_TOTAL_PATHS = 50_000; // max total paths across all entries

/**
* Generates a unique cache key based on the project directory and the content
* of ignore files. This ensures that the cache is invalidated if the project
Expand Down Expand Up @@ -42,13 +46,54 @@ export const read = (key: string): string[] | undefined => crawlCache.get(key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] read() is a bare Map.get() with no FIFO bump. write() bumps on update (delete+set at lines 96-98), but read() does not. In a long-running session, the working project's crawl result — read frequently — stays at the FIFO head and is evicted by the 256th auxiliary crawl (multi-root workspace, dependency scan).

Impact: Users see random slowdowns when a frequently-used crawl result is silently evicted, forcing a full re-crawl with no diagnostic signal.

Suggested change
export const read = (key: string): string[] | undefined => {
const result = crawlCache.get(key);
// Bump to end of FIFO queue so frequently-read entries survive eviction
if (result !== undefined) {
crawlCache.delete(key);
crawlCache.set(key, result);
}
return result;
};

— DeepSeek/deepseek-v4-pro via Qwen Code /review

/**
* Writes data to the in-memory cache and sets a timer to evict it after the TTL.
* Enforces MAX_CACHE_ENTRIES (LRU by insertion order) and MAX_TOTAL_PATHS to

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] JSDoc says LRU by insertion order but the code implements pure FIFO (no access counting or reordering). The inline comment on the eviction loop correctly calls it FIFO. Using "LRU" here will mislead future maintainers.

Suggested change
* Enforces MAX_CACHE_ENTRIES (LRU by insertion order) and MAX_TOTAL_PATHS to
* Enforces MAX_CACHE_ENTRIES (FIFO by insertion order) and MAX_TOTAL_PATHS to

— DeepSeek/deepseek-v4-pro via Qwen Code /review

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] JSDoc on write() says LRU by insertion order but the implementation is pure FIFO (no access counting or reordering). The earlier size > 1 guard has been fixed, but the misleading JSDoc remains. Consider changing to FIFO (first-in-first-out) by insertion order to avoid confusing future maintainers — especially since LruCache.ts already exists in this codebase with true LRU semantics.

— DeepSeek/deepseek-v4-pro via Qwen Code /review

* prevent heap exhaustion when many large projects are crawled.
*/
export const write = (key: string, results: string[], ttlMs: number): void => {
// Clear any existing timer for this key to prevent premature deletion
if (cacheTimers.has(key)) {
clearTimeout(cacheTimers.get(key)!);
}

// Evict oldest entries when cache exceeds entry limit (FIFO / insertion-order)
while (crawlCache.size >= MAX_CACHE_ENTRIES && !crawlCache.has(key)) {
const oldestKey = crawlCache.keys().next().value;
if (oldestKey) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The crawlCache.delete(key) + clearTimeout + cacheTimers.delete cleanup trio is duplicated in both the entry-count eviction loop (here) and the total-paths eviction loop (below). Extracting a local deleteEntry(key) helper would eliminate the duplication and ensure future changes (e.g., adding another parallel data structure) only need one edit point.

Suggested change
if (oldestKey) {
const deleteEntry = (k: string) => {
crawlCache.delete(k);
const timer = cacheTimers.get(k);
if (timer) {
clearTimeout(timer);
cacheTimers.delete(k);
}
};
while (crawlCache.size >= MAX_CACHE_ENTRIES && !crawlCache.has(key)) {
const oldestKey = crawlCache.keys().next().value;
if (oldestKey) {
deleteEntry(oldestKey);
}
}

— glm-5.1 via Qwen Code /review

crawlCache.delete(oldestKey);
if (cacheTimers.has(oldestKey)) {
clearTimeout(cacheTimers.get(oldestKey)!);
cacheTimers.delete(oldestKey);
}
}
}

// Evict largest entries when total path count exceeds limit
let totalPaths = 0;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] The MAX_TOTAL_PATHS eviction test only covers updating an existing key. The production code path (crawler.ts writes a new key on every crawl) is untested. The totalPaths calculation (lines 76-81) correctly excludes the key being written for both new and existing keys — but only the existing-key path has a test.

Impact: The actual execution path in production is untested. If the totalPaths logic or the while-loop guard is refactored incorrectly, existing tests would still pass.

Suggested change
let totalPaths = 0;
// Add to crawlCache.test.ts:
it('should evict entries when a NEW key exceeds MAX_TOTAL_PATHS', () => {
write('existing-A', makePaths(20000), 60000);
write('existing-B', makePaths(20000), 60000);
write('new-key', makePaths(20000), 60000);
expect(read('new-key')).toBeDefined();
// At least one of existing-A or existing-B must be evicted
const survivor = read('existing-A') ?? read('existing-B');
expect(survivor).toBeDefined();
expect(read('existing-A') && read('existing-B')).toBeFalsy();
});

— DeepSeek/deepseek-v4-pro via Qwen Code /review

for (const entry of crawlCache.values()) {
totalPaths += entry.length;
}
while (totalPaths + results.length > MAX_TOTAL_PATHS && crawlCache.size > 1 && !crawlCache.has(key)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] Both eviction while-loops are guarded by !crawlCache.has(key), so updating an existing key bypasses all eviction checks entirely. If a re-crawled project grows significantly (e.g. 1000 → 50000 paths), MAX_TOTAL_PATHS is silently exceeded — defeating the OOM protection this PR is meant to provide. The size > 1 guard also means a single-entry cache with 50000+ paths is never evicted.

Suggested change
while (totalPaths + results.length > MAX_TOTAL_PATHS && crawlCache.size > 1 && !crawlCache.has(key)) {
// Compute totalPaths excluding the key being updated
let totalPaths = 0;
for (const [k, v] of crawlCache) {
if (k !== key) totalPaths += v.length;
}
// Enforce entry count cap (FIFO) — only when inserting a NEW key
if (!crawlCache.has(key)) {
while (crawlCache.size >= MAX_CACHE_ENTRIES) {
const oldestKey = crawlCache.keys().next().value;
if (oldestKey) {
totalPaths -= crawlCache.get(oldestKey)!.length;
crawlCache.delete(oldestKey);
if (cacheTimers.has(oldestKey)) {
clearTimeout(cacheTimers.get(oldestKey)!);
cacheTimers.delete(oldestKey);
}
}
}
}
// Enforce total paths cap (evict largest entry, skipping current key)
while (totalPaths + results.length > MAX_TOTAL_PATHS && crawlCache.size > 1) {
let largestKey: string | undefined;
let largestSize = 0;
for (const [k, v] of crawlCache) {
if (k !== key && v.length > largestSize) {
largestSize = v.length;
largestKey = k;
}
}
if (largestKey) {
totalPaths -= crawlCache.get(largestKey)!.length;
crawlCache.delete(largestKey);
if (cacheTimers.has(largestKey)) {
clearTimeout(cacheTimers.get(largestKey)!);
cacheTimers.delete(largestKey);
}
} else {
break;
}
}

— DeepSeek/deepseek-v4-pro via Qwen Code /review

// Find and remove the entry with the most paths
let largestKey: string | undefined;
let largestSize = 0;
for (const [k, v] of crawlCache) {
if (v.length > largestSize) {
largestSize = v.length;
largestKey = k;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The else { break; } branch is untested. When the cache holds only the current key and results.length > MAX_TOTAL_PATHS, the largest-key scan finds nothing and breaks — the oversized entry is stored unconditionally, violating the invariant. No test covers this control flow.

Consider adding a test for a single-key cache updated with >50k paths, and optionally refuse oversized single entries (if (results.length > MAX_TOTAL_PATHS && crawlCache.size <= 1) return).

— glm-5.1 via Qwen Code /review

}
}
if (largestKey) {
totalPaths -= crawlCache.get(largestKey)!.length;
crawlCache.delete(largestKey);
if (cacheTimers.has(largestKey)) {
clearTimeout(cacheTimers.get(largestKey)!);
cacheTimers.delete(largestKey);
}
} else {
break;
}
}

// Store the new data
crawlCache.set(key, results);

Expand Down
Loading