Skip to content

Fix: Name the process holding a pinned port, and stop looping silently - #1366

Merged
cwiklik merged 1 commit into
mainfrom
fix/supervise-port-conflict
Oct 13, 2026
Merged

cwiklik merged 1 commit into
mainfrom
fix/supervise-port-conflict

Conversation

@cwiklik

@cwiklik cwiklik commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A second Cortex install on one machine cannot start: the loopback ports are pinned
(47600–47604). All that was ever said about it was net.Listen's own line —

WARN forward-proxy listen: listen tcp 127.0.0.1:47600: bind: address already in use

— which names the address and nothing about who holds it. The supervisor then doubled
its backoff to 30s and repeated proxy exited; restarting … restart_in=30s there
forever: about 2,880 restarts a day, with no cause among them. The companion symptom
looks unrelated — requests reach whichever install won the port and are bridged with
its CA, so the agent reports a self-signed certificate rather than a connection
failure.

install.sh already refuses to install over a foreign proxy on the forward port
(#1104). This is the runtime case, which no install-time check can reach: the other
install may be started, or stopped, long after this one was set up.

What changed

The child classifies the failure, because it alone knows the failing address —
net.Listen puts it only in its message. reserveListeners now returns a
*listenError carrying the socket's name and address, and the new
cmd/cortex/portconflict.go names the holder from the kernel's own tables via
core/peerproc (no lsof, no ss, no root), then exits 3:

ERROR cannot start: another Cortex already holds this address
      listener=forward-proxy address=127.0.0.1:47600
      cause="listen tcp 127.0.0.1:47600: bind: address already in use"
      holder_pid=4812 holder=/Users/other/.cortex/bin/cortex holder_parent_pid=1
      reason="a local install's ports are pinned, so two Cortex installs on one machine cannot both bind them"
      fix="stop the other one — `agentop service stop` as the user who owns …"

Every branch keeps net.Listen's message verbatim in cause — the wording operators
have learned to search for. Unknown values are omitted rather than rendered as real
ones, and the Cortex-specific remedy is gated on the holder's basename, so a sidecar
that cannot bind :8080 in a pod is not sent looking for a laptop install.

The supervisor classifies that exit status and dampens. The condition is explained
once at ERROR; after the third consecutive bind failure the ceiling moves from 30s to
10 minutes (announced once); the per-restart line drops to DEBUG while that holds. It
never gives up — nothing restarts it until the next login, and the holder may stop
at any moment — and a healthy run resets the backoff and says so. Any other exit comes
straight back under the ordinary ceiling, so a crash loop that happens to follow a port
clash is not retried once an hour.

The division of labour is deliberate: the supervisor could have parsed the child's
stderr, but that turns a log line into a protocol. The exit status is the whole
contract.

agentop service status says it too, between "NOT answering" and the log tail —
the proxy's log explains it on every attempt, but that is five lines of supervisor
output and the one line that explains them should not have to be found in it:

Cortex is NOT answering http://127.0.0.1:47604/healthz
  127.0.0.1:47600 is held by ~/other/bin/cortex (pid 4812), not this Cortex
  That is another Cortex, so requests reaching it are bridged with ITS CA — which is the self-signed-certificate error agents report.
  Stop the job that runs it: com.rossoctl.cortex

Open question from the issue

The issue asks whether the ports should stop being pinned. Recommendation: no.
HTTPS_PROXY=http://localhost:47600 is a fixed contract the docs, agentop configure
and every configured agent depend on — and the bind-before-disk ordering in
listeners.go exists precisely because a taken port is the guard that stops two
proxies writing one ~/.cortex. Diagnostics are the right fix. Happy to open a
separate issue if multi-install support is wanted on its own merits.

Testing

New: cmd/cortex/portconflict_test.go (6 tests), cmd/cortex/supervise_test.go
(6 tests driving the whole policy through a run of failures rather than an hour of wall
clock), and two tests plus a stub helper in cmd/agentop/cmd_service_test.go. The
agentop tests stub lsof, redirect procRoot and stub launchctl, so the holder and
the remedy are pinned on both platforms and no assertion keys off runtime.GOOS.

Both touched modules, run per-module with GOWORK=off:

  • cmd/cortex — gofmt -l . clean, go vet ./... ok, go test ./... -count=1 ok (5.2s)
  • cmd/agentop — gofmt -l . clean, go vet ./... ok, go test ./... -count=1 ok (272s) and all ten subpackages green

Fixes #1122

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • Bug Fixes
    • Service status now identifies other processes occupying the proxy port and provides relevant guidance, including when another Cortex process may cause certificate errors.
    • Startup diagnostics now report which process is holding a required port and offer a suitable remedy.
    • Repeated port conflicts trigger progressively longer retries, while successful runs reset the delay.

A second Cortex install on one machine cannot start: the loopback ports are
pinned (47600-47604). All that was ever said about it was net.Listen's own
line, which names the address and nothing about who holds it — and the
supervisor then doubled its backoff to 30s and repeated that line there
forever, about 2,880 restarts a day with no cause among them (#1122). The
companion symptom looks unrelated: requests reach whichever install won the
port and are bridged with ITS CA, so the agent reports a self-signed
certificate.

The child classifies the failure, because it alone knows the failing address:
reserveListeners now returns a *listenError carrying the socket's name and
address, and reportListenFailure names the holder from the kernel's own
tables via core/peerproc — no lsof, no ss, no root — then exits 3. Every
branch keeps net.Listen's message verbatim in a cause field, the wording
operators have learned to search for. The Cortex-specific remedy is gated on
the holder's basename, so a sidecar that cannot bind :8080 in a pod is not
sent looking for a laptop install.

The supervisor classifies that exit status and dampens: the condition is
explained once at ERROR, the ceiling moves from 30s to 10 minutes after the
third consecutive bind failure (announced once), and the per-restart line
drops to DEBUG while it holds. It never gives up — nothing restarts it until
the next login, and the holder may stop at any moment — and a healthy run
resets the backoff and says so. Any other exit comes straight back under the
ordinary ceiling, so a crash loop following a port clash is not retried once
an hour.

`agentop service status` says it too, between "NOT answering" and the log
tail: the proxy's log already explains it on every attempt, but that is five
lines of supervisor output and the one line that explains them should not
have to be found in it.

install.sh's check covers the install-time case (#1104); this is the runtime
one, which no install-time check can reach.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9693ba1b-780f-415a-8dfe-9d0dc89c2d72
📥 Commits

Reviewing files that changed from the base of the PR and between 9e9b577 and 3fefd3c.

📒 Files selected for processing (9)
  • cmd/agentop/cmd_service.go
  • cmd/agentop/cmd_service_test.go
  • cmd/agentop/setup_runner.go
  • cmd/cortex/listeners.go
  • cmd/cortex/main.go
  • cmd/cortex/portconflict.go
  • cmd/cortex/portconflict_test.go
  • cmd/cortex/supervise.go
  • cmd/cortex/supervise_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

Listener conflicts now produce holder diagnostics and a distinct exit status. The supervisor adjusts retries for repeated bind failures. Service status reports identifiable foreign processes holding the forward-proxy port.

Changes: Port conflict handling

Layer / File(s) Summary
Classify and report listener conflicts
cmd/cortex/listeners.go, cmd/cortex/portconflict.go, cmd/cortex/main.go, cmd/cortex/portconflict_test.go
Listener reservation errors retain the listener name and address. Startup reports address conflicts, attempts to identify the holder, and exits with a distinct status. Tests cover error details, holder fields, probe addresses, and port formatting.
Adjust retries after bind failures
cmd/cortex/supervise.go, cmd/cortex/supervise_test.go
The supervisor distinguishes port-conflict exits from other failures, changes retry delays after consecutive bind failures, and resets retry state after a healthy run or unrelated failure. Tests cover policy behavior and delay limits.
Show port holders in service status
cmd/agentop/cmd_service.go, cmd/agentop/cmd_service_test.go, cmd/agentop/setup_runner.go
Service status includes the health URL, identifiable foreign-port-holder diagnostics, and the existing log tail. Tests cover holder cases and output order. setupEnv.tilde delegates path formatting to tildePath.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Supervisor
  participant CortexChild
  participant reserveListeners
  participant reportListenFailure
  participant peerproc
  Supervisor->>CortexChild: Start child
  CortexChild->>reserveListeners: Reserve configured listener
  reserveListeners-->>CortexChild: Return listenError for EADDRINUSE
  CortexChild->>reportListenFailure: Report listener failure
  reportListenFailure->>peerproc: Identify process at probe address
  peerproc-->>reportListenFailure: Return holder details or lookup error
  reportListenFailure-->>CortexChild: Exit with port-conflict status
  CortexChild-->>Supervisor: Return port-conflict exit status
  Supervisor->>Supervisor: Select retry delay and log note
Loading

Suggested reviewers: huang195, esnible

Merge Risk: ⚪ Minimal · up to 3fefd

No issue requiring a fix before merge was established. Service status may omit holder details for a second instance using the same binary, but the proxy log remains the documented diagnostic source.

Pre-merge checks · Passed 5
Passed Passed checks (5 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title accurately summarizes the main changes: identifying the process holding a pinned port and making repeated supervisor retries visible instead of silent.
Linked Issues check Passed The PR meets the coding requirements in [#1122]. listenError preserves the listener name, configured address, and original net.Listen cause. reportListenFailure identifies the holder through `co…
Out of Scope Changes check Passed The changes stay within [#1122]. The listener error type, holder lookup, supervisor policy, service-status output, and their tests directly implement the runtime conflict diagnosis and retry requireme…
Docstring Coverage Passed Docstring coverage is 86.67% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 9 files.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mrsabath mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostics-only change: the child classifies an EADDRINUSE bind failure, names the holder from kernel tables via core/peerproc, and exits 3; the supervisor reads that status to explain once and dampen the retry ceiling to 10 minutes; service status surfaces the same line.

The exit-status-as-contract split (rather than parsing the child's stderr) is the right call, and cause keeping net.Listen's wording verbatim on every branch preserves what operators search for.

What I verified

Checked against origin/main via git show — the local working tree was ahead 3081, behind 237, so nothing was read from it.

Claim Result
peerproc API (New, ListenerOwner, Proc.PID/PPID/Exe, ErrUnsupported) matches core/peerproc/peerproc.go exactly
"peerproc ranks exact bind ahead of wildcard, incl. the macOS IPV6_V6ONLY caveat" documented verbatim in the ListenerOwner interface comment
Double peerproc.New() retry has precedent same pattern at cmd/cortex/main.go:973-977
log.Fatalf "nothing on disk open yet" pre-existing comment at the bind site says the same; bind precedes pipeline Start and the ledger/archive open
slog.Error reaches the log bootstrap.InitLogging at main.go:338, bind at ~573
Helpers reused, not duplicated portHolder, ourProxy, holderJob, launchdBootout, portOfAddr all exist in setup_probe.go / setup_step_service.go

Dual-path parity. The new foreignHolderLines against the existing install-time preflight at setup_step_service.go:118-134: both call portHolder(port), both gate on ourProxy(binDir, proxy.pid, pid, exe), both use the identical holderJob/darwin/default remedy switch and the same "%s is held by %s (pid %d), not this Cortex" sentence. Same source, same guard, same wording — no divergence between the two times this condition is met.

Backoff equivalence. The refactor moves advance to before the wait and logs the pre-doubling n.delay, where the old code logged delay, waited, then doubled. Both yield 2s, 4s, 8s…, so "which is how the loop read before this was extracted from it" holds.

Timer hygiene. healthy.Stop() is called on both wait: exit paths and healthy.C fires at most once, so the added inner loop cannot spin or leak a timer.

Two things I probed as likely bugs and found correct by design

  • portHolder matches only loopback and wildcard binds, so a forwardAddr on a LAN address finds no holder. That limitation is inherited and documented on the existing helper, and the new caller returns nil rather than guessing — consistent with its own stated "empty when the holder cannot be named" contract.
  • holderFields omitting ppid <= 1 and ppid == pid is deliberate and covered by TestHolderFields_OmitsWhatIsNotKnown.

Notes

Areas reviewed: Go (cmd/cortex, cmd/agentop), tests, commit/PR conventions, security.
Commits: 1, signed off. Subject 70 chars, imperative, fix: prefix matching repo convention.
CI: all 29 checks passing (Spellcheck skipped).
Security: no secrets, no new dependencies, and no shell interpolation of untrusted input — portOf returns a <port> placeholder rather than an unparsable string, and holder paths only ever reach log fields and prose.

On the open question: agreed that the ports should stay pinned. HTTPS_PROXY=http://localhost:47600 is a fixed contract, and the bind-before-disk ordering in listeners.go depends on a taken port being the guard that stops two proxies writing one ~/.cortex. Diagnostics are the right fix here.

No inline comments — I looked for findings in every area and could not substantiate one.

@cwiklik
cwiklik merged commit 7821df6 into main Oct 13, 2026
30 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 13, 2026
@evaline-ju
evaline-ju deleted the fix/supervise-port-conflict branch November 18, 2026 06:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

The supervisor loops forever when another install holds the pinned ports, and never says so

2 participants