Repository navigation
Fix: bound moca-egress connections in time on CONNECT tunnels and the forward path - #619
Conversation
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]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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]>
|
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.
1 + 2: one clock, but direction-aware
I took the re-arm-free variant of your suggestion rather than the watchdog. The part I didn't expect. A plain per-connection clock broke So the forward path has three clocks split by direction, while the tunnel has one:
A correction on item 2's mechanismThe 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: The conn stays in the clock anyway — a deadline expiring on a connection whose bytes are moving contradicts what TestsThree new, all at 400ms bounds:
You were right that 3:
|
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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:
- Tunnel per-direction bound (must-fix): fixed.
splicenow shares onebothWaysidleClockacross 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. - 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 (guestReadingtouches only the guest's write deadline) keepsTestForwardStalledGuestBodyExpiresWhileUpstreamTalksmeaningful. A trickled response can't excuse a body the guest never sent. - Response-header default: fixed. It now defaults to the effective idle bound (
ConfigFromEnvandNewProxy), and a new test pins it. - 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 |
There was a problem hiding this comment.
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."
Summary
An established
moca-egressconnection had no time bound at all.servearms a read deadline for the request headers and then clears it (handler.go), and before this nothing replaced it:Readindefinitely —copyCountedhas a bare read loop;TransportsetDisableKeepAlives,DisableCompressionandMaxResponseHeaderBytesbut noResponseHeaderTimeout, so an upstream that accepts the connection and never answers hungRoundTripforever. There was likewise no deadline on the guest-side body read or onresp.Write(pc.c).A grep for
Set*Deadlinein the package returned exactly four calls, all inhandler.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.
MOCA_EGRESS_IDLE_TIMEOUT_S300MOCA_EGRESS_RESPONSE_HEADER_TIMEOUT_S30300s 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.goholds 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:
CloseWriteand then waits on a silent upstream would otherwise keep its slot indefinitely — the case the issue calls out.keptBody, not thecountingBodyit 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 newEventfield — 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:
TestActiveTunnelSurvivesManyIdlePeriodswhile the idle-tunnel test still passes — which is the point: the active test pins the refresh, not merely the presence of a bound;One mutation initially survived, and it found a real gap. Moving the guest-conn deadline down into the shared
countingBodypassed 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.TestForwardStalledGuestBodyExpiresWhileUpstreamTalksnow pins the placement and kills the mutation.Verification
go build,go vet,gofmt -l— cleango test -race ./...over the wholeremote-workermodule (what theprotojob runs) — pass, 17 packages, no racesinprocessand a real subprocess) — 30/30Honest 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 cloneagainst 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_Sis the longest name in that config table, so prettier re-pads column 1 across all 27 rows. Applied deliberately —prettier --checkis what CI enforces.Out of scope
control/client.go.headerTimeout/drainTimeout, the two existing unexported bounds inhandler.go. They work; this issue is about what happens after them.Assisted-By: Claude