Skip to content
Hrushiekesh Reddy Kanjula
Two AI agents working on the same codebase with a file-locking orchestration layer preventing write collisions

Running Multiple AI Agents in Parallel Without Destroying Your Codebase

Two AI agents writing to the same file overwrite each other silently, so I put a SQLite file-lock layer in front of every write.

Published
May 25, 2026
Author
Hrushiekesh Reddy Kanjula
Read time
~4 min
Category
engineering

Parallel AI agents with file-locking orchestration preventing write collisions

Two AI agents writing to the same file at the same time is a data corruption event. One agent's work overwrites the other's. You lose changes silently, or you hit a merge conflict in the middle of an automated pipeline with no human to resolve it.

Parallel agents are worth it. If one agent builds a feature in 20 minutes, two agents should build two features in 20 minutes. But it only works with orchestration. This post covers the file-locking protocol I use in the assembly hub.

The collision problem

Say Agent A is refactoring the BOM normalization engine. Agent B is adding a query method to the database access layer. The tasks are independent. They touch different modules.

But both modules import from utils/constants.py. Agent A adds a regex constant. Agent B adds a SQL template string. Both read constants.py, add their line, and write the file back. Whoever writes second wipes out the first addition. No error. No warning.

This is not an edge case. Shared utilities, base classes and config files are imported everywhere. In a naive parallel setup, collisions happen constantly.

Silent overwrite: two agents reading then writing the same file with no coordination

The locking protocol

The fix is a lightweight coordination layer. Before an agent writes to a file, it must acquire a lock on that file. If another agent holds it, the requester gets a LOCKED response. It then waits and retries, or works on a different task.

The lock registry is one SQLite table:

CREATE TABLE file_locks (
    file_path TEXT PRIMARY KEY,
    locked_by TEXT NOT NULL,        -- agent identifier
    locked_at TIMESTAMP NOT NULL,
    task_description TEXT,
    expires_at TIMESTAMP            -- safety timeout
);

Acquiring a lock is a single atomic operation. SQLite's transaction isolation means two agents cannot take the same lock at once:

def acquire_lock(file_path: str, agent_id: str, task: str, timeout_minutes: int = 30) -> bool:
    with conn:
        try:
            conn.execute("""
                INSERT INTO file_locks 
                (file_path, locked_by, locked_at, task_description, expires_at)
                VALUES (?, ?, datetime('now'), ?, datetime('now', ? || ' minutes'))
            """, (file_path, agent_id, task, timeout_minutes))
            return True
        except sqlite3.IntegrityError:
            # PRIMARY KEY conflict — file already locked
            return False
 
def release_lock(file_path: str, agent_id: str) -> None:
    conn.execute(
        "DELETE FROM file_locks WHERE file_path = ? AND locked_by = ?",
        (file_path, agent_id)
    )
    conn.commit()

An agent that fails to get a lock checks the context archive and picks a different task from the backlog, one that does not need the locked file.

Orchestration

Above the lock registry sits an orchestration layer. It assigns tasks to agents and manages the parallel flow. In the assembly hub this is a custom task queue in the same SQLite database. A coordinator process polls available agents and matches them to unlocked tasks.

Frameworks like LangGraph formalize this pattern. It is a directed graph where nodes are agent steps and edges are task dependencies and coordination signals. The lock protocol fits as a "guard" node in front of any write.

LangGraph orchestration with file-lock guard nodes before write operations

Every write follows the same flow:

  1. The agent proposes a file write to the coordinator.
  2. The coordinator tries to acquire the lock for the agent.
  3. If the lock is acquired, the agent writes and releases the lock when done.
  4. If the lock is blocked, the coordinator gives the agent a different task and retries the lock after a configurable delay.

Context archive integration

The lock protocol uses the context archive from the governance framework. Say Agent B cannot lock constants.py because Agent A holds it. Agent B's redirect message includes the relevant archive section: "Agent A is currently refactoring the normalization engine constants. Do not modify constants.py until lock released. See context archive section 4.2 for current normalization architecture."

So the agent knows why the file is locked, not just that it is. That helps it pick a better alternative task. It can also avoid changes that would conflict with Agent A's work in files that are not locked yet.

Safety timeouts

Locks need timeouts. An agent that crashes mid-task, or gets stuck in a long reasoning loop, holds its locks forever. Every other agent is then blocked on those files.

The expires_at column handles this. A background process runs every 5 minutes and releases any lock past its expires_at. When a lock expires, the crashed agent's partial work is flagged for human review. The orchestration layer does not reverse it automatically, because partial work may be partly correct and worth keeping.

Lock expiry and cleanup: background process releasing stale locks with partial-work flagging

What a parallel session looks like

A typical session on the assembly hub:

AgentTaskLocks
ARotation validation improvementsrotation_engine.py, heuristics.py
BNew AOI report parserparsers/aoi.py, schemas/aoi_schema.py
CAnalytics query optimizationanalytics/queries.py, db/views.sql

All three run at once. The coordinator redistributes tasks when a lock conflicts.

Wall-clock time for three independent features is roughly the time of one feature done serially. The theoretical 3x speedup does not fully show up. Coordination overhead, the occasional lock conflict and the planning steps eat some of it. But 2x to 2.5x is consistently achievable.

The codebase also stays coherent. Every write is coordinated, and every conflict is resolved before it becomes silent data loss.

Hire me