Skip to content

Fix #1629: refuse a second Tower against a live global.db (owner lock) - #1689

Merged
amrmelsayed merged 19 commits into
mainfrom
builder/bugfix-1629
Sep 16, 2026
Merged

amrmelsayed merged 19 commits into
mainfrom
builder/bugfix-1629

Conversation

@amrmelsayed

@amrmelsayed amrmelsayed commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The port bind is only a same-port mutex, so a second Tower on a different port could open the same global.db (the #1515 incident: an AGENT_FARM_DIR typo pointed a test Tower at production; port is a CLI arg, the DB path comes from AGENT_FARM_DIR, and they are independent). Its startup reconcile then reconnected every live shellper socket (one client per shellper), stealing them from the real Tower, and the stale-row sweep deleted the rows. This adds a global.db owner lock that makes the second Tower refuse to start.

Fixes #1629

Root Cause

  • AGENT_FARM_DIR resolves from CODEV_AGENT_FARM_DIR only (packages/core/src/constants.ts); the mistyped env var was a no-op, so the test Tower opened the production ~/.agent-farm/global.db.
  • Neither ensureGlobalDatabase nor bootSequence checked for a live owner before reconcile. The port bind is a same-port mutex, so a Tower on a different port opened the shared DB and reconcile hijacked its shellpers.

Fix

An exclusive lock file next to the contended database, <global.db path>.tower-owner (so global.db.tower-owner, and test-<port>.db.tower-owner under test isolation — 1:1 with the DB file, so two isolated test Towers never share a lock; the suffix deliberately avoids SQLite's own -wal/-shm/-journal and dotfile-VFS .lock names). It carries the owner identity as JSON: pid, port, bindHost, hostname, startedAt, dbDir.

  • claimGlobalDbOwnership runs first in bootSequence, before getGlobalDb() opens the DB and before consolidation / reconcile / killOrphanedShellpers touch shared state, so a refused Tower never touches the database. It refuses with a loud, teaching error (naming the AGENT_FARM_DIR vs CODEV_AGENT_FARM_DIR fix) when a live Tower already owns the DB, and claims otherwise.
  • Atomic acquire: write the full record to a unique temp file, then hard-link() it onto the lock path. link() fails EEXIST if held, and the linked inode already carries complete content, so a concurrent starter never sees an empty/partial lock.
  • Liveness is a fail-closed, host-aware tri-state /health probe (tower / gone / unreachable): a 6s budget (the endpoint shells out to ps -A), 200 healthy or 503 STARTING_UP counts as a live Tower, and only a connection refusal or a non-Tower response claims. An inconclusive probe against a still-live pid is treated as live. The probe targets the owner's recorded bindHost (wildcard 0.0.0.0/::/[::] resolve to loopback) so a bridge-mode Tower is not missed.
  • A dead owner self-clears (dead-pid short-circuit), so the legitimate single-Tower restart is never blocked; the same-port shortcut also requires the bind interface to match (a wildcard and a loopback bind coexist on one port). Ownership is released pid-scoped on graceful shutdown.
  • No database change: no new table, no migration, no schema-version bump.

Test Plan

  • Regression test added (bugfix-1629-tower-owner.test.ts): decision matrix; real /health classification (Tower, 503 STARTING_UP, non-Tower garbage, degraded 5xx, connection-refused); the incident refuse; fail-closed on inconclusive; dead-owner / recycled-pid / corrupt-lock self-clear; bridge same-port refuse; atomic acquire (exclusive + no temp residue); fail-closed under contention; and a boot-order source guard (claim precedes reconcile / consolidation / killOrphanedShellpers, and refusal exits).
  • Build passes (pnpm build)
  • All tests pass (305 files / 6141 tests)

Review Disposition (3-way CMAP)

Reviewed across multiple CMAP rounds; every substantive item was fixed in-branch: the fail-open probe under load (6s host-aware tri-state, 503 STARTING_UP = live, inconclusive fails closed), the bridge same-port hijack (a wildcard 0.0.0.0:P and a loopback 127.0.0.1:P bind coexist — verified — so the same-address shortcut also requires the bind interface to match), and the atomic acquire (temp + link(), no empty-file window). Final verdicts converged to APPROVE aside from one design frontier below.

The design started as a singleton tower_owner table + migration v19; on request it was pivoted to this lock file to avoid any database change, since ownership is ephemeral process state (a cleanly-stopped Tower leaves nothing behind) and fits a lock file better.

Accepted residual (documented, not blocking): two Towers cold-starting simultaneously on different ports against a stale lock share an irreducible unlink-then-recreate window, because no filesystem compare-and-swap primitive exists without a native flock dependency. It is contained by bounded retry + fail-closed, and it is not the incident shape (the incident had a live owner, which is refused deterministically).

Filed as a separate "owner-lock robustness" follow-up: (1) surface the refusal to the CLI (afx tower start daemonizes, so today the loud error only reaches tower.log and reads as a generic timeout) — most urgent; (2) the graceful-shutdown same-address overlap via a pid-is-a-Tower identity check; (3) a --force / clear-owner escape hatch for a wedged owner. Items (2) and (3) ship together or not at all (phantom-pid coupling).

…wner lock)

The port bind is only a same-port mutex, so a second Tower on a different
port could open the same global.db (the #1515 incident: an AGENT_FARM_DIR
typo pointed a test Tower at production). Its startup reconcile then
reconnected every live shellper socket (one client per shellper), stealing
them from the real Tower, and the stale-row sweep deleted the rows.

Add a singleton tower_owner record inside global.db (pid, port, hostname,
started_at, db_dir). The boot guard runs first in bootSequence, before
consolidation/reconcile/killOrphanedShellpers touch the shared DB, sockets,
or production shellpers: it refuses to start (loud, teaching error naming the
AGENT_FARM_DIR vs CODEV_AGENT_FARM_DIR fix) when a live Tower already owns the
DB, and claims ownership otherwise. Liveness is a Tower-shaped /health probe on
the owner's port; a dead owner self-clears so the legitimate single-Tower
restart is never blocked. Ownership is released (pid-scoped) on graceful
shutdown.

Guard-only per scope ruling; the reconcile-delete hardening (rows deleted on a
merely-failed reconnect) is tracked separately.

- db/tower-owner.ts: owner record + liveness + claim guard + conflict message
- db/schema.ts, db/migrations.ts: tower_owner table; migration v19 (18 -> 19)
- servers/tower-server.ts: guard at bootSequence start; release on shutdown
- tests: owner decision matrix + real /health probe; v19 migration convergence
…iter 1)

CMAP flagged that the liveness probe failed OPEN: /health shells out to `ps -A`
(5s) plus getInstances(), so a 1.5s budget times out under the incident's load
(60+ shellpers) and was read as "stale, claim it" — the hijack proceeds. The
owner's ~20s mid-boot window (readiness gate holds /health) had the same hole.

- Replace the boolean probe with a tri-state probeTowerHealth: 'tower' (200
  healthy OR 503 STARTING_UP mid-boot) | 'gone' (connection refused, or a
  non-Tower response) | 'unreachable' (timeout / transport error). Budget 6s,
  paid only on the conflict path.
- ownerIsLive refuses unless the probe is definitively 'gone'; an inconclusive
  probe against a still-live pid is treated as a live owner (fail closed). The
  dead-pid short-circuit keeps the legitimate restart self-clearing.
- readTowerOwner rethrows any error other than "no such table" so a real DB
  fault fails the boot closed instead of masquerading as an unowned DB.
- Add a boot-order source guard (claim precedes reconcile / consolidation /
  killOrphanedShellpers, and refusal exits) plus 503-STARTING_UP and
  fail-closed test cases; source guard now also asserts Migration v19.
…k (CMAP iter 2)

CMAP iter 2 (Codex) flagged that the liveness probe hardcoded 127.0.0.1: a Tower
bound only to a specific non-loopback BRIDGE_TOWER_HOST would answer there, so the
loopback probe gets ECONNREFUSED, reads 'gone', and lets the second Tower claim —
reopening the destructive path for bridge-mode deployments.

The v19 tower_owner table is unshipped, so extend it in place (no migration churn):
persist the owner's bind_host and probe it. A wildcard bind (0.0.0.0 / ::) accepts
loopback so it still probes 127.0.0.1; a specific bridge host is probed directly.

- tower_owner gains bind_host (schema + migration v19); TowerOwner.bindHost
- resolveProbeHost() maps wildcard/empty binds to loopback, keeps specific hosts
- probeTowerHealth takes (host, port); ownerIsLive probes the resolved bind host
- claimGlobalDbOwnership persists bindHost, threaded from tower-server's bindHost
- tests: resolveProbeHost mapping, bind-host persist, bridge-host detection
…(PR CMAP)

PR CMAP surfaced two real guard-correctness defects:

1. The owner.port === myPort shortcut skipped the liveness probe, but a wildcard
   bind (0.0.0.0:P, a bridge owner) and a loopback bind (127.0.0.1:P, a second
   Tower) coexist on the same port — both listen() succeed — so a bridge owner
   was hijacked. The shortcut now also requires bindHost to match (an identical
   interface:port bind is exclusive, so it proves the prior owner gone); a
   differing interface falls through to the pid + probe path, which detects the
   live wildcard owner via its recorded bind host.
2. The claim was a blind read -> probe -> upsert, so two cold-start contenders
   could both overwrite the singleton and proceed. Acquisition is now atomic: an
   empty table is claimed with a plain INSERT (the singleton PK makes a second
   inserter lose and re-evaluate), a stale owner is taken over with a
   compare-and-set guarded on the observed row, and a lost race re-evaluates
   behind the winner. The invariant preserved is never overwriting a LIVE owner.

- ownerIsLive gains myBindHost; the shortcut is interface-scoped
- claimGlobalDbOwnership: INSERT-if-empty / CAS-take-over-if-stale, no blind upsert
- tests: bridge same-port refuse, two-connection concurrency (no double-claim,
  duplicate singleton INSERT throws, CAS take-over of a stale row)
…ardening (PR CMAP 2)

PR CMAP round 2 flagged the last fail-open path and two safety nits:

- claimGlobalDbOwnership no longer blind-overwrites after a lost CAS. It now
  loops read -> liveness -> conditional-write up to a bound; a losing attempt
  re-evaluates (the new writer may be a live owner), and persistent contention
  REFUSES rather than overwriting. Deterministic regression: a probe that
  rewrites the row on every attempt drives exhaustion and asserts we refuse.
- probeTowerHealth maps a non-STARTING_UP 5xx to 'unreachable' (a degraded but
  live owner must not read as absent / 'gone').
- resolveProbeHost maps the bracketed IPv6 wildcard [::] (what validateHost
  emits) to loopback, alongside 0.0.0.0 and ::.
…able

Per Amr's request to avoid database changes. The owner record is ephemeral
process state (a cleanly-stopped Tower leaves nothing behind), so durable schema
was a poor fit and forced a migration. Move it to an exclusive lock file next to
global.db (`<db path>.lock`), which travels with the exact file being contended,
keeps CODEV_AGENT_FARM_DIR isolation, and gives two isolated test Towers on
different DB files distinct locks.

- New storage: JSON lock file carrying the same identity (pid, port, bindHost,
  hostname, startedAt, dbDir). Acquisition is an atomic O_EXCL create; stale
  takeover is read -> probe -> (if stale) compare-and-unlink -> O_EXCL re-create
  in a bounded loop, so a race loser re-reads the live winner and refuses. No
  blind unlink, no rename-replace, no heartbeat. Released pid-scoped on graceful
  shutdown. The guard now runs before global.db is opened, so a refused Tower
  never touches the shared DB.
- Removed the tower_owner table from GLOBAL_SCHEMA, migration v19, and the
  version bump (GLOBAL_CURRENT_VERSION back to 18); reverted the source guard and
  deleted the migration test. No database change remains.
- Liveness logic (dead-pid self-clear, tri-state /health probe, bind-host
  handling, fail-closed) is unchanged; tests rewritten for the lock file incl.
  O_EXCL exclusivity, corrupt-lock recovery, and fail-closed contention.
…(PR CMAP)

CMAP flagged that writeFile({flag:'wx'}) exposes an empty file between create and
write: a concurrent starter could read it as corrupt, delete it mid-write, and
both acquire. Replace the acquire with the canonical write-temp-then-link:

- tryAcquire writes the FULL record to a unique temp file, then hard-links it
  onto the lock path. link() is atomic and fails EEXIST if held, and the linked
  inode already carries complete content, so a reader never sees an empty/partial
  lock (which also removes the corrupt-classification-deletes-a-live-holder
  window Claude noted). The temp is always cleaned up.
- On persistent contention the refusal names a real observed contender, never our
  own pid (Claude).

Stale takeover keeps the compare-and-unlink + bounded-retry + fail-closed shape
(the residual simultaneous-cold-start-against-a-stale-lock window is the accepted
one; no filesystem compare-and-swap primitive exists without a native flock dep).
…honest 503 note

Non-blocking CMAP minors:
- resolveProbeHost strips brackets from a specific IPv6 literal ([::1] -> ::1);
  http.request's hostname rejects brackets, which otherwise made the probe never
  conclusive for an IPv6 bridge owner.
- tryAcquire falls back to an O_EXCL create on filesystems without hard links
  (ENOSYS/EPERM/EXDEV) so boot never fails on an exotic FS.
- Soften the 503 STARTING_UP comment: a mid-boot Tower usually holds /health past
  the probe budget (times out to 'unreachable', also refused); the 503 branch is
  the within-budget case. Either way a live owner.
- Add deterministic coverage that a contender's live lock is never deleted during
  stale takeover (the compare-and-set re-read refuses behind it), and IPv6 strip.
…le-VFS collision

The lock was <db>.lock. SQLite's unix-dotfile VFS (a fallback on filesystems
without POSIX locks) creates exactly <db>.lock, so on such a mount our lock and
SQLite's would collide. Verified better-sqlite3's default WAL path creates only
<db>-wal / <db>-shm (no .lock), but rename defensively to a suffix SQLite never
generates: <db>.tower-owner (avoids -wal/-shm/-journal/-mj* and the dotfile .lock).
Added a test asserting the name matches no SQLite auxiliary pattern.
@amrmelsayed
amrmelsayed merged commit 6538d5d into main Sep 16, 2026
7 checks passed
amrmelsayed added a commit that referenced this pull request Sep 16, 2026
amrmelsayed added a commit that referenced this pull request Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tower: a second Tower started against a live global.db hijacks and deletes every production shellper session

1 participant