Skip to content

Fix: bound moca-egress connections in time on CONNECT tunnels and the forward path - #619

Merged
cwiklik merged 2 commits into
rossoctl:mainfrom
cwiklik:fix/585-egress-idle-deadlines
Oct 27, 2026
Merged

cwiklik merged 2 commits into
rossoctl:mainfrom
cwiklik:fix/585-egress-idle-deadlines

Conversation

@cwiklik

@cwiklik cwiklik commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Summary

An established moca-egress connection had no time bound at all. serve arms a read deadline for the request headers and then clears it (handler.go), and before this nothing replaced it:

  • a CONNECT tunnel's two copy loops block in Read indefinitely — copyCounted has a bare read loop;
  • the forward path's per-request Transport set DisableKeepAlives, DisableCompression and MaxResponseHeaderBytes but no ResponseHeaderTimeout, so an upstream that accepts the connection and never answers hung RoundTrip forever. There was likewise no deadline on the guest-side body read or on resp.Write(pc.c).

A grep for Set*Deadline in the package returned exactly four calls, all in handler.go, none past the header read. So one guest could pin all 32 of its connection slots — plus an upstream socket each, in a host process every VM shares — for the VM's lifetime. Unbounded in time.

#586 (PR #614) bounded the refusal path's descriptors; this bounds the admitted path's time.

Both defects were verified by reading the code on main, not taken from the issue text.

Fixes #585

Two knobs, because the quantities differ in kind

A five-minute silent gap mid-transfer is ordinary. Five minutes to send response headers is not.

Variable Default Bounds
MOCA_EGRESS_IDLE_TIMEOUT_S 300 an established connection with no byte moving, either direction, either path
MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S 30 the wait for a forwarded request's response headers

300s matches squid's request_timeout. Zero is rejected rather than read as "no bound" — an established connection unbounded in time is the defect, not a configuration an operator may pick.

The one invariant that matters

The idle bound is refreshed on every read and every write, never armed once. An absolute deadline would kill a slow but healthy git clone; a refreshed one cannot, because every byte pushes it out. deadline.go holds the three wrappers each path goes through — a reader, a writer, and a conn for the Transport (which writes the request, reads the headers and streams the body on its own schedule, with the proxy out of the loop for all three).

Two placement decisions that are not arbitrary:

  • Both tunnel legs, and writes as well as reads. A half-close leaves exactly one leg running, so a guest that sent CloseWrite and then waits on a silent upstream would otherwise keep its slot indefinitely — the case the issue calls out.
  • The guest conn's bound sits on keptBody, not the countingBody it embeds. That struct is shared with the response body, whose reads come off the upstream conn. Put the deadline there and an upstream that keeps talking would refresh the deadline guarding the guest's connection.

No audit change

An expiry ends a connection exactly as any other copy error does, and a header timeout lands on the existing 502 upstream_unreachable. So no new decision value and no new Event field — MI1 §8.5's audit shape is untouched, and unlike P4.1 amendment item 8, this owes no audit-shape change.

Tests

Seven unit tests and two conformance cases (connect_tunnel_idle_deadline, forward_response_header_timeout, both pinned with the // pinned against: comment the suite uses). The tests set both knobs, so one bounding a given path cannot pass because the other fired.

The eight mutations from the plan were each reintroduced and shown to be caught. The two that carry the most weight:

  • arming the deadline once instead of per read kills TestActiveTunnelSurvivesManyIdlePeriods while the idle-tunnel test still passes — which is the point: the active test pins the refresh, not merely the presence of a bound;
  • bounding only one tunnel leg is caught solely by the half-close test.

One mutation initially survived, and it found a real gap. Moving the guest-conn deadline down into the shared countingBody passed every test I had written: HTTP/1.1 serializes the two bodies, so an upstream read never overlaps a guest-body read, and the slow-reader test is bounded by the conn's write deadline, which that mutation does not touch. A duplex probe distinguishes it — guest promises a 1000-byte body and sends none while the upstream trickles a response: clean code truncates at 1 byte, the mutant relays all 8. TestForwardStalledGuestBodyExpiresWhileUpstreamTalks now pins the placement and kills the mutation.

Verification

  • go build, go vet, gofmt -l — clean
  • go test -race ./... over the whole remote-worker module (what the proto job runs) — pass, 17 packages, no races
  • 15 conformance cases × 2 targets (inprocess and a real subprocess) — 30/30

Honest limitation

These tests pin in-process behaviour with short timeouts. Nothing here demonstrates that 300s is the right production number — that is a judgement about real upstreams (a large repo being packed server-side before the first byte of the pack arrives, an inference endpoint thinking), not a measured result. No real git clone against a slow-packing server is exercised. The knob exists so an operator who disagrees can move it.

Note on the MI1 diff size

The MI1 spec diff is ~60 lines of pure whitespace for 2 lines of content: MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S is the longest name in that config table, so prettier re-pads column 1 across all 27 rows. Applied deliberately — prettier --check is what CI enforces.

Out of scope

Assisted-By: Claude

An established moca-egress connection had no time bound at all. serve arms a
read deadline for the request headers and then clears it, and before this
nothing replaced it: a CONNECT tunnel's two copy loops block in Read
indefinitely, and the forward path's per-request Transport set no
ResponseHeaderTimeout, so an upstream that accepts and never answers hung
RoundTrip forever. One guest could therefore pin all 32 of its connection
slots -- plus an upstream socket each, in a host process every VM shares --
for the VM's lifetime. rossoctl#586 bounded the refusal path's descriptors; this
bounds the admitted path's time.

Two knobs, because the quantities differ in kind. A five-minute silent gap
mid-transfer is ordinary; five minutes to send response headers is not.

  MOCA_EGRESS_IDLE_TIMEOUT_S             300   (squid's request_timeout)
  MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S   30

The idle bound is refreshed on every read and every write, never armed once:
an absolute deadline would kill a slow but healthy clone, and a refreshed one
cannot. deadline.go holds the three wrappers every path goes through -- a
reader, a writer, and a conn for the Transport, which writes the request,
reads the headers and streams the body on its own schedule.

Both tunnel legs are bounded, and writes as well as reads, because a
half-close leaves exactly one leg running: a guest that sent CloseWrite and
then waits on a silent upstream would otherwise keep its slot. On the forward
path the guest conn's bound sits on keptBody rather than the countingBody it
embeds, which the response body shares -- upstream reads must not refresh the
deadline guarding the guest's connection.

No new audit decision value and no new Event field: an expiry ends a
connection as any other copy error does, and a header timeout lands on the
existing 502 upstream_unreachable. MI1 §8.5's audit shape is untouched.

Seven new tests, two conformance cases, and the eight mutations the plan
called for, each shown to be caught. One mutation -- moving the guest-conn
deadline into the shared countingBody -- initially survived, because a
serialized exchange never overlaps the two bodies; the duplex test added for
it now kills it.

Refs rossoctl#585

Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from pdettori as a code owner October 26, 2026 19:56
@cwiklik cwiklik added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 26, 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.

Thanks — the structure here is careful and the mutation-tested keptBody placement is a nice catch. One blocking issue, though, and it hits the exact case the PR sets out to protect.

The idle bound is per direction, but the PR (code comments, IdleTimeout doc, P4.1 amendment 9, MI1 §8.5) promises a per-connection bound ("no byte moving, either direction"). Each wrapper refreshes only the deadline of the socket it reads or writes, so a silent reverse direction expires even while the other direction is streaming. The result: a long one-way transfer (git clone / large download over HTTP/1.1-in-TLS, or a large upload with a silent upstream) dies after MOCA_EGRESS_IDLE_TIMEOUT_S. Details inline for the tunnel and forward paths. TestActiveTunnelSurvivesManyIdlePeriods can't see this because it echoes, so both directions move.

Suggested shape: one per-connection activity clock (atomic last-activity bumped on every read/write of either conn), enforced by a watchdog that closes both conns when it goes stale (or by re-arming on os.ErrDeadlineExceeded while the other side is active), plus a one-way streaming test on each path.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: Go (egress, conformance), Docs (specs)
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing

pipe := func(dst net.Conn, src net.Conn, sr io.Reader, n *atomic.Int64) {
defer wg.Done()
if err := copyCounted(dst, src, n); err != nil {
if err := copyCounted(idleWriter{c: dst, idle: idle}, idleReader{r: sr, c: src, idle: idle}, n); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: Each leg arms the read deadline only on its own src. Nothing the other leg does refreshes it. In a git clone or large curl download over HTTP/1.1-in-TLS, the guest sends nothing while the pack streams down. So the guest→up leg's Read(client) hits the deadline after idle, copyCounted returns the timeout, and closeBoth tears down a healthy transfer. A large upload with a silent upstream (git push) fails the same way, mirrored.

That contradicts the invariant in deadline.go/IdleTimeout ("no byte moving, in either direction") and amendment 9. Suggest a shared per-connection activity clock (atomic last-activity bumped on every read/write of both legs), enforced by a watchdog that closes both conns when now-last > idle, or by re-arming on errors.Is(err, os.ErrDeadlineExceeded) while the other leg is active. Please add a one-way test too: the upstream writes a byte every idle/2 for about 4×idle while the guest sends nothing, and the tunnel must survive. TestActiveTunnelSurvivesManyIdlePeriods echoes, so it can't catch this.

// ResponseHeaderTimeout covers only the gap before the headers --
// an upstream that sends them and then stalls mid-body is bounded
// here and nowhere else.
return idleConn{Conn: up, idle: idle}, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix (same root cause): http.Transport starts persistConn.readLoop at dial time. It blocks in br.Peek(1) → idleConn.Read while the request is still being written. That read deadline is set once at the Peek and request-body writes never refresh it, so a forwarded POST/PUT whose upload takes longer than idle fails with a 502 even though bytes move the whole time. The activity clock suggested on connect.go should cover the guest conn and this upstream conn together.

DisableKeepAlives: true,
DisableCompression: true,
MaxResponseHeaderBytes: maxHeaderBytes,
ResponseHeaderTimeout: pc.p.cfg.ResponseHeaderTimeout,

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: 30s to response headers is tight for plain-HTTP non-streaming inference endpoints. An in-cluster vLLM/Ollama completion can easily take longer than that before the first header byte. The PR body names "an inference endpoint thinking" as a quiet stretch the idle bound has to outlast, but on the forward path this knob fires first. Consider defaulting it to the idle bound, or at least documenting the trade-off next to the knob.

// exists to prevent. An absolute deadline, or one armed once before the copy
// loop, would kill a slow but healthy transfer -- a large repo being cloned.
// Only a deadline refreshed on every read lets this pass.
func TestActiveTunnelSurvivesManyIdlePeriods(t *testing.T) {

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: These idle tests run 150ms bounds with 2ms polling under -race on shared CI runners. Somewhat larger margins (300–500ms) would make scheduler-induced flakes less likely, at little cost in runtime.

The idle bound added for rossoctl#585 armed a deadline on whichever socket each
wrapper happened to touch. That is a bound on one direction of one socket,
not on the connection, and real traffic is one-way for long stretches:
during a git clone the guest sends nothing for as long as the pack takes to
stream down, so the guest->up leg's own read expired and closeBoth tore down
a healthy transfer. The IdleTimeout doc, P4.1 amendment 9 and MI1 section 8.5
all promised the opposite.

One byte now pushes out every deadline that byte proves is still live, via an
idleClock that names its targets per kind of activity. Which deadlines a byte
vouches for is per path, because only the forward path can tell the directions
apart:

  - A tunnel is opaque, so any byte either way keeps the whole of it alive.
  - On the forward path, relaying a response proves the guest is *reading* and
    must not excuse a request body it promised and never sent, so a response
    write refreshes the guest's write deadline alone. Request-body reads do
    carry the upstream conn, since http.Transport has its read loop blocked on
    that conn from the dial and a slow upload is guest-side activity only.

No watchdog goroutine: a socket deadline applies to calls already blocked in
Read or Write, so writing the clock through to the sockets is the enforcement.
That also keeps every expiry an ordinary timeout error, which serve's loop and
splice's copy-error arm already classify, rather than the ErrClosed a Close
would produce, and adds no per-connection goroutine to a process every VM on
the host shares.

ResponseHeaderTimeout now defaults to the idle bound rather than 30s, and
tracks an operator-raised MOCA_EGRESS_IDLE_TIMEOUT_S. The slot is bounded
without it, so a tighter default bought no safety while turning legitimate
slow thinking into a 502: a plain-HTTP inference endpoint, or a forge packing
a large repo, can take minutes before its first header byte.

Three tests cover the one-way cases, which the existing echo-based tunnel test
structurally could not reach. Reintroducing the per-leg bound kills both
tunnel tests. The forward upload test is weaker and says so in its comment:
net/http swallows the readLoop's Peek error while a request is in flight, so
dropping the upstream conn from the request-body clock does not fail it. That
conn stays in the clock on the invariant, not on the assertion.

Also widens the idle tests' bounds from 150ms to 400ms, since they run under
-race on shared runners where a scheduling hiccup between a write and the
deadline it refreshes decides pass or fail.

Addresses the review on rossoctl#619.

Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

Both must-fix items confirmed in the code and fixed in f50aa2b. Thanks — item 1 was a real bug and item 2 led somewhere interesting.

# Item Status
1 connect.go:51 per-leg deadline kills one-way transfers Fixed
2 forward.go:121 Transport readLoop Peek not refreshed by body writes Fixed (with a correction, below)
3 ResponseHeaderTimeout too tight for inference endpoints Fixed — defaults to the idle bound
4 Widen 150ms test bounds Fixed — 400ms

1 + 2: one clock, but direction-aware

idlePair/extendRead/extendWrite are gone. One byte now pushes out every deadline that byte proves is live, via an idleClock that names its targets per kind of activity.

I took the re-arm-free variant of your suggestion rather than the watchdog. SetDeadline applies to calls already blocked in Read/Write, not just later ones, so writing the clock through to the sockets is the enforcement. It also keeps every expiry an ordinary timeout error — which serve's loop and splice's copy-error arm already classify correctly — rather than the ErrClosed a watchdog's Close would produce, and adds no per-connection goroutine to a process every VM on the host shares.

The part I didn't expect. A plain per-connection clock broke TestForwardStalledGuestBodyExpiresWhileUpstreamTalks, and it was right to break: relaying a response to a guest genuinely does move bytes on the guest conn, so a per-connection clock carries the stalled upload through. Your "cover the guest conn and this upstream conn together" is correct for the forward path's request direction and wrong for its response direction.

So the forward path has three clocks split by direction, while the tunnel has one:

  • tunnel — opaque, so any byte either way keeps the whole of it alive.
  • guestSending (request-body read) — guest conn and upstream conn, per your item 2.
  • guestReading (response write) — the guest's write deadline only. It must not reach the guest's read deadline, or a guest could promise a body, send none, and ride a trickling upstream.
  • upstreamTalking — upstream conn only, the mirror.

A correction on item 2's mechanism

The 502 doesn't actually fire today. I mutation-tested it by dropping the upstream conn from the request-body clock, and the slow-upload test still passed: net/http swallows the readLoop's Peek error while a request is in flight, so that expiry never reaches the caller.

The conn stays in the clock anyway — a deadline expiring on a connection whose bytes are moving contradicts what IdleTimeout promises, regardless of whether today's Transport surfaces it, and it would surface if that ever changed. But the comment and the test doc now claim only what's true rather than the 502, since a comment asserting a failure mode that can't happen is worse than no comment.

Tests

Three new, all at 400ms bounds:

  • TestOneWayTunnelDownloadSurvivesASilentGuest — exactly your proposal: a byte every idle/2 for 4×idle, guest silent throughout.
  • TestOneWayTunnelUploadSurvivesASilentUpstream — the git push mirror.
  • TestForwardSlowUploadSurvivesASilentUpstream — the forward path.

You were right that TestActiveTunnelSurvivesManyIdlePeriods structurally couldn't catch this: it echoes, so the guest's own pings refresh both legs and it passes either way. I verified the new ones aren't the same no-op by reintroducing the per-leg bound — it kills both tunnel tests (0.40s each, i.e. the bound firing mid-transfer). The forward upload test is the weak one, for the reason above, and says so in its comment.

3: ResponseHeaderTimeout defaults to the idle bound

Agreed, and I went with your first option rather than documenting the trade-off. The knob is new in this PR, so nothing depends on 30s; the slot is bounded without it, since the idle clock covers the upstream conn from the dial; and an upstream legitimately slow to its first header byte gets a surprise 502 for no safety gain.

It defaults to the effective idle bound, not the compiled-in one, so raising only MOCA_EGRESS_IDLE_TIMEOUT_S carries it along and never leaves a tighter bound hiding behind it. TestResponseHeaderBoundFollowsARaisedIdleBound pins that. An operator who'd rather fail fast still sets it lower.

4: margins

All seven 150ms sites → 400ms, with a note in idleHarness on why the margin is there rather than the tightest value that works. Egress suite goes 6s → 18s; cheaper than a flake.

Docs

The promise and the mechanism now agree, which was the root of your review. P4.1 amendment 9 gained the per-connection statement, the per-path direction rules, the no-watchdog rationale and the header-timeout default; MI1 §8.5 item 2 and its config table match.

Verification: go test -race ./... clean across all 12 packages, conformance 30/30 (same as baseline, confirmed by stashing), prettier --check . clean, go build/vet/gofmt clean.

@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.

Follow-up review at f50aa2b.

f50aa2b is a single commit on top of aefd09f (fast-forward, same base 002f8b5). All 4 aefd09f items are fixed and checked against the code:

  1. Tunnel per-direction bound (must-fix): fixed. splice now shares one bothWays idleClock across both conns. Every read or write on either leg pushes out both conns' read and write deadlines, so one-way downloads and uploads survive. Two new one-way tests (TestOneWayTunnelDownloadSurvivesASilentGuest, …UploadSurvivesASilentUpstream) cover the case our review described. The echo test couldn't see it.
  2. Forward upload (must-fix): fixed. Request-body reads (guestSending) now refresh the upstream conn's deadlines as well. The author found that the 502 doesn't surface today, because net/http swallows the readLoop Peek error while a request is in flight. They corrected the comment and the test doc to match, which is fair. The direction split (guestReading touches only the guest's write deadline) keeps TestForwardStalledGuestBodyExpiresWhileUpstreamTalks meaningful. A trickled response can't excuse a body the guest never sent.
  3. Response-header default: fixed. It now defaults to the effective idle bound (ConfigFromEnv and NewProxy), and a new test pins it.
  4. Test margins: fixed. All 150ms bounds are now 400ms.

No watchdog goroutine is needed. SetDeadline applies to calls that are already blocked, so expiries stay ordinary timeout errors on the existing teardown paths. Docs (P4.1 amendment 9, MI1 §8.5 and its config table) now describe a per-connection bound.

Author: cwiklik (MEMBER, maintainer)
Areas reviewed: Go (remote-worker/internal/egress), Docs (specs). Incremental diff aefd09f..f50aa2b only.
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (all checks green at f50aa2b)

IdleTimeout time.Duration
// ResponseHeaderTimeout bounds how long a forwarded request may wait for
// its response headers after the request is sent. Separate from
// IdleTimeout, and strictly tighter: it treats a silent upstream that has

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: The doc still says "Separate from IdleTimeout, and strictly tighter", but the default is now equal to the idle bound, and the next paragraph argues against defaulting it tighter. Suggest something like "Separate from IdleTimeout, and no looser by default: an operator may set it tighter to treat a silent upstream as a fault sooner."

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.

moca-egress: idle deadlines on CONNECT tunnels and the plain-HTTP forward path

2 participants