Skip to content

memory: two processes clearing one crash-left lock guard can remove a live guard #5624

Done

Description

@cliffhall

Problem

The memory server's cross-process lock uses a second exclusive-create file, the guard (<memory file>.lock.break), to order stale-lock breaking and, since #5565 (PR #5623), every release and every newly created lock's confirmation. A guard left behind by a process that crashed while holding it is cleared by whoever finds it older than the stale timeout (30 seconds by default).

That clearing is done by path: the finder opens the guard, judges its age through the handle, and then calls unlink on the guard's path (isGuardHeld in src/memory/index.ts; before #5565 the same stat then unlink in breakStaleLock). Two processes clearing the same crash-left guard at once can therefore remove a live one:

  1. A and B both open the crash-left guard and judge it stale.
  2. A unlinks it.
  3. C (a releasing holder, or a breaker) creates a fresh guard at the same path.
  4. B unlinks the path, deleting C's fresh guard.

C then runs its few guarded file-system calls unguarded, so a breaker can act between a release's token comparison and its removal (the third window of #5565), or two breakers can run at once.

It takes a crash inside a guarded section (a few file-system calls per write), then two processes clearing that guard within the same moment, then a third taking the guard between their two unlinks. The processes run as the same user, so this is a correctness gap, not a security boundary. Raised by Copilot in review of #5623 and declined there as beyond the three windows #5565 names.

Expected behavior

Clearing a guard left by a crash never removes a guard another process has taken since.

Approach

To be decided. Renaming the guard aside and comparing device and inode with the judged file before deleting it, as breakStaleLock does for the lock itself (#5560), removes exactly this interleaving, but putting a mistakenly taken live guard back has its own gap one level down (a create at the guard path while it is aside). Whatever is chosen should say what remains, as the comment above guardPathOf() does today.

Acceptance criteria

  • A deterministic test (no timing dependence): two clearers of one crash-left guard, with a fresh guard created between their removals; the fresh guard survives.
  • The existing lock tests still pass.

Activity

  1. added this to the v2.7.0 milestone on Nov 18, 2026
  2. added
    bug
    server-memory
    on Nov 18, 2026
  3. A7mdMe commented on Nov 19, 2026

    @A7mdMe

    Sharp observation on this ABA race window, @cliffhall.

    The core vulnerability stems from unlink(guardPath) operating by pathname rather than on the file descriptor/inode identity that was evaluated stale.

    One clean, robust way to eliminate this interleaving without the secondary gap of putting an aside file back is the Atomic Rename-Aside Staging Pattern:

    Architectural Mechanism

    Rather than having a clearing process call unlink(guardPath) directly:

    1. The process opens the guard file via descriptor (fs.openSync), evaluates its age via fstatSync, and captures stat.ino / stat.dev.
    2. If stale, the process executes an atomic rename aside to a private unique staging path in the same directory:
      const stagingPath = `${guardPath}.clearing.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
      try {
        fs.renameSync(guardPath, stagingPath);
      } catch (err) {
        if (err.code === 'ENOENT') {
          // Lost race to another cleaner: abort safely without touching anything
          return { cleared: false, reason: 'ALREADY_REMOVED' };
        }
        throw err;
      }
    3. Verify that the staged file's inode matches the judged handle (fs.statSync(stagingPath).ino === statBefore.ino).
    4. Safely unlinkSync(stagingPath).

    Why this completely closes the ABA window:

    • If Process A and Process B both judge the crash-left guard stale at $T_0$, only one process will successfully rename guardPath.
    • The second process gets an immediate ENOENT from renameSync and safely aborts.
    • When Process C creates a fresh live guard at guardPath, Process B is never in a position to blindly unlink guardPath. Even if Process B retried, clearStaleGuardSafely would inspect C's fresh guard, see age < staleTimeout, and immediately abort with NOT_STALE.
    • Process C's live guard remains completely untouched.

    Deterministic Concurrency Test Pattern (No Timing Dependence)

    it('deterministic ABA test: fresh guard survives concurrent stale clearers', () => {
      const guardPath = path.join(tmpDir, 'memory.json.lock.break');
    
      // 1. Initial crash-left stale guard
      createLiveGuard(guardPath, 9999);
      const oldTime = (Date.now() - 40000) / 1000;
      fs.utimesSync(guardPath, oldTime, oldTime);
    
      // 2. Clearer A evaluates and clears stale guard via rename-aside
      const resultA = clearStaleGuardSafely(guardPath, 30000);
      assert.strictEqual(resultA.cleared, true);
      assert.strictEqual(fs.existsSync(guardPath), false);
    
      // 3. Process C takes a fresh live guard at the exact same path
      const liveGuardC = createLiveGuard(guardPath, process.pid);
      assert.strictEqual(liveGuardC.created, true);
    
      // 4. Delayed Clearer B attempts to act on guardPath
      const resultB = clearStaleGuardSafely(guardPath, 30000);
      assert.strictEqual(resultB.cleared, false); // Rejected: fresh guard is NOT_STALE
    
      // 5. Assert Process C's live guard survived with token intact
      assert.strictEqual(fs.existsSync(guardPath), true);
      const current = JSON.parse(fs.readFileSync(guardPath, 'utf8'));
      assert.strictEqual(current.token, liveGuardC.token);
    });

    (Disclosure: I maintain A7mdMe/mcp-production-kit, where we test and harden production MCP client/server boundary and concurrency defenses).

  4. anassk01 commented on Nov 23, 2026

    @anassk01

    One thing to watch on issue 5624 is inode reuse on Linux tmpfs and ext4. After Process A unlinks .lock.break and Process C creates a fresh guard, the kernel can reuse the same inode number, so checking dev and ino alone still lets Process B delete C's live guard. Taking .lock.break.reclaim first and checking an owner token inside the guard keeps C's guard intact, and I wrote a zero-timer node:test for it if helpful.

  5. self-assigned this
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugserver-memoryv2

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions