Skip to content

Fix: keep the egress control connection when a call outlives its ctx - #621

Merged
cwiklik merged 1 commit into
rossoctl:mainfrom
cwiklik:fix/587-keep-control-conn
Oct 27, 2026
Merged

cwiklik merged 1 commit into
rossoctl:mainfrom
cwiklik:fix/587-keep-control-conn

Conversation

@cwiklik

@cwiklik cwiklik commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Summary

moca-egress is one shared host process and vmpool talks to it over one shared control connection, so one slow call used to cost the whole host. When a call gave up with its reply still pending, the stream was out of step and do() dropped the connection — and the server's dropConn unbinds every VM that connection owned, which makes Proxy.Unregister close each VM's listener and abort() its live connections. An open git clone in an unrelated microVM failed, until the heal loop re-registered about healMin (100 ms) later. client.go already documented this and named the fix as a follow-up.

A call that gives up now keeps the connection. clientConn counts the replies whose caller gave up, and the per-connection reader discards exactly that many, so the stream comes back into step on its own and the next call is unaffected.

No wire change. Every call holds Client.mu, so the stream is strictly one-request-one-reply and FIFO: the Nth reply belongs to the Nth request, and a count is enough to match them. The issue's alternative — a request id on ControlRequest/ControlReply — would be additive on the wire and would permit concurrent calls, but nothing needs that today and it costs a proto change, regenerated gen/go, a server change and an MI1 §8.3 table amendment.

The abandonment is carried as its own error type so do() can tell it from a genuine transport fault, with Unwrap keeping errors.Is(err, context.DeadlineExceeded) working for callers that test for one. An abandoned call is not retried: its budget is spent, and a retry would spend another against a server just shown to be too slow.

The consequence the issue does not mention

server.register sets s.bindings[vm] = sc before it calls s.h.Register. With the connection kept, a Register the client abandoned can still complete server-side, so moca-egress ends up holding a binding — and the VM's listener fd — for a VM the client never recorded in c.live. The launcher does not compensate (egressRegistered is only set after success). VM IDs are monotonic and never reused, so the orphan is inert, but it is an fd leak in the shared egress process, unbounded in time under a sustained stall — the same failure class as #586, so it is closed here rather than noted.

A background reaper sends a compensating Unregister, on the client's existing wg/stopCtx machinery and with the same backoff as the heal loop. An Unregister for a VM that was never bound is a no-op (Proxy.Unregister returns nil for an unknown vm), so reaping a Register the server in fact refused costs one harmless round trip.

Two deviations from the plan, called out rather than left to be inferred

1. The symmetric Unregister orphan is not real, so it is not handled. The plan assumed an abandoned Unregister could leave the server still holding a VM the client forgot. It cannot: call writes the request frame before it waits, so a successful write means the server reads and processes the Unregister even though nobody is left waiting for the reply. Client and server converge on their own. Only Register diverges. The planned queueing and its test were dropped rather than ship code that could not be pinned with a test.

2. One mutation survived and is not covered by a test. Moving the hand-off to replies back outside cc.mu survived -race -count=20. It is a pure interleaving bug, not a memory race — both sides still take cc.mu and the channel supplies its own synchronization, so -race has nothing to flag, and killing it needs the reader parked between its unlock and its push while a caller abandons. That window is a few instructions wide with no seam to steer it. The lock placement stays as correctness by construction, with the losing interleaving spelled out in the comment (reader sees owed == 0 and unlocks → caller gives up and records owed = 1 → reader pushes anyway, so the channel holds a stale reply and a discard is owed, and the next call reads the wrong answer). No test covers it.

No P4.1 amendment item. Unlike #585, this adds no knob, no default and nothing an operator configures; the wire format, the message set and the audit shape are all untouched.

Tests

  • TestCallTimingOutMidFlightKeepsTheConnection replaces TestCallTimingOutMidFlightHealsTheConnection, which pinned exactly the behaviour being removed. It asserts what must not happen: vm-1 is never unbound (nothing on unregs for 500 ms), c.conn is the same pointer, c.healing is false, and vm-1's listener still accepts — with closeOnUnregister set, so closing that listener is exactly what an unbind would have done.
  • TestAnOwedReplyIsNotDeliveredToTheNextCall — gates a Register the handler will refuse, abandons it, then registers a fresh VM that must succeed. If the owed refusal leaked into replies, the fresh call returns someone else's verdict.
  • TestAnAbandonedRegisterIsReapedFromTheServer — proves vm-2 really was bound server-side, then waits for held() to converge on exactly [vm-1] and stay there, so the reaper does not go on to unbind vm-1.
  • TestAReplyThatLandsAsTheCallGivesUpIsNotOwed and TestAnOwedReplyIsDiscardedExactlyOnce drive clientConn directly, with no server. The first exists because the mutation it kills (abandon always owed++, skipping the drain) survived -count=20 against a real server — a gated handler cannot be steered into that window, but the invariant is deterministic, so this is where it gets pinned.
  • A gate rather than a sleep holds the call mid-flight, the deterministic pattern rebind_test.go already uses. newGatedRecorder releases on t.Cleanup: a parked handler holds Server.wg, so a test failing before it released would wedge Server.Close until the package timeout.
  • TestAlreadyCancelledCallNeverTouchesTheConnection (I1) passes unchanged.

Honest scope note. "The other VMs' tunnels stay intact", which the issue asks for literally, is asserted here as vm-1 is never unregistered and its listener still accepts. The control package cannot use the real egress.Proxy as its Handler without an import cycle (egress imports control). That Unregister is what aborts live tunnels is pinned separately by TestUnregisterAbortsInFlightTunnels (proxy_test.go). The two together cover the chain; neither alone does.

Verification

Check Result
go build ./..., go vet ./..., gofmt -l clean
go test -race ./internal/egress/control/ -v 21 PASS, 0 FAIL
go test -race -count=2 ./internal/egress/control/ pass
go test -race ./... (whole module, what CI's proto job runs) pass, 12 packages
Conformance (-run Conformance) 26/26, identical count before and after
prettier --check . clean

Mutation testing

# Mutation Outcome
M1 reader treats an owed reply as "unsolicited reply" killed by two tests
M2 do still calls dropConn on an abandonment killed — as a hang, not an assertion: the drop triggers heal, which replays vm-1 into the still-gated handler and wedges on the server's hmu. That drop→heal chain is the #587 blast radius, so the kill is genuine
M3 no orphan reaper killed — the server holds [vm-1 vm-2], want exactly [vm-1]
M4 an abandoned Unregister queues no orphan dropped — deviation 1 above; the case does not exist
M5 abandon skips the already-landed drain survived -count=20 against a real server → killed deterministically by the new clientConn unit test
M6 the push to replies moved outside cc.mu survived, uncovered — deviation 2 above

Fixes #587

Assisted-By: Claude Code

One slow Register used to sever every in-flight tunnel on the host. When a
control call gave up with its reply still pending, the stream was out of step,
so do() dropped the connection -- and the server's dropConn unbinds every VM
that connection owned, which makes Proxy.Unregister close each VM's listener and
abort its live connections. An open git clone in an unrelated microVM failed,
until the heal loop re-registered about healMin later.

A call that gives up now keeps the connection. clientConn counts the replies
whose caller gave up, and the per-connection reader discards exactly that many,
so the stream comes back into step on its own and the next call is unaffected.
This needs no wire change: every call holds Client.mu, so the stream is strictly
one-request-one-reply and FIFO, and a count is enough to match them. The
abandonment is carried as its own error type so do() can tell it from a genuine
transport fault, with Unwrap keeping errors.Is(err, context.DeadlineExceeded)
working for callers that test for one.

Keeping the connection loses a cleanup the drop did for free. The server binds a
VM before it calls the handler, so a Register the client abandoned can still
complete server-side, leaving moca-egress holding a binding -- and a listener fd
-- for a VM the client never recorded. A background reaper sends a compensating
Unregister, on the same wg/stopCtx machinery and with the same backoff as the
heal loop; an Unregister for a VM that was never bound is a no-op, so reaping a
Register the server in fact refused costs one harmless round trip. Only Register
diverges this way: an abandoned call wrote its request frame before it waited,
so a queued Unregister is still read and processed.

TestCallTimingOutMidFlightHealsTheConnection pinned exactly the behaviour being
removed and is replaced by TestCallTimingOutMidFlightKeepsTheConnection, which
asserts what must NOT happen -- vm-1 is never unbound and its listener still
accepts. Two unit tests on clientConn pin the owed-reply state machine
directly, including the reply that lands as the call gives up.

Fixes rossoctl#587

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from pdettori as a code owner October 26, 2026 23:52
@cwiklik cwiklik added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 27, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Before this change, an abandoned control call dropped the shared connection and unbound every VM on the host (#587). The owed-reply count is sound: serveConn is strictly serial, with one reply per frame, so FIFO matching by count is enough. The take/abandon locking is correct, including the drain for a reply that lands in the abandon window. The Register orphan reaper closes the fd-leak gap that a kept connection opens. I agree an abandoned Unregister can't diverge, because a partial write is still a transport fault.

Two suggestions on the reaper are inline. One nit is outside the diff: vmpool/launcher_firecracker.go:421-423 still says an abandoned Register "costs the shared control connection (which the client then heals)". The "harmless (the server unbinds everything a lost control connection owned)" rationale at :357-359 and :1250-1251 now covers only transport faults. Abandoned calls are harmless for a different reason: the frame was written.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: Go (egress control client + tests), Docs (MI1 spec §8.3)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing

if !errors.As(err, &ae) {
return
}
c.orphans[vmID] = struct{}{}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: A successful Register doesn't clear c.orphans[vmID], and reap doesn't check c.live. If an ID is abandoned and then re-registered successfully before the reaper runs, the reaper's Unregister unbinds a VM that is still in c.live. The heal loop never repairs that, because the connection stays up. vmpool IDs are monotonic, so it's latent today, but it's cheap to close: delete(c.orphans, vmID) on Register success, or skip ids present in c.live in reap.

delete(c.orphans, vm)
backoff = healMin
} else {
backoff = min(backoff*2, healMax)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: The reaper is silent. During a sustained stall it re-abandons every ≤ healMax. Each attempt queues another Unregister on the server and adds owed++, with only the socket buffer bounding it. Meanwhile the orphaned listener fd held by moca-egress goes unreported. Consider logging the first abandoned reap attempt, the way heal logs its first failure, and possibly log on settle too. Optionally, also cap owed.

@cwiklik
cwiklik merged commit 057e664 into rossoctl:main Oct 27, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

egress control client: keep the connection when a call outlives its ctx

2 participants