You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(runtime): harden filesystem mutations against external path replacement #2600
Maka serializes cooperative file mutations by canonical path, but Bash or external processes can replace that path between lock resolution and mutation. This affects Write/Edit/FormatJson/ApplyPatch; delete may unlink the replacement, and worker disconnects may leave the outcome unknown.
Define a shared filesystem-authority contract for stable target identity, compare-and-delete/update, and post-dispatch unknown outcomes. Keep this separate from individual editing tools.
I'd like to pick this up. Below is the approach I'm proposing — it's built directly around the three concerns in the issue and the contract the author asked for.
Root cause
Today expectedTarget is computed after the write lock is acquired (client.ts:245-250), not when the lock key is resolved. The lock serializes concurrent Maka tools on one path, but it does nothing while a call is queued for it, and Bash is not serialized at all (file-write-lock.ts:13-17). So in the window between lock acquisition and the actual write/unlink, an external process can replace or create the path — and because we then resolve the target after acquiring the lock, we mutate whatever we find at that point, not the file we originally intended. That is exactly the "write/delete the replacement" failure called out here.
A shared filesystem-authority contract (kept separate from the tools)
The centerpiece is a new packages/runtime/src/filesystem-authority.ts that declares the contract types themselves, imported by the executor, worker, and workspace-executor alike — not another bag of I/O helpers. It owns the three things the issue names:
// Opaque identity: String(dev)/String(ino), compared as strings (BigInt can't// cross the JSON protocol boundary; an opaque token avoids that entirely).typeFilesystemTargetIdentity={dev: string;ino: string};// Discriminated union so "skip CAS" must be written explicitly.typeFilesystemTargetDescriptor=|{enforcementPath: string;targetType: 'missing'}|{enforcementPath: string;targetType: 'file'|'directory'|'symlink'|'other';identity: FilesystemTargetIdentity};typeMutationOutcome='applied'|'rejected'|'unknown';
A discriminated union (rather than identity?) means a "no identity to compare → pass" branch can't exist by accident — it must be the explicit missing case. This compiles the whole class of "silently skipped CAS" regressions out of existence.
1. Stable target identity — capture at lock acquisition, never re-derived
writeLockTarget resolves the lock key and captures a full FilesystemTargetDescriptor (path + type + inode) at lock acquisition time. That descriptor travels with the call into the backend; the worker's assertTargetUnchanged compares against that captured identity, not against a freshly-resampled path. enforcementPath/targetType are also pinned to the capture moment (a symlink swapped after that point changes both the path string and the type, so only the captured inode is load-bearing). This closes the queue window for Write/Edit/FormatJson/ApplyPatch-update, including the "target was missing at capture, created externally by execution time" direction (the descriptor is missing; an edit/format_json landing on a just-appeared file now fails with path_changed instead of silently running).
For content updates the RMW is rewritten to hold a single file descriptor across read → transform → truncate+write. An fd binds to a specific inode at open, so a path swapped mid-operation can't divert the write — it lands on the original inode structurally, not just by re-checking. CAS (fstat(fd) vs the captured identity) runs before the write, and a post-write lstat(path) vs fd check reports an unknown outcome if the on-path inode no longer matches (the write went to an orphaned inode; the visible file is the replacement).
This is exposed as one new optional executor method, readModifyWrite({ expected: FilesystemTargetDescriptor, transform }), so the existing readFile→writeFile split (which itself re-opened the race) collapses into one atomic primitive. New-file writes use O_CREAT|O_EXCL; apply_patch create keeps its wx flag.
On path_changed we do not auto-retry: content matching an oldString only proves the snippet exists, not that it's the same file — retrying would reproduce the exact defect this issue describes (mv other.ts target.ts where both contain the string). We return a clear "the target was replaced while queued; re-read before editing" and let the model do Read → Edit.
3. Compare-and-delete — honest about POSIX limits
Delete can't be fd-pinned (unlink is path-based), so it does lstat({bigint}) to compare the captured inode + unlink, without opening the file (an open('r+') precondition would break deletion of read-only/write-only files today — unlink only needs the parent dir). To be explicit about what this does and doesn't buy: POSIX has no atomic compare-and-unlink, so this narrows the lstat→unlink window rather than closing it. On Linux, pinning the parent dir (openSync(parent, O_PATH|O_DIRECTORY|O_NOFOLLOW) + unlinkSync('/proc/self/fd/${parentFd}/${basename})) additionally closes the ancestor-traversal race; macOS/Windows have no /proc equivalent, so the window is wider there. I'll record this as a documented residual rather than over-claiming "closed."
4. Post-dispatch unknown outcomes
The worker crash path currently throws a generic FilesystemWorkerClientError. The plan:
Split the ambiguous failure reasons by a dispatched flag (driven by Node's 'spawn' event / stdin.end), not by guessing error types. spawn_failed (never started, nothing could have been written) is distinguished from worker_io_incomplete (ran but the result was lost — e.g. output didn't drain before the lifecycle deadline). aborted is split the same way: a pre-dispatch abort is a clean cancel, a post-dispatch kill is an unknown outcome. Without this, a single ESC marks every queued file tool "outcome unknown" (retrySafe: false), which both penalizes the highest-frequency user action and dilutes the unknown signal for the cases that actually need it.
Add an outcome_unknown protocol error code (identity fields are string-encoded) so the worker can report "I may have written before I died." normalizeOperationError maps the post-write orphan check to this code.
A mutating op that fails with any of {worker_crashed, worker_io_incomplete, timeout, response_overflow, invalid_response, response_id_mismatch, response_kind_mismatch, outcome_unknown, post-dispatch aborted} is rethrown as ToolOutcomeUnknownError, which already flows through tool-runtime.ts to a structured uncertainOutcome result telling the model the file's state is indeterminate.
What's in scope / out of scope
In scope (issue's three concerns): path replacement for writes/edits; replacement detection for deletes; unknown outcomes on disconnect.
Out of scope (separate work): hard-link concurrent writes to the same inode. The issue is specifically about path replacement, lexical lock keying is a documented existing tradeoff, and CAS can't catch two RMWs on one inode (the inode never changes). I'll leave withFileWriteLock untouched.
Phased rollout
Failure-class split + outcome_unknown wiring — independently shippable, closes the "disconnect" concern on its own.
The filesystem-authority contract module — types only, no behavior change.
Captured identity + CAS + fd-pinned readModifyWrite — the core; includes the queue-window red-line tests.
Activity
chinawch007 commentedon Aug 10, 2026
I'd like to pick this up. Below is the approach I'm proposing — it's built directly around the three concerns in the issue and the contract the author asked for.
Root cause
Today
expectedTargetis computed after the write lock is acquired (client.ts:245-250), not when the lock key is resolved. The lock serializes concurrent Maka tools on one path, but it does nothing while a call is queued for it, and Bash is not serialized at all (file-write-lock.ts:13-17). So in the window between lock acquisition and the actual write/unlink, an external process can replace or create the path — and because we then resolve the target after acquiring the lock, we mutate whatever we find at that point, not the file we originally intended. That is exactly the "write/delete the replacement" failure called out here.A shared
filesystem-authoritycontract (kept separate from the tools)The centerpiece is a new
packages/runtime/src/filesystem-authority.tsthat declares the contract types themselves, imported by the executor, worker, and workspace-executor alike — not another bag of I/O helpers. It owns the three things the issue names:A discriminated union (rather than
identity?) means a "no identity to compare → pass" branch can't exist by accident — it must be the explicitmissingcase. This compiles the whole class of "silently skipped CAS" regressions out of existence.1. Stable target identity — capture at lock acquisition, never re-derived
writeLockTargetresolves the lock key and captures a fullFilesystemTargetDescriptor(path + type + inode) at lock acquisition time. That descriptor travels with the call into the backend; the worker'sassertTargetUnchangedcompares against that captured identity, not against a freshly-resampled path.enforcementPath/targetTypeare also pinned to the capture moment (a symlink swapped after that point changes both the path string and the type, so only the captured inode is load-bearing). This closes the queue window forWrite/Edit/FormatJson/ApplyPatch-update, including the "target was missing at capture, created externally by execution time" direction (the descriptor ismissing; anedit/format_jsonlanding on a just-appeared file now fails withpath_changedinstead of silently running).2. Compare-and-update — fd-pinned read-modify-write
For content updates the RMW is rewritten to hold a single file descriptor across read → transform →
truncate+write. An fd binds to a specific inode atopen, so a path swapped mid-operation can't divert the write — it lands on the original inode structurally, not just by re-checking. CAS (fstat(fd)vs the captured identity) runs before the write, and a post-writelstat(path)vsfdcheck reports an unknown outcome if the on-path inode no longer matches (the write went to an orphaned inode; the visible file is the replacement).This is exposed as one new optional executor method,
readModifyWrite({ expected: FilesystemTargetDescriptor, transform }), so the existingreadFile→writeFilesplit (which itself re-opened the race) collapses into one atomic primitive. New-file writes useO_CREAT|O_EXCL;apply_patch createkeeps itswxflag.On
path_changedwe do not auto-retry: content matching anoldStringonly proves the snippet exists, not that it's the same file — retrying would reproduce the exact defect this issue describes (mv other.ts target.tswhere both contain the string). We return a clear "the target was replaced while queued; re-read before editing" and let the model doRead→Edit.3. Compare-and-delete — honest about POSIX limits
Deletecan't be fd-pinned (unlinkis path-based), so it doeslstat({bigint})to compare the captured inode +unlink, without opening the file (anopen('r+')precondition would break deletion of read-only/write-only files today —unlinkonly needs the parent dir). To be explicit about what this does and doesn't buy: POSIX has no atomic compare-and-unlink, so this narrows thelstat→unlinkwindow rather than closing it. On Linux, pinning the parent dir (openSync(parent, O_PATH|O_DIRECTORY|O_NOFOLLOW)+unlinkSync('/proc/self/fd/${parentFd}/${basename})) additionally closes the ancestor-traversal race; macOS/Windows have no/procequivalent, so the window is wider there. I'll record this as a documented residual rather than over-claiming "closed."4. Post-dispatch unknown outcomes
The worker crash path currently throws a generic
FilesystemWorkerClientError. The plan:dispatchedflag (driven by Node's'spawn'event /stdin.end), not by guessing error types.spawn_failed(never started, nothing could have been written) is distinguished fromworker_io_incomplete(ran but the result was lost — e.g. output didn't drain before the lifecycle deadline).abortedis split the same way: a pre-dispatch abort is a clean cancel, a post-dispatch kill is an unknown outcome. Without this, a single ESC marks every queued file tool "outcome unknown" (retrySafe: false), which both penalizes the highest-frequency user action and dilutes the unknown signal for the cases that actually need it.outcome_unknownprotocol error code (identity fields are string-encoded) so the worker can report "I may have written before I died."normalizeOperationErrormaps the post-write orphan check to this code.{worker_crashed, worker_io_incomplete, timeout, response_overflow, invalid_response, response_id_mismatch, response_kind_mismatch, outcome_unknown, post-dispatch aborted}is rethrown asToolOutcomeUnknownError, which already flows throughtool-runtime.tsto a structureduncertainOutcomeresult telling the model the file's state is indeterminate.What's in scope / out of scope
withFileWriteLockuntouched.Phased rollout
outcome_unknownwiring — independently shippable, closes the "disconnect" concern on its own.filesystem-authoritycontract module — types only, no behavior change.readModifyWrite— the core; includes the queue-window red-line tests.binary/new/unknown) +format_jsonno-write.This plan was drafted with material assistance from GLM, DeepSeek, Claude fable, and reviewed by a human before publication.
I will start when this task is assigned to me.
feat(runtime): surface worker disconnect as unknown outcome for mutat…
refactor(runtime): extract filesystem-authority contract (apache#2600)
feat(runtime): capture target identity at lock acquisition for CAS (a…
feat(runtime): extend post-write orphan check to edit/format/update (a…
feat(runtime): surface worker disconnect as unknown outcome for mutat…
refactor(runtime): extract filesystem-authority contract (apache#2600)
feat(runtime): capture target identity at lock acquisition for CAS (a…
feat(runtime): extend post-write orphan check to edit/format/update (a…
test(runtime): pass expected identity in Linux filesystem worker smoke (
feat(runtime): surface worker disconnect as unknown outcome for mutat…
refactor(runtime): extract filesystem-authority contract (apache#2600)
feat(runtime): capture target identity at lock acquisition for CAS (a…
feat(runtime): extend post-write orphan check to edit/format/update (a…
test(runtime): pass expected identity in Linux filesystem worker smoke (
13 remaining items
feat(runtime): compare-and-delete with tombstone verification (apache…
feat(runtime): surface worker disconnect as unknown outcome for mutat…
refactor(runtime): extract filesystem-authority contract (apache#2600)
feat(runtime): capture target identity at lock acquisition for CAS (a…
feat(runtime): extend post-write orphan check to edit/format/update (a…
test(runtime): pass expected identity in Linux filesystem worker smoke (
test(runtime): make the T0 and missing-target tests protect observabl…
feat(runtime): fd-pinned mutation primitive for both backends (apache…
feat(runtime): compare-and-delete with tombstone verification (apache…
fix(runtime): no-replace tombstone restore and directory rejection (a…
fix(runtime): type-aware tombstone restore and structured directory r…
fix(runtime): close the path-replacement window for filesystem mutati…