Repository navigation
fix(upgrade): adopt the inherited listener sockets instead of closing them - #1362
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 20, 2026 10:38
FlorentinDUBOIS
force-pushed
the
fix/upgrade-inherited-listener-fd
branch
4 times, most recently
from
September 20, 2026 12:30
1c2bea7 to
faa7d67
Compare
517 `file.rs:NNN` anchors across `bin/src/command/LIFECYCLE.md`, `lib/src/protocol/kawa_h1/LIFECYCLE.md`, `lib/src/protocol/mux/LIFECYCLE.md`, `lib/src/protocol/proxy_protocol/LIFECYCLE.md` and `lib/src/protocol/udp/LIFECYCLE.md` were read against the code they point at. 310 did not need a line number and are now symbol anchors; of the 207 that name a specific statement or branch, 171 had to be renumbered and 36 were already right. A line number has no anchor, so it rots the moment anyone edits above it, and nothing resolves it: a mechanical scan for a missing target, a line past EOF or a blank line flagged only 27 of the 517. The two drift patterns measured in issue #1335 account for nearly all of the rest — single-line anchors off by +1 from the `//!` module-doc line added at the top of each source file after the documents were written, and ranges off by tens to thousands of lines from the TigerStyle `debug_assert!` campaign and the growth of `lib/src/protocol/mux/h2.rs`, where the drift reaches +2165. The convention now matches `lib/src/protocol/tcp_preread/LIFECYCLE.md`, which was already written this way and is why it needed no repair. Where the prose names an item the anchor is that item plus its file, with a method qualified `Type::method` so it is greppable; a line or range survives only where the claim is about a statement or a branch inside an item. Bare basenames that were ambiguous repo-wide (`server.rs`, `backends.rs`, `upgrade.rs`) are now repo-root-relative. Each of the five preambles states the convention and the date the surviving numbers were refreshed. No prose claim was rewritten to match code. Four stale claims surfaced on the way — `Server::run`, `upgrade_main`'s file, `ListenerAnswers` / `ClusterAnswers` and the mux "inline removal" list — and are anchored correctly but left for a separate pass. `doc/` is untouched. Rebased onto 95c5f37 (#1369), whose H2 timer-ownership move drifted five more citations in these same documents. Four were caught by the guard landing in #1371 -- `editor.rs:561-621`, `h2.rs:6045-6047` and `manager.rs:555-567` twice, each now resolving to a blank line -- and are re-anchored on `HttpContext::on_request_headers`, the three `ConnectionH2` frame handlers that decrement `active_requests`, and `UdpManager::handle_timeout`. The fifth the guard cannot see, and it is the more instructive one: `shrink_trailing_recycle`'s "single call site at `mod.rs:616`" now lands on `HttpContext::new`, 58 lines short of the real call at `mod.rs:674`. A citation that drifts onto a different non-blank line passes the check -- the checker says so in its own output -- which is why the anchor is now `Mux::create_stream`. The rebase also took the `mux/LIFECYCLE.md` backend-timeout tracker from 95c5f37, whose description is current, but symbolised its two citations rather than keeping either side's numbers: `mod.rs:773` had come to land on unrelated doc prose and `mod.rs:1279` on a `gauge_add!` call. Refs #1335 Signed-off-by: Florentin Dubois <[email protected]>
A line number carries no anchor, so a `file.rs:NNN` citation rots the moment anyone edits the file it points into. The pull request that breaks it is almost never the pull request that contains it, so no reviewer is ever shown both halves. #1335 measured 29 of 35 citations wrong in one audited document. Add `.github/scripts/check_doc_citations.py` and wire it as the non-experimental `Doc citations` CI cell. It resolves every citation under `doc/**` and `**/LIFECYCLE.md` and fails on a missing file, an ambiguous basename, a line below 1 or past end of file, a blank line at either end of a range, an inverted range, or the same line repeated inside one citation group -- the last being what a `/` or `,` continuation renumbered on one half only looks like. Its extraction pattern keeps a digit in the character class, without which every citation naming a file whose name contains one is skipped: on `lib/src/protocol/mux/LIFECYCLE.md` the digitless class sees 78 of the 201 occurrences that are there. A cited path resolves against the document's own directory first, so a module `LIFECYCLE.md` keeps citing its siblings by bare name. `--self-test` asserts the exact failures a deliberately broken fixture must produce, and the exact citation total, and -- because classifying a failure and acting on it are different lines -- runs the real command line in a subprocess requiring exit 1 on that fixture and exit 0 on a clean one. The cell asserts that exit code in a step of its own. The fixtures carry a digit-bearing `h2.rs` and a `mod/LIFECYCLE.md` whose citations resolve only through the sibling-directory rule, so each of the four one-line ways to make this checker report a clean run over a quietly smaller surface -- `if failures:` -> `if False:`, dropping the digit from the pattern, dropping `**/LIFECYCLE.md` from the scan, dropping sibling-directory resolution -- fails the self-test. Repair `doc/`: all 106 citation groups across 9 files were read against the code they point at. 74 became symbol anchors, which cannot drift; of the 32 that survive as line anchors, 24 were renumbered and 8 were already right. Five landed on a blank line -- the only class a mechanical scan sees. The rest resolved to a valid line in the wrong place, which is what actually misleads a reader and what the checker cannot catch: `doc/README.md` now states that limit, and the two narrower ones, next to the local run instructions. Correct three stale citations outside the guarded surface, where nothing will catch them later: `CLAUDE.md`'s logging bullet cited ten surviving `macro_rules!` definition sites and every one had moved, `socket.rs:86/133` included -- a trait method declaration and a line inside a macro body. `command/src/channel.rs` and `bin/README.md` cited a UDP-frontend invariant comment and a `ChannelError` variant for the state-file save format and the `max_buffer_size` ceiling. The comment in `lib/src/protocol/mux/h2.rs` pointing at the inbound `stream_last_activity_at` refreshes named SETTINGS-ACK tracking instead of `handle_data_frame` and `handle_headers_frame`; it is rewritten at its original line count, because two anchors elsewhere name lines below it. No prose claim was rewritten to match the code; four that have gone stale are recorded in the changelog entry instead. Line anchors were refreshed against `main` at `ba7fa5f9` on 2026-09-20. Signed-off-by: Florentin Dubois <[email protected]>
`log_socket_context!` built its `peer=` slot from `$self.socket_ref().peer_addr().ok()` — a live `getpeername(2)` — while its module-level twin `log_socket_module_prefix` already preferred the address the handler had cached. The split fell along the handler, not the layer: the macro has exactly one production caller, `impl SocketHandler for FrontRustls`, whose thirteen expansions are every SOCKET line a TLS frontend emits, while every plaintext frontend and every backend socket reaches the free function through `SessionTcpStream`. So on a PROXY-protocol HTTPS frontend the MUX-H2 line named the client and the SOCKET line named the load balancer, for one and the same connection. That was an artefact of `FrontRustls` having carried no cached address before `SocketHandler::peer_addr` and `FrontRustls::configured_peer` landed, not a deliberate split; `doc/observability.md` recorded it as a follow-up rather than fixing it, because nothing asserted the `peer=` slot of a SOCKET line. The slot is now `SocketHandler::peer_addr`, same cached-then-live preference as the rest of the stack. It is spelled as a fully-qualified trait call to foreclose a latent hazard, not to fix a present one: `$self.peer_addr()` compiles clean today and passes every test, because no current expansion sits on a raw `mio::TcpStream` and `FrontRustls` has no inherent `peer_addr` for method resolution to prefer. Add an expansion on a bare `TcpStream` and the unqualified form silently picks mio's inherent method — measured on a probe, that slot renders `peer=Ok(127.0.0.1:33587)` beside `local=Some(..)`, an `io::Result` where every other expansion renders an `Option`. `local`, `rtt`, `state` and `protocol` are untouched. The missing assertions are the substance of the change, and there are three. Two unit tests pin the macro's slot, one per half of the defect: `socket::tests::log_socket_context_renders_the_cached_peer_not_a_live_lookup` covers a live lookup that succeeds and disagrees, and also asserts `local=` stays `getsockname(2)`; `socket::tests::log_socket_context_renders_the_cached_peer_when_the_live_lookup_fails` covers one that fails, staged with a never-connected socket because only that refuses `getpeername(2)` deterministically — a socket waiting on an RST is a race this suite already declines to assert on. Against the pre-fix macro they render the loopback address and `peer=None` respectively. `e2e::tests::socket_log_context_tests::test_tls_socket_log_peer_is_the_advertised_client` drives a real PROXY-v2 header through the real accept path. It provokes rather than raises a level — the opposite of its MUX-H2 sibling — because every `log_socket_context!` expansion is an `error!` and a healthy TLS session emits no SOCKET line at any level: it corrupts one TLS record once the mux is established. Keeping the connection ESTABLISHED, now asserted rather than assumed, is what makes the negative assertion discriminate: only while `getpeername(2)` still succeeds can a slot name the raw TCP peer. Measured against the unfixed tree: 1 SOCKET line, 0 naming the advertised client, 1 naming the raw TCP source. The same edits shifted `lib/src/socket.rs` by +13 lines at `udp_connect`, which moved `udp/LIFECYCLE.md`'s `socket.rs:1081-1083` anchor onto a blank line. That anchor never pointed at `udp_connect`: on `origin/main` those lines are a `BrokenPipe` arm inside `FrontRustls::socket_write`, so this was pre-existing rot that the shift merely made detectable. Re-anchored to the symbol the prose already names, per `doc/README.md#citing-code-from-these-documents` — a symbol survives every edit above it. Spelled identically to the same line on `docs/lifecycle-citation-repair` so the two land without a conflict. Signed-off-by: Florentin Dubois <[email protected]>
Host is case-insensitive (RFC 9110 §7.2 / §4.2.3) but Sōzu normalised only one side of the comparison. `Router::add_tree_rule` and `DomainRule::from_str` lowercase every configured hostname through `idna::domain_to_ascii`; `Router::lookup` walked the routing trie with the client's raw bytes and compared `Exact`/`Wildcard` byte-exactly. Nothing between the wire and that walk touches the case either: kawa slices the authority verbatim, `HttpContext::on_request_headers` copies it verbatim, and `hostname_and_port` strips the port and nothing else. So `Host: WWW.EXAMPLE.COM` missed a frontend declared `www.example.com`, and declaring the frontend uppercase did not help — it was lowercased on the way in too. `lookup` and `has_hostname` now normalise their key through a new `normalize_hostname`, which returns `Cow::Borrowed` for a host that is already lowercase so the datapath pays a scan and not an allocation. HTTP/1.1 and HTTP/2 reach the same `frontend_from_request` call, so one change covers both; each leg is exercised over a real socket, which the issue noted had never been done. `DomainRule::from_str` now compiles hostname regexes case-insensitively. `convert_regex_domain_rule` keeps the operator's source verbatim, unlike the trie, so matching a normalised key against a case-sensitive `/API[0-9]/` would have turned a rule that matched `API7.example.com` into one that matched nothing. It is set on the `RegexBuilder` rather than by folding the source, which would rewrite `\D` into `\d`, and `captures_len()` is unchanged so no `$HOST[n]` index moves. The fold is the crate default, Unicode simple case folding; `.unicode(false)` is deliberately not set, because it also refuses Unicode-class syntax and `\p{L}` matches ASCII letters, so a frontend that installs and routes today would start being rejected at add time. Two tests pin that and the ASCII-only input constraint that makes the choice unobservable on the haystack side. The same asymmetry exists on the TLS side with the two sides swapped: rustls lowercases the SNI before `ResolvesServerCert::resolve` is called, while `CertifiedKeyWrapper::try_from` stored SAN / `names` entries verbatim, so a certificate carrying `MiXeD.Example.COM` was reachable by no SNI at all and every handshake for it fell back to the default certificate. The names are normalised at that single construction point, and `query_certificate_for_domain` normalises its lookup to ask the same question a handshake asks. The TCP SNI preread routes and the `:authority`-versus-SNI 421 check were audited and are already symmetric. Left open deliberately, with a test recording the current answer so it fails and gets inverted the day it is closed: a trailing-dot Host (`www.example.com.`, the absolute form of RFC 1034 §3.1) still does not reach a frontend declared without it. Closes #1349 Signed-off-by: Florentin Dubois <[email protected]>
… them A worker upgrade hands the retiring worker's listening sockets to its replacement over SCM_RIGHTS. The replacement discarded all of them, on all four protocols. Server::new applied the initial state -- which generate_requests builds as one AddXxxListener immediately followed by one ActivateListener per active listener -- before it called receive_listeners(). scm_listeners was therefore still None for the whole initial state, so every ActivateListener took the server_bind / udp_bind branch and the listener came up active on a socket it had bound itself. That bind succeeds only because both helpers set SO_REUSEPORT, which is also why this never surfaced as an outage: the address kept being served throughout. The inherited descriptors arrived immediately afterwards, and UpgradeWorkerTask then scattered generate_activate_requests() to the new worker. Each repeat pulled its descriptor out of the SCM table -- Listeners::get_http and friends remove the entry as they hand it over -- wrapped it in an owning MioTcpListener / MioUdpSocket, and handed it to an activate() that returns on its `if self.active` guard before it can consume it. The wrapper dropped and the descriptor closed, once per listener per upgrade: the accept backlog for TCP/HTTP/HTTPS, so a connection that had completed its handshake against the old socket got an RST instead of being served, and the receive buffer for UDP. Three changes, one per place a descriptor could be lost. Server::new receives the SCM listeners before it applies the initial state, so the first ActivateListener adopts the inherited descriptor and the later repeats find nothing left to discard. No socket is replaced under a live listener: at that point the listener was created by the AddXxxListener on the line above and holds no socket at all. The relocated call is the same blocking read as before, only earlier -- the sole production caller of fork_main_into_worker, launch_new_worker, always passes Some(listeners) and always sends a manifest, so a fresh start receives an empty one immediately and every listener binds its own socket exactly as it always did. Ownership is settled before the descriptor leaves the table rather than after. Each arm of notify_activate_listener asks the proxy inherited_socket_fate(&address), which answers one of three things. Adopted -- a listener is there and not active -- takes it. Refused -- a listener is there and already active on a socket of its own -- takes it and closes it deliberately, with a warn naming the address. Not because it could never be adopted: give_back_listener clears active and keeps the listener object, so DeactivateListener then ActivateListener -- an operator-reachable feature covered by listener_reactivation_tests.rs -- brings that address back to Adopted, and scm_listeners is filled once and never refilled, so the close is irreversible. It is a trade. The descriptor carries only the connections queued on it at hand-off, whose value decays as those peers time out while the address is served by the listener's own socket; the cost of keeping it is continuous, because it stays bound with SO_REUSEPORT and registered with no event loop and is expected to go on taking a share of new connections nothing accepts. That expectation follows from SO_REUSEPORT load-balancing semantics and nothing here measures it, which the enum doc, the helper doc, the test doc and both operator-facing warn strings say too. Unclaimed -- no listener at the address -- keeps it, because an AddListener plus ActivateListener can still adopt it; that is how an upgrade whose initial state carries the listeners inactive works, so closing leftovers at the end of startup would destroy the case this commit fixes. No point during startup makes a leftover provably unclaimable, so retention stays open-ended and Server::new reports what it kept: info when the address has a listener awaiting activation, warn when it has none at all. A third copy lived on the registration-error path. activate() moved the socket into a local to register it and propagated a Registry::register failure straight from there, so the `?` dropped the local and closed a descriptor Listeners::get_* had already removed. All four activate() implementations now park that socket and reuse it on the next attempt instead of binding a second one. The park lives in a new parked_listener / parked_socket field, not in the listener's live socket field. Every other consumer reads that field's Some as "registered and live": give_back_listener hands it back as an activated socket and answers Ok, soft_stop and hard_stop deregister it and fold a failure into ProxyError::SoftStop / HardStop, accept accepts on it. Parking there made a listener that never came up look activated. Nothing but activate() reads the new field. If an inherited socket and a parked one ever coexist, the loser is closed explicitly and logged rather than dropped by an assignment. Listeners::get_udp gains the removal post-conditions its three siblings already assert. doc/upgrade_e2e_tests.md stated the old ordering as the root cause of its own scenarios, lib/src/protocol/udp/LIFECYCLE.md claimed the re-exec'd worker adopts the passed fd, and the comment in e2e/src/sozu/worker.rs justified its deactivate-then-activate sequence by the defect; all three are corrected. The citations this commit authors are symbol anchors rather than line numbers, following the convention PR #1366 established -- numbering them rotted twice across review rounds. The pre-existing citations it moves are re-anchored by content where the cited line is unambiguous, and turned into symbol anchors where the number resolved to something other than what its sentence names. Rebased onto the docs-citation stack. This commit adds 1242 lines to lib/src/server.rs, which drifts the two `epoll_time` citations in doc/lifetime_of_a_session.md onto a blank line; they are re-anchored on `names::event_loop::EPOLL_TIME` in `Server::run`. Neither this branch nor the citation guard could see that alone -- on this branch the citations read `server.rs:593-595` and `:594`, roughly 478 lines from the real site, and a citation that lands on a different non-blank line passes the check. Only the merged tree puts the range end on a blank line and fails. Closes #1342 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/upgrade-inherited-listener-fd
branch
from
September 20, 2026 19:15
faa7d67 to
86cafab
Compare
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.
Closes #1342.
The defect
On a worker upgrade every inherited listener file descriptor was closed unused, on all four
protocols.
SO_REUSEPORTmeant no outage — what was lost is the point of the hand-off: the acceptbacklog for TCP/HTTP/HTTPS, and the receive buffer for UDP. A client that completed its handshake
against the retiring worker's socket got an RST instead of being served.
Cause
CAUSE: lib/src/server.rs (the initial-state application ran above the receive) -> every initial-state ActivateListener saw scm_listeners == None and took the server_bind/udp_bind branch, which succeeds only via SO_REUSEPORT, setting active = true; the inherited fds arrived afterwards -> the next activate consumed and dropped them, because ScmListeners::get_* removes the entry (command/src/scm_socket.rs:473-528) and the caller has already wrapped the fd in an owning MioTcpListener/MioUdpSocket -> SYMPTOM: lib/src/http.rs:1300, lib/src/https.rs:1446, lib/src/tcp.rs:2382, lib/src/udp.rs:287 — "if self.active { return Ok(self.token); }" returns before it can consume the wrapper, which drops and closes the fd.The change
receive_listeners()now runs before the initial state is applied, so the firstActivateListeneradopts the inherited fd instead of binding its own. One protocol-agnostic change;the four
activatesignatures are untouched.Two properties were established before choosing this over giving
activatea hand-back path:fork_main_into_workercallssend_listenerswhenever
listeners.is_some(), and its sole production caller hardcodesSome(listeners.unwrap_or_default()), so a fresh start receives an empty manifest rather thannothing. The identical blocking read already existed, just later.
it has no channel dependency; nothing in it reads
scm_listenersor writes the SCM socket. Wireorder is preserved: the parent sends the fds inside
fork_main_into_worker, strictly beforelaunch_new_workersendsStatus.generate_requestsemitsAddXxxListenerimmediatelyfollowed by its
ActivateListener, so at adoption time the listener holdslistener: None, active: false.Test
scm_listener_handoff_testsdrives one hand-off covering all four protocols: it binds four "oldworker" sockets with the real
server_bind/udp_bind, queues a completed connection on eachTCP-family one and a datagram on the UDP one, ships all four fds over the SCM socket and closes the
sender's copies exactly as
fork_main_into_workerdoes, then drivesServer::newwith an initialstate of four
Add*Listener+ActivateListenerpairs.Seen red on the unfixed tree:
got []is the defect in one line: the accept queue was empty because all four listeners had boundtheir own sockets. Green after the fix.
The production hunk is pure code motion and shares no literal with the test, so the fix is not
test-shaped.
Correction to the issue text
#1342 states there is "zero
from_scm: trueanywhere in the tree". That is wrong — there are five,all in
e2e/. The field is nonetheless genuinely unread (142 construction sites, zero readers),so the dead-field conclusion stands; but it is a
requiredprotobuf field, so removing it is awire-format change across four crates and does not belong in this fix. Flagged as a separate LEANER
candidate.
Three of the four
activateline numbers cited in the issue had also drifted.Residual, deliberately not closed
activate()still drops an inherited socket silently if anActivateListenernames analready-active listener while
scm_listenersstill holds its fd. After this change that combinationis unreachable on the ordinary upgrade — the initial state consumes every fd whose address the main's
state marks active, and
generate_activate_requestsnames exactly those addresses. Reaching it wouldneed the retiring worker to have held a socket for an address the main's state does not mark active,
i.e. a partially applied deactivate.
Validation
BUILD=0 CLIPPY=0 TEST=0 FMT=0,test result: ok. 864 passed; 0 failed.Plus, by exact name:
tests::tests::test_upgrade_in_flight_requestandtests::command_channel_security_tests::scm_inconsistent_listeners_count_does_not_panic_server_constructor.Not reproduced on a live
sozu upgradewithss/lsof, as the issue itself suggests; the proof isthe in-lib hand-off test over real sockets and real
SCM_RIGHTS.