`read_file` leaks the ReadStream fd whenever the line budget is reached, which blocks `MoveFileEx(..., MOVEFILE_REPLACE_EXISTING)` on that path indefinitely (Windows)
read_file leaks the ReadStream fd whenever the line budget is reached, which blocks MoveFileEx(..., MOVEFILE_REPLACE_EXISTING) on that path indefinitely (Windows)
This is additional data for #476, not a new report. #476 already describes the symptom and guessed the cause correctly. What follows adds: the exact trigger condition (measured, 108 attempts), the boundary case that pins the mechanism down, confirmation of the root cause by reading the shipped
dist/, and a one-line fix. Everything below was measured on 0.2.46; the relevant code is byte-identical in 0.2.47.
Summary
readFromStartWithReadline exits its for await loop with break once it has collected length lines, then
calls rl.close(). readline.Interface.close() does not close the interface's input stream, so the
fs.createReadStream file descriptor stays open for the lifetime of the server process. On Windows that open
handle causes MoveFileEx with MOVEFILE_REPLACE_EXISTING — i.e. os.replace(), File.Move(..., true),
fs.rename() over an existing target — to fail with ERROR_ACCESS_DENIED (WinError 5) from any other
process, for as long as the server lives.
The trigger is not "the read was truncated". The trigger is "the loop hit break instead of running to
completion". Those differ at exactly one point, and that point is measurable (see the length=5 vs length=6
rows below).
Environment
| Desktop Commander | 0.2.46, installed as a Claude Desktop extension (isDXT: true) |
| Node | 24.18.1 (bundled with Claude Desktop, MSIX-packaged) |
| Electron | 42.9.2 |
| OS | Windows 11 |
| Filesystem | local NTFS volume (not a network share, not cloud-synced) |
fileReadLineLimit |
1000 (default) |
defaultShell |
powershell.exe (PowerShell 5.1) |
| Writer process | Python 3.12, os.replace() |
Expected vs actual
Expected: after read_file returns, the server holds no handle on the file. A read is a read.
Actual: the server holds a read handle on that path until the process exits. Other processes can still
write to it, delete it, and rename it — the handle was opened with
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE — but replace-by-rename is refused. Any writer
using the standard atomic-write idiom (write temp file → os.replace() onto the target) fails, and it fails
silently from the reader's point of view: nothing in the MCP client indicates that a completed read is now
holding a lock.
Minimal repro (~2 minutes)
The companion script repro_handle_leak.py in this directory does the file setup and the probing. It cannot
issue MCP calls, so steps 2 and 4 are manual — that is the whole manual part.
Setup.
python repro_handle_leak.py setupCreatesD:\scratch\leak-test\with one file per cell, so the cells cannot contaminate each other (a leaked handle is not released — see Persistence — so reusing one file across cells does not work). The script prints the exact MCP calls for step 2.Confirm config, then make the reads. Check that
fileReadLineLimitis 1000 (get_config), then issue these seven calls from any MCP client, in any order. Do not readc8_control_5lines.txt.read_file(path="D:\\scratch\\leak-test\\c1_nolength_5lines.txt") read_file(path="D:\\scratch\\leak-test\\c2_len1000_5lines.txt", length=1000) read_file(path="D:\\scratch\\leak-test\\c3_len6_5lines.txt", length=6) read_file(path="D:\\scratch\\leak-test\\c4_len5_5lines.txt", length=5) read_file(path="D:\\scratch\\leak-test\\c5_len3_5lines.txt", length=3) read_file(path="D:\\scratch\\leak-test\\c6_nolength_1200lines.txt") read_file(path="D:\\scratch\\leak-test\\c7_len5000_1200lines.txt", length=5000)Note that c1 through c5 return identical content and identical status lines —
[Reading 5 lines from start (total: 5 lines, 0 remaining)]. From the client's side these five calls are indistinguishable. Three of them leak a handle and two do not.Probe.
python repro_handle_leak.py probe-allFor each file: write a temp file next to it, thenos.replace(tmp, target). Prints the matrix. Expected result is the Predicted column of the table below.Optional — identify the holder. Windows Restart Manager (
RmGetListinrstrtmgr.dll, no admin required) names the holder of each locked path. Compare that PID against thesystemInfo.processInfo.pidreported byget_config.
Measurements
Selected cells from a 108-attempt matrix on 0.2.46. Every failure is PermissionError: [WinError 5] Access is denied on os.replace(); every pass completed in ≤ 1 ms.
| Cell | File lines | length argument |
Effective budget | os.replace failures |
Predicted by rule |
|---|---|---|---|---|---|
| c1 | 5 | (omitted) | 1000 | 0 / 6 | pass |
| c2 | 5 | 1000 | 1000 | 0 / 6 | pass |
| c3 | 5 | 6 | 6 | 0 / 6 | pass |
| c4 | 5 | 5 | 5 | 6 / 6 | fail |
| c5 | 5 | 3 | 3 | 6 / 6 | fail |
| c6 | 1200 | (omitted) | 1000 | 6 / 6 | fail |
| c7 | 1200 | 5000 | 5000 | 0 / 6 | pass |
| c8 | 5 | never read | — | 0 / 60, all ≤ 1 ms | pass |
| — | 1200 | read_multiple_files |
1000 | 5 / 5 | fail |
c4 vs c3 is the decisive pair. Same file, same 5 lines, same bytes returned to the client, same status
line. length=5 leaks; length=6 does not. Nothing about the output differs — only whether the loop
reached break or fell out naturally.
c8 is the antivirus / search-indexer control: a file written by the same Python process and never touched by any tool replaces cleanly 60 times out of 60, sub-millisecond. Windows Search indexing was also excluded.
Derived rule
leaks ⟺ (length ?? fileReadLineLimit) ≤ (totalLines − offset)That is: the leak happens iff the budget is reachable within the file, which is exactly the condition for
break to execute.
Two consequences worth stating explicitly:
- The default is the dangerous case. With
fileReadLineLimit: 1000and nolengthargument, every file with ≥ 1000 lines leaks a handle on every read. No caller has to do anything unusual. lengthis not clamped tofileReadLineLimit—filesystem-handlers.jsuseslength: parsed.length ?? defaultLimit, a default and not aMath.min. So a larger explicitlengthmakes the leak go away (c7), which is the opposite of what a clamping model would predict.
Root cause
Verified by reading the shipped dist/ of both 0.2.46 and 0.2.47 —
dist/utils/files/text.js, readFromStartWithReadline:
const rl = createInterface({
input: createReadStream(filePath, { signal }), // <-- fd created here, never captured
crlfDelay: Infinity
});
const result = [];
let lineNumber = 0;
for await (const line of rl) {
if (lineNumber >= offset && result.length < length) {
result.push(line);
}
if (result.length >= length)
break; // <-- stream abandoned mid-flight
lineNumber++;
}
rl.close(); // <-- closes the Interface, NOT the input streamThe stream is created inline, so there is no reference left to destroy it with. createReadStream has
autoClose: true, which closes the fd when the stream reaches 'end' (or errors, or is destroyed). Running
the loop to completion drains the stream, 'end' fires, and the fd closes — which is why every non-leaking
cell above is a cell where the file ran out of lines before the budget did. Breaking out of the loop makes
readline's async iterator call Interface.close(), and
per the Node docs that does not close the input stream. The
signal is threaded through to createReadStream, but nothing aborts it on the early-exit path.
Suggested fix — capture the stream and destroy it in a finally:
const stream = createReadStream(filePath, { signal });
const rl = createInterface({ input: stream, crlfDelay: Infinity });
try {
for await (const line of rl) { /* unchanged */ }
} finally {
rl.close();
stream.destroy(); // the missing line
}Two other functions in the same file have the same shape and are presumably affected the same way, though
neither was measured here: readFromEstimatedPosition (two inline streams, two breaks — the sampling pass
breaks at SAMPLE_SIZE, so it should leak even when the second stream drains) and the rl2 block inside it.
readFromEndWithReadline has no break and always drains, so it should be safe.
Worth noting while fixing: for any file under 10 MB, readFileWithSmartPositioning has already called
getFileLineCount, which does a full fs.readFile of the file to count lines. The whole file is in memory
before the readline pass starts. So the early break is not saving I/O for the common case, and destroying
the stream costs nothing.
Persistence
A file read at 18:17 was still locked at 18:37:30 — about 20 minutes, 42 probes across 3 locked files, zero releases. The handle is not released by GC, by a later read of the same file, or by time. Effectively it is held until the server process exits.
Impact
The setup where this surfaced runs several MCP clients against a shared set of files, coordinated by an advisory lock protocol. Locks serialise the writers correctly — but a reader in one client silently disarms the atomic-write path for every writer, and the lock protocol has no reason to consider a read as conflicting. Result: 12 writes lost in a 20-minute window, and 11 more in a separate workspace that went unnoticed for 3 days, because the failure surfaces as a permission error in a writer that then rolls back quietly.
The reason this is easy to hit and hard to diagnose:
- The default read path arms it. Any file over
fileReadLineLimitlines leaks on a plainread_file. - The read succeeds. There is no error, no warning, and no difference in the returned payload (c3 vs c4).
- The lock holder is a reader, in a different process from the one that fails.
- The error surfaces as
WinError 5, which reads like a permissions or antivirus problem, so the first two days of investigation go into the wrong place. - Only
replacefails. Write, delete, and plain rename all succeed, which rules out most mental models of "the file is locked".
Workarounds
Verified:
- Reader side: pass
lengthstrictly greater than the file's line count — e.g. callget_file_infofirst and passlineCount + 1, or just pass an absurdlength. RaisingfileReadLineLimitabove your largest file works too, at the cost of context for every default read. Neither is a real fix: both push the threshold rather than removing it, and both are easy to forget on one call out of a hundred.read_multiple_fileshas no workaround at all:readMultipleFilescallsreadFile(validPath)with no options, so its budget is alwaysfileReadLineLimitand it cannot be told otherwise from the tool call.
Not verified, offered as options:
- Writer side: abandon replace-by-rename and write in place (
open(path, 'w')), which the share flags permit — at the cost of atomicity. - Reader side: read files you may need to replace through
start_processrather thanread_file. - Restarting the MCP server should release everything, but see below.
Retrying does not help — the handle does not time out.
What we don't know
- Whether the handle survives the server process exiting. Not tested: doing so meant killing a live session. Very likely it does not survive, but it is untested and stated as such.
- Behaviour on macOS and Linux. POSIX
rename(2)does not care about open descriptors, so the leak should be invisible there — which means it presents as slow fd accumulation instead of an error, and a long-lived server reading many large files could plausibly hitEMFILE. Not measured. readFromEstimatedPositionand negative offsets. Reasoned about from the source (above), not measured.- Exact fd count per leak. Assumed one per
read_file; not counted directly.
Version note
The file-reading code is unchanged between 0.2.46 and 0.2.47: dist/utils/files/text.js and
dist/tools/filesystem.js are byte-identical across the two published npm tarballs (MD5
21c1fc0ccc901e27d4fa11941f9e7dc9 and 854b61e658d7bebe939b42e040651fab respectively). 0.2.47 changes
remote-device/ duplicate-delivery handling, a toolHistory memory cap, telemetry, and README wording.
So 0.2.47 does not fix this, and users on it are affected identically.
Source: wonderwhy-er/DesktopCommanderMCP