Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:777genius Agent teams ai Scope Locking

From Leeroopedia
Knowledge Sources
Domains Concurrency, Data_Persistence
Last Updated 2026-10-22 00:00 GMT

Overview

Use SQLite-backed lease locks with heartbeat verification to serialize write operations across app instances and prevent concurrent mutation of review decisions.

Description

Review persistence scope locks use a SQLite database to implement a lease-based locking protocol. Each lock has an owner token (UUID), owner PID, and process start time. The lease is acquired via `BEGIN IMMEDIATE` with busy timeout and retry. Once acquired, a heartbeat interval (5s) periodically verifies ownership by checking that the owner token still matches. If the heartbeat detects ownership loss (e.g., another process stole the lease after a crash), the operation aborts. Stale leases from crashed processes are reclaimed by checking if the PID is still alive and comparing process start times to detect PID recycling.

Usage

Use this heuristic when multiple app instances or concurrent operations need exclusive access to a shared resource. This applies to review decision persistence — serializing apply/revert operations per task/agent scope. The logical scope lock serializes retention and recovery discovery before the exact-scope lock.

The Insight (Rule of Thumb)

  • Action: Wrap operations in `withReviewPersistenceScopeLock(teamName, scope, operation)`.
  • Value: Acquire timeout: 30s. Retry interval: 25ms. Heartbeat interval: 5s. SQLite busy timeout: 2s.
  • Trade-off: Operations are serialized per scope — concurrent operations on different scopes proceed in parallel. Heartbeat adds minor I/O overhead.
  • Compatibility: Cross-process via shared SQLite file. Cross-platform via `node:sqlite`. PID recycling handled by process start time comparison.

Reasoning

Without locking, concurrent review changes (e.g., accept + revert on the same task) could corrupt state. SQLite provides ACID transactions, and `BEGIN IMMEDIATE` ensures only one writer at a time. The lease + heartbeat pattern detects crashes: if the lock owner process dies, its heartbeat stops, and the next acquirer reclaims the stale lease by verifying the PID is no longer alive (or has been recycled to a different process, detected by start time mismatch).

Code Evidence

Lease acquisition from `ReviewPersistenceScopeLock.ts:313-337`:

async function acquireLease(...): Promise<ReviewScopeLockLease> {
  const ownerToken = randomUUID();
  const deadline = Date.now() + options.acquireTimeoutMs;

  while (true) {
    try {
      if (await tryAcquireLease(database, scopeId, ownerToken, budget)) {
        activeOwnerTokens.add(ownerToken);
        return { database, scopeId, ownerToken };
      }
    } catch (error) {
      if (!isSqliteBusy(error)) throw error;
    }
    if (Date.now() >= deadline) {
      throw new Error('Review changes are busy in another app process; retry shortly.');
    }
    await sleep(Math.min(options.retryIntervalMs, Math.max(1, deadline - Date.now())));
  }
}

Heartbeat from `ReviewPersistenceScopeLock.ts:387-394`:

const heartbeat = setInterval(() => {
  try {
    ownershipLost ||= !heartbeatLease(lease);
  } catch {
    // A final owner check distinguishes a transient busy database from a lost lease.
  }
}, resolvedOptions.heartbeatIntervalMs);
heartbeat.unref();

Stale owner detection from `ReviewPersistenceScopeLock.ts:225-237`:

async function isStaleOwner(row: ReviewScopeLockRow, budget: OwnerProbeBudget): Promise<boolean> {
  if (!isProcessAlive(row.owner_pid)) return true;
  const observedProcessStart = await getProcessStartedAt(row.owner_pid, budget);
  if (observedProcessStart !== null &&
      Math.abs(row.owner_started_at - observedProcessStart) > 10_000) {
    return true;  // PID recycled
  }
  return row.owner_pid === process.pid && !activeOwnerTokens.has(row.owner_token);
}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment