Skip to content

test(router): property harness for hostname resolution, proven against the four shipped routing bugs - #1407

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
test/router-property-harness
Sep 22, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
test/router-property-harness

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

lib/src/router/ is already sans-io — Router::lookup(&self, ...) takes &self, touches no socket
and no clock; the only Instant::now() calls feed a REGEX_MATCHING_TIME metric and never influence
a match. So there is nothing to extract here. What was missing was the test.

Four routing correctness bugs shipped and were found by hand in the days before this: #1349
(uppercase Host does not match a lowercase frontend), #1351 (an exact rule added after a matching
regex segment attaches to the regex leaf and leaks to every host it matches), #1356 (an alternation
in a hostname regex segment is only half-anchored), #1377 (idna::domain_to_ascii folds regex
escapes, inverting \D into \d). All four were found by reading pattern_trie.rs line by line.

The one property test this module had was dead:

/* FIXME: randomly fails
quickcheck! { fn qc_insert(h: HashMap<String, u32>) -> bool { hm_insert(h) } }
*/

and even alive it only checked exact-string insert/lookup against a HashMap oracle — no regex, no
wildcard, no case folding, no declaration order. It could not have caught any of the four.

The harness

qc_router_hostname_resolution_matches_the_documented_semantics.

The oracle is independent of the implementation. It never calls anchored_segment,
compiled_segment, TrieNode::lookup*, tree_hostname_to_ascii or convert_regex_domain_rule. It
is a linear scan applying the documented semantics directly, with its own exact → regex (in
declaration order) → wildcard precedence search and its own anchoring, using regex::bytes::Regex
only as a primitive the way the implementation does.

Its independence is stated honestly rather than assumed. The case-folding half is genuinely
derived from RFC 9110 §4.2.3. The \A(?:…)\z grouping half matches doc/configure.md's prose —
and that prose was itself added by the #1356 fix, so for the grouping convention the oracle and the
implementation share a source rather than the oracle checking an external spec. Both halves say which
they are, in the oracle's doc comment, so a reader knows what the harness can and cannot falsify.

The generator is biased toward the shapes that actually bit us: mixed exact/wildcard/regex at the
same hostname position; case varied independently on the rule and the query; uppercase regex escapes
(\D, \W, \S) which is #1377's shape; alternations, which is #1356's; a Gen-driven Fisher-Yates
shuffle of declaration order, which is #1351's; and path variation, which is what makes #1351
observable at all — see below. Queries cross every hit hostname against every distinct path declared
anywhere in the scenario, because #1351's leak crosses fronts.

Proving it bites: four reverts, four reds

Each is the exact "To SEE THIS RED" mutation named in the corresponding fix's own commit message.

#1377 — tree_hostname_to_ascii reverted to whole-string domain_to_ascii:

MISMATCH host="xADmIN.example.com" expected=None actual=Some("C3") declared=["/\\W+/.example.com"]

\W+ — not a word character — folded to \w+, matching an all-word-character host.

#1356 — anchored_segment's (?:...) group dropped:

MISMATCH host="apifoo.example.com" expected=None actual=Some("C0") declared=["/api|admin/.example.com"]

#1349 — normalize_hostname(hostname) reverted to Cow::Borrowed(hostname):

MISMATCH host="ADMIN.example.com" expected=Some("C1") actual=None declared=["admin.example.com"]

#1351 — TrieNode::lookup_mut's if !accept_wildcard { return None; } guard dropped:

MISMATCH host="UNMATCHED-HOST.example.com" path="/" expected=None actual=Some("C0")
  declared (in order, with path)=[("/\\S+/.example.com", "/other"), ("abc.example.com", "/")]

That last one only became a genuine mismatch after path variation was added. Without it, every
generated rule shared PathRule::Prefix("/"), so a literal whose insert would leak onto a regex leaf
found that leaf already carrying an identical (path, method) — add_tree_rule refused the insert
outright and the harness tripped its own defensive assertion at insert time instead of ever reaching a
lookup. The production symptom — a rule answering for a hostname nobody declared — was structurally
unreachable. A first version of this changeset shipped that way and claimed #1351 coverage; the claim
was not true, and the fix was to widen the generator rather than soften the prose.

qc_insert: revived, after finding out why it failed

Not deleted, and not assumed flaky. Root cause, established by execution:

hm_insert's skip filter excluded only the whole key "*". But TrieNode::insert_recursive's
dotless arm routes into self.wildcard whenever a key's leftmost label is "*" — so {"*.": 0}
lands in the wildcard slot, while hm_insert's lookup pass calls lookup(key, accept_wildcard: false),
which structurally cannot read that slot. Guaranteed "inserted but not found", on a key the generator
produces rarely. Shrunk counterexample: two characters.

This is a gap in the test's own exclusion list, not a router defect — * resolution is exercised
correctly elsewhere with accept_wildcard: true. The filter is now widened to any key whose leftmost
label is "*", and the reasoning is recorded in the function's doc comment. Verified stable across
120,000+ post-fix iterations; reverting the filter reproduces {"*.": 0} deterministically.

The defensive assertion, reworded

It previously read "harness bug, not a router bug: ... must always insert". That message steers a
maintainer toward distrusting the harness for exactly the bug family it exists to catch — #1351's own
mechanism can make that call return false. It now reports the refusal with full context as a
TestResult::failed() and assigns no blame.

A limitation, stated rather than hidden

quickcheck 1.1.0 seeds Gen::new from entropy with no exposed seed, and CI sets no
QUICKCHECK_TESTS, so a failing CI run here is reproduced by re-running with a raised iteration count,
not by replaying a seed. That sits awkwardly beside doc/testing.md's FoundationDB-style "exact
replay of a failing seed", which the moonpool simulators do honour via SOZU_*_SIM_SEED. Recorded in
the module doc and in doc/testing.md; not fixed here.

No behaviour change

Test-only. Every hunk is inside #[cfg(test)] mod tests; no non-test router code is touched.

Validation

cargo +1.93.1 build --all-features --locked                       -> exit 0
cargo +1.93.1 clippy --all-targets --all-features -- -D warnings  -> exit 0
cargo +nightly fmt --all -- --check                               -> exit 0
cargo +1.93.1 test -p sozu-lib --locked router                    -> 142 passed, 0 failed
python3 .github/scripts/check_doc_citations.py --base origin/main -> exit 0

Stability: 8 consecutive runs at default settings, plus one at QUICKCHECK_TESTS=10000 (109s), all
clean.

Refs #1349, #1351, #1356, #1377.

lib/src/router/ was flagged as the highest value-to-cost target for
deterministic testing in the whole codebase: Router::lookup(&self, hostname,
path, method) is already pure, and the only property test in the file,
pattern_trie.rs's qc_insert, was commented out with "FIXME: randomly fails"
and checked only exact-string insert/lookup against a HashMap oracle -- no
regex, wildcard, case folding or declaration-order precedence, so it could
not have caught any of the four hostname routing bugs fixed in the days
before this changeset (sozu#1349, #1351, #1356, #1377).

qc_router_hostname_resolution_matches_the_documented_semantics
(lib/src/router/mod.rs) is a new quickcheck property that would have. Its
oracle is independent of pattern_trie by construction: it is written fresh
from doc/configure.md's "Hostname precedence" and "Regex hostname segments"
sections, never by calling anchored_segment, compiled_segment,
TrieNode::lookup*, tree_hostname_to_ascii or convert_regex_domain_rule. It
uses the regex crate only as a primitive, exactly as pattern_trie does, to
build its own "\A(?:source)\z" case-insensitive anchoring and its own
exact/regex/wildcard precedence search. Every generated rule and query shares
a fixed two-label "example.com" suffix and MethodRule::new(None) -- method
stays fixed because sozu#1351's reproduction needed only path variation, and
method precedence already has its own tests.

The generator is biased toward the shapes that bit sozu, not uniform:
REGEX_CATALOG is a fixed table of regex-segment sources (alternations,
uppercase \D/\W/\S escapes, uppercase literals inside classes) each paired
with hand-verified hit/miss samples; LITERAL_POOL deliberately overlaps those
samples so an exact rule and an overlapping regex rule land in the same
scenario often enough to exercise sozu#1351 without a forced pairing; case is
varied independently on the declared rule and the query; declaration order is
a Fisher-Yates shuffle driven by the same Gen; and PATH_POOL gives each
generated front its own declared path, crossed against every path declared
anywhere in the scenario when building queries.

Path variation is not decorative -- an earlier version of this harness pinned
every rule to the same path, and a review caught that this hides sozu#1351's
actual production symptom rather than exercising it. With every rule sharing
one path, a literal whose insert would leak onto a regex leaf finds that leaf
already carrying an identical (path, method), so add_tree_rule's append-skip
condition is always false and the insert is refused before any lookup
happens -- the leak is real but observable only as add_tree_rule returning
false, never as a routing mismatch a future regression using a different
mechanism could slip past. Reproduced live against the reverted fix to
confirm the production shape: test4.example.com declared at /other after
/test[0-9]/.example.com at / leaks, so test7.example.com at /other wrongly
answers with test4's rule -- an exact-host rule answering for a hostname
nobody declared, sozu#1351's own wording. Varying path is what lets the
harness observe that instead of only the insert-time artifact.

Reverting each of the four fixes in turn -- the exact mutation each fix's own
commit message names as its "To SEE THIS RED" step -- reproduces a genuine
MISMATCH host=... path=... expected=... actual=... for every one, with a
shrunk minimal case:

- sozu#1349 (Router::lookup's normalize_hostname -> Cow::Borrowed): shrinks
  to a single Literal("xadmin") rule at path "/"; Host: XADMIN.example.com
  at "/" expects its cluster and gets None.
- sozu#1351 (TrieNode::lookup_mut's accept_wildcard guard dropped): shrinks
  to a Regex("\S+") rule at "/other" declared before a Literal("abc") rule at
  "/" (\S+ matches "abc", almost any ASCII label); an unrelated
  "UNMATCHED-HOST.example.com" at "/" expects no match and gets the literal
  "abc" rule's cluster -- the family-wide leak sozu#1351 reported, in an even
  more open form since \S+ matches nearly everything.
- sozu#1356 (pattern_trie's anchored_segment ungrouped): shrinks to a single
  Regex("a|b") rule at "/other"; "aBC.example.com" at "/other" expects no
  match (neither branch matches the whole label) and gets the half-anchored
  first branch's cluster.
- sozu#1377 (tree_hostname_to_ascii replaced with the whole-string
  idna::domain_to_ascii fold): shrinks to a single Regex("\D+") rule at "/";
  the letters-only "unmatched-host.example.com" expects a match (\D+ is
  "not a digit") and gets None once the folded source became \d+.

Each mutation was applied, the property run at QUICKCHECK_TESTS=5000 to
confirm red, reverted, and the property rerun to confirm green; git diff
against origin/main was checked after each revert to confirm no residue.
Stability: 8 separate default-settings runs (QUICKCHECK_TESTS unset, 100
cases each) plus one 10,000-case run are all clean after the path-variation
widening.

The defensive check around add_tree_rule no longer presumes a refusal is the
harness's own fault -- sozu#1351's mechanism can make that exact call return
false, so the message says only that a refusal is worth investigating and
reports which (hostname, path, cluster) triggered it.

Two limits of this harness are recorded in its own doc comment rather than
left implicit: it has no reproducible seed (quickcheck 1.1.0 seeds Gen from
OS entropy; unlike the FoundationDB-style simulators doc/testing.md
describes, a failing CI run here is reproduced by re-running with a raised
QUICKCHECK_TESTS, not by seed replay -- not fixed in this changeset); and its
regex anchoring convention matches doc/configure.md's prose because that
prose was itself added by the sozu#1356 fix, so the GROUPING half is a shared
convention with the implementation rather than an independently-checked
spec, while the CASE-FOLDING half is genuinely RFC 9110 derived.

qc_insert's own "randomly fails" was investigated rather than assumed.
Uncommenting it and running at scale shrinks to {"*.": 0}: TrieNode's dotless
insert arm stores a value in the wildcard slot whenever a key's LEFTMOST
label is exactly "*", not only when the whole key is "*", because the
recursive dot-split always keeps the original first byte at index 0 of every
prefix it recurses into. hm_insert's skip list excluded only the latter, so a
HashMap key like "*." inserted fine into the wildcard slot and then reported
"did not find key" against lookup(key, accept_wildcard: false), which
structurally can never consult that slot -- a gap in the test's own exclusion
list, not a router defect. hm_insert_skips now excludes any key whose
leftmost label is "*"; 120,000+ iterations across six separate runs are
clean. Revived rather than deleted: once the oracle model is understood, it
is a small, honest, still-useful check of raw trie insert/lookup independent
of routing semantics, and deleting a test that "randomly fails" without first
finding out why is how a real defect gets silenced instead of fixed.

doc/testing.md notes both properties, their generator bias, and the two
harness limits above in the unit-test taxonomy row. CHANGELOG.md records the
harness, the qc_insert fix, and the four shrunk MISMATCH counterexamples
under Fixed, following the test(e2e) precedent already in the file for a
pure test-only change.

No router behaviour changes in this commit.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the test/router-property-harness branch from 6844bcc to 695715d Compare September 22, 2026 03:32
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 4a3b4e6 into main Sep 22, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the test/router-property-harness branch September 22, 2026 05:06
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.

1 participant