Skip to content

fix(tcp): stop re-arming frontend-readable on a routed SNI preread - #1387

Merged
FlorentinDUBOIS merged 4 commits into
mainfrom
fix/tcp-preread-backend-connecting-spin
Sep 21, 2026
Merged

FlorentinDUBOIS merged 4 commits into
mainfrom
fix/tcp-preread-backend-connecting-spin

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

A full frontend buffer while the backend is still connecting spun the datapath to
MAX_LOOP_ITERATIONS and closed a healthy session with bin: 16384, bout: 0.

CAUSE: tcp_preread/shell.rs, the `Output::Routed` arm of `SniPreread::handle_output`
       arms backend-WRITABLE but leaves `Ready::READABLE` in frontend_readiness.interest,
       while the shell from that point on deliberately reads nothing
   ->  the early return returns Continue without consuming the latched frontend READABLE
       event — latched because the capped read filled its slice exactly, so
       `tcp_socket_read` returned Continue and not WouldBlock
   ->  front_interest = interest & event stays readable on every pass of ready_inner's
       bounded loop
SYMPTOM: the MAX_LOOP_ITERATIONS guard closes the session.

One production line: self.frontend_readiness.interest.remove(Ready::READABLE);.

It masks the interest, never the event. That distinction is the whole fix:
upgrade_sni_preread carries frontend_readiness.event into the post-upgrade Pipe or
SendProxyProtocol, and under edge-triggered epoll that carried-over bit is the only
wake-up the coalesced tail ever gets — clearing the event would have traded the spin for a
hang. HUP/ERROR stay armed. MAX_LOOP_ITERATIONS is untouched.

This is the house shape, and only half of it had been copied here: proxy_protocol/relay.rs
and expect.rs both remove READABLE and insert backend WRITABLE as a pair once their own
header is parsed, and the pre-existing comment in shell.rs already claimed it mirrored
RelayProxyProtocol::readable's arm.

Verified independently of the authoring run, by commenting out that one line:

unit  FAILED  re-armed frontend-readable 4 times without consuming the event:
              this is the spin to MAX_LOOP_ITERATIONS
              (interest Readable | Error | Hup, event Readable, bin 16384)
e2e   FAILED  test result: FAILED. 0 passed; 1 failed
restored      both ok

The failure message reproduces the issue's worker log verbatim in field terms.

Test-shaped, stated plainly. The unit test shares two literals with the production diff
(frontend_readiness.interest, Ready::READABLE) and is close to tautological on its own.
The independent witness is the pre-existing e2e test, which contains zero occurrences of
either, never mentions readiness, and moved 0 pass / 5 fail → 5 pass / 0 fail on this
commit. Both are kept: the unit test fails in milliseconds and names the mechanism.

BUILD=0 CLIPPY=0 TEST=0 FMT=0 CITATIONS=0 — test result: ok. 917 passed; 0 failed.

Stacked on #1386; review the top commit.

Closes #1373

`AddCertificate.certificate.names` is a free `Vec<String>` that
`CertificateResolver::add_certificate` inserted into the SNI
`TrieNode<Fingerprint>` verbatim. That trie is the same
`lib/src/router/pattern_trie.rs` the HTTP router uses, where a
dot-separated label wrapped in `/.../` is compiled as a REGEX segment, so
a certificate declared for `/te.*/.example.com` was served for
`test.example.com` and for `tenant.example.com` alike -- one certificate
bound to an open-ended class of SNI values, with an inventory that shows a
SAN-shaped string.

The validation that existed could not catch it: it dry-runs every name
into a scratch trie and asks only whether the name INSERTS, which a regex
segment does. The check has to be on the name's bytes. `add_certificate`
now also refuses a name containing `/`, in the SAME pre-mutation block as
the `MAX_HOSTNAME_LENGTH` bound, returning
`CertificateResolverError::InvalidName`; nothing is half-registered. A
`/` cannot occur in a DNS name, so no legitimate SAN is lost, and an
ordinary `*.example.com` wildcard is not a regex segment and still loads.
This is the rule `config::validate_sni_pattern` already applies to every
path into the TCP SNI route table; the certificate trie was the one SNI
table left open.

Removal is unaffected: `remove_certificate` re-inserts the names a
certificate already carries and never re-validates them, so a certificate
an earlier build accepted stays removable.

`doc/configure.md` states the rule under "Hostname case" and
`CHANGELOG.md` tells an operator how to find an affected configuration --
the bundled CLI never sets the `names` override, so only a control plane
that fills it, or a saved state replaying one, can be affected.

Reported in #1378.

Signed-off-by: Florentin Dubois <[email protected]>
`add_tree_rule`, `remove_tree_rule` and `has_hostname` ran the WHOLE
configured hostname through `idna::domain_to_ascii`, regex segments
included. That function ASCII-lowercases, and lowercasing an uppercase
regex escape inverts the character class it names: measured,
`"/\D+/.example.com"` normalised to `"/\d+/.example.com"` and
`"/[^\D]/.example.com"` to `"/[^\d]/.example.com"`. `\D` is "not a
digit" and `\d` is "a digit", so the installed rule matched the exact
COMPLEMENT of what the operator wrote while `sozu query frontends` still
echoed the original spelling. Measured on the tree as it stood, the
frontend `/\D+/.rx.example.com` served `777.rx.example.com` and did not
serve `abc.rx.example.com`. `\W`/`\w` and `\S`/`\s` invert the same way.
Pre and Post never carried it: `convert_regex_domain_rule` copies a
segment's source verbatim and `DomainRule::from_str` takes its case
insensitivity from the `RegexBuilder` instead.

`tree_hostname_to_ascii` normalises the literal labels only and copies a
`/`-delimited segment byte for byte -- the split
`convert_regex_domain_rule` already makes and the one
`pattern_trie.rs`'s `insert_recursive` addresses a `regexps` entry by.
Per-label and whole-domain IDNA agree on a label (measured: `"MUNCHEN"`
with an umlaut maps to `"xn--mnchen-3ya"` either way), so a genuine
unicode label in a hostname that also carries a regex segment is still
punycoded. A hostname with no `/` at all, and one whose `/` does not
parse as that grammar (`abc/[0-9]+/.example.com`, `example.com/`), both
keep the historical whole-string call byte for byte.

Leaving the source unfolded moves the case fold onto the compile, and
that half is load-bearing: an uppercase literal such as `/API[0-9]/`
used to meet the ASCII-lowercased lookup key only because the source had
been lowercased too. `pattern_trie`'s `compiled_segment` wraps
`anchored_segment` and sets `case_insensitive(true)`, exactly as
`DomainRule::from_str` does, so literals fold and `\d`/`\D`, `\w`/`\W`
and `\s`/`\S` do not. `RegexBuilder` leaves `as_str()` as the pattern it
was handed, so `anchored_segment` remains the single source of a
`regexps` entry's identity, a stored segment stays removable, and
`captures_len` -- and therefore every `$HOST[n]` rewrite index -- is
unchanged.

This changes existing rules. A trie-routed frontend spelling `\D`, `\W`
or `\S` has been matching the complement of its source and now matches
what it says; a rule tuned against the folded behaviour must be
respelled with the lowercase escape it actually meant. `/API[0-9]/`
keeps matching exactly the hosts it matched before.
`doc/configure.md` and `CHANGELOG.md` carry the migration note in this
changeset.

Regression tests, each seen red on the unfixed tree:
`a_tree_hostname_regex_escape_is_not_case_folded`,
`every_inverting_uppercase_regex_escape_survives_a_tree_insert`,
`a_unicode_label_is_punycoded_while_its_sibling_regex_segment_is_not`,
and `compiled_segment_folds_case_without_respelling_its_identity`.

Closes #1377

Signed-off-by: Florentin Dubois <[email protected]>
… map

The per-frontend tag cache was written under the frontend RULE's hostname
(`listener.set_tags(front.hostname, front.tags)` in `lib/src/https.rs` and its
twin in `lib/src/http.rs`) and read back under the REQUEST's authority
(`listener.get_tags(hostname)` in `lib/src/protocol/mux/stream.rs`). The store is
a `BTreeMap<String, CachedTags>` and the read is `self.tags.get(key)`: exact key,
no pattern resolution. For `*.example.com`, `/foo.*/.example.com` or any
Pre/Post rule string, the key written can never be produced by the key read, so
`get_tags` returned None and the configured tags were silently absent from every
access-log line of that frontend. Three ways to miss from the one asymmetry:
wildcard/regex, port (the read strips `:port`, the write does not) and case.

Resolve L7 tags through the router instead of through a parallel exact map, the
way `lib/src/tcp.rs` already builds `sni_tags_key` with the same function on both
sides. The router knows which frontend rule matched and is the only correct owner
of its tags; a request carries a concrete authority while tags are configured per
rule, so no string key can be spelled the same on both sides.

- `Router::add_http_front_with_hsts_origin` counts `tags` as a policy field, so a
  tagged frontend is stored as `Route::Frontend(Rc<Frontend>)` carrying
  `Rc<CachedTags>` rather than a tagless `Route::ClusterId`. Only a tagged
  frontend pays that shape.
- `Router::route_from_request` stashes `RouteResult.tags` on `HttpContext.tags`
  before every early return, so a redirect, a 401 and a backend-connect failure
  log them too. The `..` that dropped the field is gone with it.
- `Stream::generate_access_log` reads from there, keeping the authority lookup
  only as the fallback for a request that never reached routing at all.

The WS/WSS post-upgrade pipe keeps its own `tags_key` string, which only the TCP
SNI-preread path sets; on an HTTP/HTTPS listener it falls back to the listener
address and carries no frontend tags on any frontend shape. That is a separate
pre-existing miss, recorded in `doc/observability.md` rather than folded in here.

`a_wildcard_frontends_tags_reach_the_access_log_of_a_concrete_authority`
registers `*.example.com` with tags through `HttpProxy::add_http_frontend`,
routes `foo.example.com` through `Router::route_from_request`, emits through
`Stream::generate_access_log` and asserts on the rendered access-log line.

Repairs the 24 `file.rs:NNN` doc citations this changeset moved. Inserting a
field into `HttpContext` and an import above it shifts every line below them in
`lib/src/protocol/kawa_h1/editor.rs`, which `kawa_h1/LIFECYCLE.md` cites 21
times; the `RouteResult` stash shifts `mux/router.rs` below it, and the
`tags: None` test literal shifts `mux/answers.rs`. The CI resolver saw only the
two that happened to land on a blank line (`doc/benchmark.md`,
`doc/lifetime_of_a_session.md`) — it cannot see a citation that drifts onto a
different non-blank line, which is what the other 22 did.

Twenty-two are re-anchored on the symbol their sentence already names — the
struct, field, method or test — with the file path and no line number, because a
fresh number would rot at the next edit above it and the pull request that
breaks it is never the one that contains it. Two stay ranges and are renumbered
instead (`editor.rs:607-627`, `:628-631`): the prose there means the
Transfer-Encoding fold and the rejection predicate specifically, not the
function that holds them, which is the one case the convention keeps a range
for. `doc/benchmark.md` also loses a bare call-site line that the two symbols
around it already pin.

Closes #1379

Signed-off-by: Florentin Dubois <[email protected]>
A `protocol = "tcp"` listener with SNI routes parks the session in
`SniPreread` through the backend connect. Once routed, `readable` reads
nothing more by design: bytes past the routed window stay in the kernel
socket buffer so the post-upgrade `Pipe` replays the stream byte-for-byte.

`tcp_socket_read` returns `SocketResult::Continue`, not `WouldBlock`, when
it fills the capped slice it was handed -- exactly what a client that
coalesces its ClientHello with the first payload bytes produces -- so the
frontend READABLE event was latched at the moment of the decision with
nothing able to clear it. READABLE also stayed in
`frontend_readiness.interest`, so `front_interest = interest & event` in
`TcpSession::ready_inner` selected a dispatch that could never make
progress on every pass: the worker burned `MAX_LOOP_ITERATIONS`, emitted
`tcp.infinite_loop.error`, and closed a healthy connection with
`bin: 16384, bout: 0`. Deterministic on a release build, usually won on a
debug build, which is why it surfaced as an unreadable intermittent CI
failure rather than as a bug.

The routed transition now drops READABLE from the frontend INTEREST,
completing the `RelayProxyProtocol::readable` mirror the arm above already
claimed -- relay.rs drops READABLE on the line right before it arms
backend-writable, and only half of that pair had been copied here. The
latched EVENT is deliberately preserved: `upgrade_sni_preread` hands it to
the post-upgrade `Pipe` (`restore_readiness_events`) or
`SendProxyProtocol` (`into_pipe`), each of which re-inserts READABLE
interest, and under edge-triggered epoll it is the only wake-up the
coalesced tail will ever get -- clearing it would trade the spin for a
hang. HUP and ERROR stay armed. No metric, configuration key or CLI flag
changes.

Regression guard
`routed_preread_stops_re_arming_frontend_readable_while_connecting` drives
`ready_inner`'s exact re-entry predicate against a real socket and fails
on the unfixed tree in milliseconds; the release-profile e2e witness
`test_tcp_sni_large_payload_coalesced_with_hello_delivered_intact` went
from 0/5 to 5/5.

Fixes #1373

Signed-off-by: Florentin Dubois <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tcp_preread: a full frontend buffer while the backend is still connecting spins to MAX_LOOP_ITERATIONS (deterministic under --release)

1 participant