{"slug": "distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal", "title": "Distributed File-Lock Arbiters for Coding Agents: Preventing Multi-Agent Overwrites with SQLite WAL and PreToolUse Hooks", "summary": "Benni Alencar, Chief AI Systems Architect at Benni OS, built claude-code-swarm, a distributed file-lock arbiter that prevents parallel coding agents from overwriting each other's changes in a shared working tree. The system hooks into Claude Code's PreToolUse lifecycle event and uses a local SQLite3 WAL database to enforce atomic, lease-backed locks on every mutating filesystem call in under 1 millisecond, with time-bounded leases (default 120 seconds) that self-heal after agent crashes without background reaper daemons.", "body_md": "*By **Benni Alencar** — Chief AI Systems Architect at [Benni OS](https://benni-os.net). Canonical article & interactive benchmarks at [benni-os.net](https://benni-os.net/blog/en/distributed-file-lock-arbiters-coding-agents-sqlite-wal-pretooluse.html).*\n\nRunning 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.\n\nConsider a classic **lost-update race condition**:\n\n`t = 0s`, `src/router.py` and begins reasoning over a 25-line patch.`t = 1.8s`, `Write` or `Edit` to add an auth guard.`t = 3.1s`, 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.\n\n```\n    **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](https://github.com/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.\n```\n\nWhen designing a concurrency control layer for autonomous coding agents, the first architectural decision is choosing between **optimistic** and **pessimistic** locking.\n\n`PreToolUse` hook fails fast (`< 1ms`) and returns a deterministic conflict error before the agent corrupts state or wastes further turns.\nIn 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.\n\nEvery 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.\n\nClaude 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:\n\n```\nsequenceDiagram\n    autonumber\n    participant A as Agent A (Session 101)\n    participant H as PreToolUse Hook\n    participant DB as SQLite3 WAL Arbiter\n    participant B as Agent B (Session 204)\n\n    A->>H: Propose Edit(src/router.py)\n    H->>DB: BEGIN IMMEDIATE; evict expired; UPSERT lease(src/router.py, owner=101, TTL=120s)\n    DB-->>H: OK (fencing_token=42)\n    H-->>A: Exit 0 (Allow Write/Edit)\n\n    B->>H: Propose Write(src/router.py)\n    H->>DB: BEGIN IMMEDIATE; check owner for src/router.py\n    DB-->>H: CONFLICT (held by 101, expires_at > now)\n    H-->>B: Exit 2 + stderr(\"LOCK_CONFLICT: held by session 101, retry in 15s\")\n\n    A->>H: PostToolUse / SubagentStop (release lease 101)\n    H->>DB: DELETE FROM file_leases WHERE path='...' AND owner='101'\n    DB-->>H: Released\n```\n\nNotice two critical properties in this flow:\n\n`expires_at` and allows execution immediately.`2`, allowing it to pivot to an uncontested module or wait until Agent A's `SubagentStop` releases the lease.\nNaive 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`.\n\n```\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = NORMAL;\nPRAGMA busy_timeout = 5000;\n\nCREATE TABLE IF NOT EXISTS file_leases (\n    canonical_path  TEXT PRIMARY KEY,\n    owner_id        TEXT NOT NULL,\n    fencing_token   INTEGER NOT NULL,\n    acquired_at     REAL NOT NULL,\n    expires_at      REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS lease_sequence (\n    id              INTEGER PRIMARY KEY CHECK (id = 1),\n    next_token      INTEGER NOT NULL DEFAULT 1\n);\n\nINSERT OR IGNORE INTO lease_sequence (id, next_token) VALUES (1, 1);\nCREATE INDEX IF NOT EXISTS idx_leases_expires ON file_leases (expires_at);\n```\n\nBelow 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:\n\n``` python\nimport json\nimport os\nimport sqlite3\nimport sys\nimport time\nfrom pathlib import Path\n\nDB_PATH = Path(\".swarm/file_leases.db\")\nMUTATING_TOOLS = {\"Write\", \"Edit\", \"MultiEdit\"}\nDEFAULT_TTL_SECONDS = 120.0\n\ndef init_db(conn: sqlite3.Connection) -> None:\n    conn.execute(\"PRAGMA journal_mode = WAL;\")\n    conn.execute(\"PRAGMA synchronous = NORMAL;\")\n    conn.execute(\"PRAGMA busy_timeout = 5000;\")\n    conn.executescript(\n        \"\"\"\n        CREATE TABLE IF NOT EXISTS file_leases (\n            canonical_path TEXT PRIMARY KEY,\n            owner_id TEXT NOT NULL,\n            fencing_token INTEGER NOT NULL,\n            acquired_at REAL NOT NULL,\n            expires_at REAL NOT NULL\n        );\n        CREATE TABLE IF NOT EXISTS lease_sequence (\n            id INTEGER PRIMARY KEY CHECK (id = 1),\n            next_token INTEGER NOT NULL DEFAULT 1\n        );\n        INSERT OR IGNORE INTO lease_sequence (id, next_token) VALUES (1, 1);\n        \"\"\"\n    )\n\ndef acquire_lease(\n    db_path: Path, target_path: str, owner_id: str, ttl: float = DEFAULT_TTL_SECONDS\n) -> tuple[bool, int, str]:\n    canonical = os.path.realpath(target_path)\n    now = time.time()\n    expires_at = now + ttl\n    db_path.parent.mkdir(parents=True, exist_ok=True)\n\n    conn = sqlite3.connect(str(db_path), isolation_level=None, timeout=5.0)\n    try:\n        init_db(conn)\n        conn.execute(\"BEGIN IMMEDIATE;\")\n\n        # 1. Atomically reap expired leases (self-healing crash recovery)\n        conn.execute(\"DELETE FROM file_leases WHERE expires_at <= ?;\", (now,))\n\n        # 2. Check active lease holder\n        row = conn.execute(\n            \"SELECT owner_id, fencing_token, expires_at FROM file_leases WHERE canonical_path = ?;\",\n            (canonical,),\n        ).fetchone()\n\n        if row is not None and row[0] != owner_id:\n            remaining = max(0.0, row[2] - now)\n            conn.execute(\"ROLLBACK;\")\n            return (\n                False,\n                row[1],\n                f\"LOCK_CONFLICT: '{canonical}' is leased by session '{row[0]}' \"\n                f\"(token={row[1]}, expires in {remaining:.1f}s).\",\n            )\n\n        # 3. Mint monotonic fencing token & upsert lease\n        token = conn.execute(\n            \"UPDATE lease_sequence SET next_token = next_token + 1 WHERE id = 1 RETURNING next_token - 1;\"\n        ).fetchone()[0]\n\n        conn.execute(\n            \"\"\"\n            INSERT INTO file_leases (canonical_path, owner_id, fencing_token, acquired_at, expires_at)\n            VALUES (?, ?, ?, ?, ?)\n            ON CONFLICT(canonical_path) DO UPDATE SET\n                owner_id = excluded.owner_id,\n                fencing_token = excluded.fencing_token,\n                acquired_at = excluded.acquired_at,\n                expires_at = excluded.expires_at;\n            \"\"\",\n            (canonical, owner_id, token, now, expires_at),\n        )\n        conn.execute(\"COMMIT;\")\n        return True, token, f\"LOCK_ACQUIRED: '{canonical}' (token={token}).\"\n    except Exception:\n        conn.execute(\"ROLLBACK;\")\n        raise\n    finally:\n        conn.close()\n\ndef main() -> None:\n    payload = json.load(sys.stdin)\n    tool_name = payload.get(\"tool_name\", \"\")\n    if tool_name not in MUTATING_TOOLS:\n        sys.exit(0)\n\n    tool_input = payload.get(\"tool_input\", {})\n    file_path = tool_input.get(\"file_path\") or tool_input.get(\"path\")\n    if not file_path:\n        sys.exit(0)\n\n    owner_id = payload.get(\"session_id\", \"default-agent\")\n    acquired, _, message = acquire_lease(DB_PATH, file_path, owner_id)\n    if not acquired:\n        sys.stderr.write(message + \"\\n\")\n        sys.exit(2)\n\n    sys.exit(0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nWhy choose SQLite3 WAL + `PreToolUse` over Git worktrees, Redis, or naive filesystem lockfiles? Here is how the approaches compare under parallel swarm workloads:\n\n| Arbitration Strategy | Acquisition Latency | Crash Recovery (TTL) | External Infra | Race-Condition Safety | \n|---|---|---|---|---|\n| **Prompt-Only Coordination** (`CLAUDE.md` ) | 0 ms (probabilistic) | N/A | None | Unsafe (silent overwrites on shared files) | \n| **Naive `.lock` Files** (`open(..., 'x')` ) | 0.2 – 1.5 ms | Manual / brittle mtime checks | None | Partial (TOCTOU on cleanup & no fencing token) | \n| **Git Worktrees per Agent** | 150 – 800 ms (checkout) | Process-bound | Git CLI | High (isolated trees, but defers merge conflicts) | \n| **Redis Distributed Lock** (Redlock) | 1.5 – 5.0 ms (TCP/localhost) | Native `PX` TTL | Redis daemon | High (requires running & monitoring Redis) | \n| **`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** | \n\nIn 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.\n\nDeploy **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.\n\n```\n    Explore Benni-OS/claude-code-swarm on GitHub →\nWhy do parallel AI coding agents silently overwrite each other's files?\n      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.\n\n  Why use pessimistic TTL leases instead of optimistic concurrency control for coding agents?\n  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 `SIGKILL` ed agent never leaves the file permanently deadlocked.\n\n  How does SQLite3 WAL guarantee atomic lock acquisition across concurrent hook processes?\n  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.\n\n  How does Benni-OS/claude-code-swarm enforce file locks in Claude Code?\n  `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.\n```\n\nWhen 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.\n\nOptimistic 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 `SIGKILL` ed agent never leaves the file permanently deadlocked.\n\nBy 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.\n\n`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.", "url": "https://wpnews.pro/news/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal", "canonical_source": "https://dev.to/bennialencar/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-overwrites-with-sqlite-wal-5dig", "published_at": "2026-11-23 22:40:07+00:00", "updated_at": "2026-11-23 22:43:04.235210+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "ai-safety"], "entities": ["Benni Alencar", "Benni OS", "claude-code-swarm", "Claude Code", "SQLite3", "GitHub"], "also_reported_by": [], "takeaway": "Enforce atomic, lease-backed file locks at the PreToolUse hook with a SQLite WAL arbiter so conflicting agents fail fast in under 1ms instead of corrupting shared files.", "recommendation": {"advice": "Gate every mutating Write, Edit or MultiEdit behind a SQLite WAL lease acquired in PreToolUse, and set a short TTL so crashed agents' locks self-evict.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal", "markdown": "https://wpnews.pro/news/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal.md", "text": "https://wpnews.pro/news/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal.txt", "jsonld": "https://wpnews.pro/news/distributed-file-lock-arbiters-for-coding-agents-preventing-multi-agent-with-wal.jsonld"}}