cd /news/ai-agents/distributed-file-lock-arbiters-for-c… · home › topics › ai-agents › article
[ARTICLE · art-175052] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

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

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.

recommendation

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.

more in playbook: Designing agent systems
by read8 min views1 publishedNov 23, 2026

By Benni Alencar — Chief AI Systems Architect at Benni OS. Canonical article & interactive benchmarks at benni-os.net.

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:

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.

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

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

PreToolUse hook fails fast (< 1ms) and returns a deterministic conflict error before the agent corrupts state or wastes further turns. 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.

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:

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

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

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;")

        conn.execute("DELETE FROM file_leases WHERE expires_at <= ?;", (now,))

        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).",
            )

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

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.

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 →
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 `SIGKILL` ed 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.

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.

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.

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.

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.

── more in #ai-agents 4 stories · sorted by recency
── more on @benni alencar 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/distributed-file-loc…] indexed:0 read:8min 2026-11-23 · —