Skip to content

fix(runtime): harden filesystem mutations against external path replacement #2600

Closed

Description

@Astro-Han

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.

Activity

  1. chinawch007 commented on Aug 10, 2026

    @chinawch007
    Contributor

    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).
    type FilesystemTargetIdentity = { dev: string; ino: string };
    
    // Discriminated union so "skip CAS" must be written explicitly.
    type FilesystemTargetDescriptor =
      | { enforcementPath: string; targetType: 'missing' }
      | { enforcementPath: string; targetType: 'file' | 'directory' | 'symlink' | 'other';
          identity: FilesystemTargetIdentity };
    
    type MutationOutcome = '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).

    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 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

    1. Failure-class split + outcome_unknown wiring — independently shippable, closes the "disconnect" concern on its own.
    2. The filesystem-authority contract module — types only, no behavior change.
    3. Captured identity + CAS + fd-pinned readModifyWrite — the core; includes the queue-window red-line tests.
    4. Delete hardening + three-state diff (binary/new/unknown) + format_json no-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.

  2. 13 remaining items

  3. added
    bug
    help wanted
    on Aug 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bughelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions