Distributed File-Lock Arbiters for Coding Agents: Preventing Multi-Agent Overwrites with SQLite WAL and PreToolUse Hooks

Why parallel AI coding agents silently clobber each other's patches in shared repositories, and how Benni-OS/claude-code-swarm enforces sub-millisecond pessimistic TTL file leases using atomic SQLite3 WAL transactions and Claude Code's native PreToolUse hook boundary.

Distributed File-Lock Arbiters for Coding Agents: Preventing Multi-Agent Overwrites with SQLite WAL and PreToolUse Hooks

1. The Silent Overwrite Problem in Multi-Agent Coding Swarms

Running a single AI coding agent is fast; running four or eight specialized subagents in parallel across a monorepo is transformative—until two agents touch the same file. In a standard shared working tree, every agent operates with an independent, stale snapshot of disk state inside its context window.

Consider a classic lost-update race condition:

  1. At t = 0s, Agent A (API Refactor) reads src/router.py and begins reasoning over a 25-line patch.
  2. At t = 1.8s, Agent B (Auth Middleware) reads src/router.py, finishes thinking first, and invokes Write or Edit to add an auth guard.
  3. At t = 3.1s, Agent A emits its Write payload computed from the t = 0s file state. The OS filesystem happily overwrites the inode, silently erasing Agent B's auth guard with zero errors.

Asking agents to coordinate via natural language ("only edit files assigned to you in the prompt") is probabilistic and breaks down immediately on shared barrel files, lockfiles, database schemas, or transitive imports. You cannot solve a concurrency hazard with prompt engineering. You need a deterministic mutual-exclusion arbiter at the tool-execution boundary.

Architectural Invariant: Every mutating filesystem call (Write, Edit, MultiEdit) must acquire an atomic, lease-backed lock before the tool executes. Benni-OS/claude-code-swarm enforces this in under 1 millisecond using a local SQLite3 WAL arbiter hooked directly into Claude Code's PreToolUse lifecycle event.

2. Pessimistic vs. Optimistic File Leases & TTL Expiration

When designing a concurrency control layer for autonomous coding agents, the first architectural decision is choosing between optimistic and pessimistic locking.

Why Leases Must Have a TTL (Time-To-Live)

In distributed systems, an indefinite lock is a deadlock waiting to happen. Coding agents are ephemeral processes: a subagent can hit a timeout, get killed by Ctrl+C, crash on an OOM, or trip a FinOps circuit breaker mid-task. If that agent never reaches PostToolUse or SubagentStop to release its lock, the file remains wedged forever.

Every lock in claude-code-swarm is therefore a time-bounded lease (default ttl_seconds = 120). Each lease stores owner_session_id, fencing_token (a monotonically increasing integer), acquired_at, and expires_at. Any subsequent BEGIN IMMEDIATE transaction atomically evicts expired rows (WHERE expires_at <= now) before evaluating ownership—delivering self-healing crash recovery with zero background reaper daemons.


3. Sequence Flow: Intercepting Write/Edit in PreToolUse

Claude Code invokes PreToolUse synchronously via stdin JSON before executing any tool. When two parallel agents target the same canonical path, the SQLite WAL arbiter serializes their lock requests cleanly:

sequenceDiagram autonumber participant A as Agent A (Session 101) participant H as PreToolUse Hook participant DB as SQLite3 WAL Arbiter participant B as Agent B (Session 204) A->>H: Propose Edit(src/router.py) H->>DB: BEGIN IMMEDIATE; evict expired; UPSERT lease(src/router.py, owner=101, TTL=120s) DB-->>H: OK (fencing_token=42) H-->>A: Exit 0 (Allow Write/Edit) B->>H: Propose Write(src/router.py) H->>DB: BEGIN IMMEDIATE; check owner for src/router.py DB-->>H: CONFLICT (held by 101, expires_at > now) H-->>B: Exit 2 + stderr("LOCK_CONFLICT: held by session 101, retry in 15s") A->>H: PostToolUse / SubagentStop (release lease 101) H->>DB: DELETE FROM file_leases WHERE path='...' AND owner='101' DB-->>H: Released

Notice two critical properties in this flow:

  1. Idempotent Re-entrancy: If Agent A holds the lease on src/router.py and issues a second Edit on the same file within its TTL window, the arbiter refreshes expires_at and allows execution immediately.
  2. Zero-Token Backoff: Agent B receives a crisp, deterministic stderr message from exit code 2, allowing it to pivot to an uncontested module or wait until Agent A's SubagentStop releases the lease.

4. Atomic SQLite3 WAL Schema & Python Arbiter Implementation

Naive filesystem .lock files suffer from TOCTOU (Time-of-Check to Time-of-Use) races and stale-file cleanup bugs across platforms. SQLite3 in Write-Ahead Logging (WAL) mode gives us ACID transactions, single-file zero-daemon deployment, and sub-millisecond contention handling via busy_timeout.

SQLite3 WAL Schema

PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA busy_timeout = 5000;

CREATE TABLE IF NOT EXISTS file_leases (
    canonical_path  TEXT PRIMARY KEY,
    owner_id        TEXT NOT NULL,
    fencing_token   INTEGER NOT NULL,
    acquired_at     REAL NOT NULL,
    expires_at      REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS lease_sequence (
    id              INTEGER PRIMARY KEY CHECK (id = 1),
    next_token      INTEGER NOT NULL DEFAULT 1
);

INSERT OR IGNORE INTO lease_sequence (id, next_token) VALUES (1, 1);
CREATE INDEX IF NOT EXISTS idx_leases_expires ON file_leases (expires_at);

Python PreToolUse Hook & Atomic Lease Arbiter

Below is the core atomic arbiter used by claude-code-swarm. Every path is resolved via os.path.realpath so symlinks and relative paths (./src/../src/router.py) map to the exact same lock key:

import json
import os
import sqlite3
import sys
import time
from pathlib import Path

DB_PATH = Path(".swarm/file_leases.db")
MUTATING_TOOLS = {"Write", "Edit", "MultiEdit"}
DEFAULT_TTL_SECONDS = 120.0


def init_db(conn: sqlite3.Connection) -> None:
    conn.execute("PRAGMA journal_mode = WAL;")
    conn.execute("PRAGMA synchronous = NORMAL;")
    conn.execute("PRAGMA busy_timeout = 5000;")
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS file_leases (
            canonical_path TEXT PRIMARY KEY,
            owner_id TEXT NOT NULL,
            fencing_token INTEGER NOT NULL,
            acquired_at REAL NOT NULL,
            expires_at REAL NOT NULL
        );
        CREATE TABLE IF NOT EXISTS lease_sequence (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            next_token INTEGER NOT NULL DEFAULT 1
        );
        INSERT OR IGNORE INTO lease_sequence (id, next_token) VALUES (1, 1);
        """
    )


def acquire_lease(
    db_path: Path, target_path: str, owner_id: str, ttl: float = DEFAULT_TTL_SECONDS
) -> tuple[bool, int, str]:
    canonical = os.path.realpath(target_path)
    now = time.time()
    expires_at = now + ttl
    db_path.parent.mkdir(parents=True, exist_ok=True)

    conn = sqlite3.connect(str(db_path), isolation_level=None, timeout=5.0)
    try:
        init_db(conn)
        conn.execute("BEGIN IMMEDIATE;")

        # 1. Atomically reap expired leases (self-healing crash recovery)
        conn.execute("DELETE FROM file_leases WHERE expires_at <= ?;", (now,))

        # 2. Check active lease holder
        row = conn.execute(
            "SELECT owner_id, fencing_token, expires_at FROM file_leases WHERE canonical_path = ?;",
            (canonical,),
        ).fetchone()

        if row is not None and row[0] != owner_id:
            remaining = max(0.0, row[2] - now)
            conn.execute("ROLLBACK;")
            return (
                False,
                row[1],
                f"LOCK_CONFLICT: '{canonical}' is leased by session '{row[0]}' "
                f"(token={row[1]}, expires in {remaining:.1f}s).",
            )

        # 3. Mint monotonic fencing token & upsert lease
        token = conn.execute(
            "UPDATE lease_sequence SET next_token = next_token + 1 WHERE id = 1 RETURNING next_token - 1;"
        ).fetchone()[0]

        conn.execute(
            """
            INSERT INTO file_leases (canonical_path, owner_id, fencing_token, acquired_at, expires_at)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(canonical_path) DO UPDATE SET
                owner_id = excluded.owner_id,
                fencing_token = excluded.fencing_token,
                acquired_at = excluded.acquired_at,
                expires_at = excluded.expires_at;
            """,
            (canonical, owner_id, token, now, expires_at),
        )
        conn.execute("COMMIT;")
        return True, token, f"LOCK_ACQUIRED: '{canonical}' (token={token})."
    except Exception:
        conn.execute("ROLLBACK;")
        raise
    finally:
        conn.close()


def main() -> None:
    payload = json.load(sys.stdin)
    tool_name = payload.get("tool_name", "")
    if tool_name not in MUTATING_TOOLS:
        sys.exit(0)

    tool_input = payload.get("tool_input", {})
    file_path = tool_input.get("file_path") or tool_input.get("path")
    if not file_path:
        sys.exit(0)

    owner_id = payload.get("session_id", "default-agent")
    acquired, _, message = acquire_lease(DB_PATH, file_path, owner_id)
    if not acquired:
        sys.stderr.write(message + "\n")
        sys.exit(2)

    sys.exit(0)


if __name__ == "__main__":
    main()

5. Latency & Concurrency Architecture Comparison

Why choose SQLite3 WAL + PreToolUse over Git worktrees, Redis, or naive filesystem lockfiles? Here is how the approaches compare under parallel swarm workloads:

Arbitration Strategy Acquisition Latency Crash Recovery (TTL) External Infra Race-Condition Safety
Prompt-Only Coordination (CLAUDE.md) 0 ms (probabilistic) N/A None Unsafe (silent overwrites on shared files)
Naive .lock Files (open(..., 'x')) 0.2 – 1.5 ms Manual / brittle mtime checks None Partial (TOCTOU on cleanup & no fencing token)
Git Worktrees per Agent 150 – 800 ms (checkout) Process-bound Git CLI High (isolated trees, but defers merge conflicts)
Redis Distributed Lock (Redlock) 1.5 – 5.0 ms (TCP/localhost) Native PX TTL Redis daemon High (requires running & monitoring Redis)
claude-code-swarm SQLite3 WAL 0.3 – 0.9 ms (in-process) Atomic TTL eviction on BEGIN IMMEDIATE Zero (stdlib sqlite3) ACID Serialized + Monotonic Fencing Tokens

In practice, SQLite3 WAL hits the exact engineering sweet spot for local multi-agent coding swarms: sub-millisecond lock acquisition, zero external daemons, ACID serialization across independent OS processes, and deterministic crash recovery via TTL.

Eliminate Multi-Agent Race Conditions Today

Deploy Benni-OS/claude-code-swarm to add atomic SQLite WAL file-lock arbitration, TTL lease recovery, and deterministic PreToolUse coordination to your parallel Claude Code workflows.

Explore Benni-OS/claude-code-swarm on GitHub →

Frequently Asked Questions

Why do parallel AI coding agents silently overwrite each other's files?
When multiple coding agents share a workspace, their Read-Think-Write cycles overlap. Agent A reads a file at t=0, Agent B writes a patch at t=2, and Agent A emits a full-file Write or stale Edit at t=3 based on its stale context—silently clobbering Agent B's changes without triggering any OS-level error.
Why use pessimistic TTL leases instead of optimistic concurrency control for coding agents?
Optimistic concurrency detects conflicts only after an agent has already burned LLM tokens and wall-clock time generating a patch. Pessimistic leases fail fast in PreToolUse before execution, while a bounded Time-To-Live (TTL) ensures that a crashed or SIGKILLed agent never leaves the file permanently deadlocked.
How does SQLite3 WAL guarantee atomic lock acquisition across concurrent hook processes?
By enabling PRAGMA journal_mode=WAL and opening transactions with BEGIN IMMEDIATE, SQLite serializes all write transactions across independent OS hook processes at the C-library level. Expired leases are evicted and new leases are inserted inside a single atomic transaction, eliminating check-then-act (TOCTOU) race conditions.
How does Benni-OS/claude-code-swarm enforce file locks in Claude Code?
claude-code-swarm registers a PreToolUse hook that intercepts Write, Edit, and MultiEdit tool calls, normalizes the target path with realpath, and queries the SQLite WAL arbiter. If another active agent holds a valid lease, the hook exits with code 2 and returns a structured stderr conflict message so the blocked agent backs off or coordinates.