Repository navigation
Fix #1629: refuse a second Tower against a live global.db (owner lock) - #1689
Merged
Merged
Conversation
…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 ::.
…sion for the gate
…ot the builder's)
…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
added a commit
that referenced
this pull request
Sep 16, 2026
amrmelsayed
added a commit
that referenced
this pull request
Sep 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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: anAGENT_FARM_DIRtypo pointed a test Tower at production; port is a CLI arg, the DB path comes fromAGENT_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 aglobal.dbowner lock that makes the second Tower refuse to start.Fixes #1629
Root Cause
AGENT_FARM_DIRresolves fromCODEV_AGENT_FARM_DIRonly (packages/core/src/constants.ts); the mistyped env var was a no-op, so the test Tower opened the production~/.agent-farm/global.db.ensureGlobalDatabasenorbootSequencechecked 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(soglobal.db.tower-owner, andtest-<port>.db.tower-ownerunder 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/-journaland dotfile-VFS.locknames). It carries the owner identity as JSON:pid,port,bindHost,hostname,startedAt,dbDir.claimGlobalDbOwnershipruns first inbootSequence, beforegetGlobalDb()opens the DB and before consolidation / reconcile /killOrphanedShellperstouch shared state, so a refused Tower never touches the database. It refuses with a loud, teaching error (naming theAGENT_FARM_DIRvsCODEV_AGENT_FARM_DIRfix) when a live Tower already owns the DB, and claims otherwise.link()it onto the lock path.link()failsEEXISTif held, and the linked inode already carries complete content, so a concurrent starter never sees an empty/partial lock./healthprobe (tower/gone/unreachable): a 6s budget (the endpoint shells out tops -A),200 healthyor503 STARTING_UPcounts 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 recordedbindHost(wildcard0.0.0.0/::/[::]resolve to loopback) so a bridge-mode Tower is not missed.Test Plan
bugfix-1629-tower-owner.test.ts): decision matrix; real/healthclassification (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).pnpm build)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 wildcard0.0.0.0:Pand a loopback127.0.0.1:Pbind 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_ownertable + 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
flockdependency. 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 startdaemonizes, so today the loud error only reachestower.logand 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).