Skip to content

h2 sans-io core perimeter: recap of Q6, Q7 and Q12 (from #1340) #1684

Closed

Description

@FlorentinDUBOIS

Recap of the H2 sans-io "core perimeter" decision set tracked in #1340 (Q6 routing, Q7 listener configuration, Q12 backend handles and accounting), measured on main at e55c8bd14facb8a928c8479e1a00b06b1574c09d.

Shipped

PR Merge Question Change
#1516 5355cec0 Q10 (prerequisite) ConnectionH2 drops its Front parameter into an H2Shell
#1517 66205685 Q12, first half backends held as an opaque id; accounting returned as deltas
#1519 339f794a Q6 Router::connect split into plan_connect and an embedder-performed dial
#1525 d6a7d10f Q6 / Q7 cluster configuration read from a borrowed RoutingView
#1527 223a4511 Q6 per-IP limit gate becomes a returned ConnectStep::CheckIpLimit
#1529 747128ea Q6 (UDP) backend selection moved into the UDP manager through BackendSource
#1550 e2fd5f0d Q12, second half selection and dial through a BackendDialer lent for one call

Where the perimeter sits

  • lib/src/protocol/mux/router.rs has no production reference to L7Proxy, Rc<RefCell<dyn ProxySession>> or Rc<RefCell<Backend>>; the remaining mentions are doc comments and #[cfg(test)] fixtures.
  • Routing is inside the core (Router::plan_connect → ConnectPlan), the dial is performed by the embedder (Mux::dial_backend), and backend accounting flows back as deltas against an opaque BackendId.
  • Listener configuration is read from a snapshot taken at stream creation, not from live listener borrows.

One recorded deviation

The decision on #1340 asked for a read-only view of backend load state, "the same shape" as RoutingView (#1525). #1550 deliberately used a &mut dyn BackendDialer capability instead, following the UDP BackendSource precedent (#1529): selection mutates state (round-robin cursor, fail-open latch, EWMA observation, Maglev table, availability latch), and a read-only snapshot of per-backend RefCells cannot be lent without allocating. The rationale is in the #1550 description. This recap records that shape as the accepted outcome of Q12.

Status

No open work remains from #1340. This issue is the summary to point at; #1340 is closed in its favour.

Activity

  1. FlorentinDUBOIS commented on Sep 29, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Measured on main at e55c8bd14facb8a928c8479e1a00b06b1574c09d (2026-09-29). The perimeter claim above holds: router.rs has no production L7Proxy, Rc<RefCell<Backend>> or .backends(). Two things remain, though. The reason Q6 put routing inside the core was determinism, and a simulator still cannot reach backend selection. One recorded claim about L7Proxy::backends is also wrong. Below is a /goal prompt for the part of Q12 part 2 that remains.

    /goal Finish the second part of Question 12 of sozu-proxy/sozu#1340 (backend load state for selection), as recapped in #1684: backend selection and its accounting must be supplied by the embedder and drivable by the simulator.
    
    BASELINE (origin/main e55c8bd14facb8a928c8479e1a00b06b1574c09d, 2026-09-29). Re-measure before acting and stop if any line no longer holds.
    - Settled and not to be reopened: Q6 puts routing inside the core, with the dial performed by the embedder (#1519 Router::plan_connect / Mux::dial_backend / Router::commit_dialed, #1525 RoutingView, #1527 ConnectStep::CheckIpLimit). Q7 snapshots configuration per stream at HEADERS (#1513). Q12 part 1 is an opaque BackendId, with invariant-14 accounting sent back as BackendDelta (#1517). Q12 part 2 is `&mut dyn BackendDialer` (#1550). #1684 records that as the accepted outcome in place of the read-only view: selection mutates state (round-robin cursor, fail-open latch, PeakEWMA, Maglev, availability latch), and a snapshot of N RefCell-guarded backends cannot be lent without allocating. It follows the UDP `BackendSource` precedent (lib/src/protocol/udp/mod.rs, #1529).
    - Why select and dial are a single call: Backend::try_connect raises active_connections directly, outside the delta ledger. LIFECYCLE.md §9 invariant 14, "Drain before any read", holds only while selection and dial form one synchronous step. DialedBackend therefore carries both the BackendId and the socket.
    - Wrong on the record: `L7Proxy::backends` still has one production caller, Mux::dial_backend (lib/src/protocol/mux/mod.rs, `proxy.borrow().backends()`). e2fd5f0d moved that call out of router.rs rather than removing it. LIFECYCLE.md §3.2 says it has "no caller left", CHANGELOG.md's #1550 entry says it "now has no caller", and #1550's description counts `.backends()` in lib/ + bin/ as 2 -> 0.
    - What blocks a simulator: sim/tests/h2_simulation.rs drives ConnectionH2 only, and says "no backend exists in this simulation". Router::plan_connect and Router::commit_dialed are pub(super). BackendId's slot is private, and the only code that mints one is BackendRegistry::id_for(&Rc<RefCell<Backend>>) on a pub(crate) type. DialedBackend.socket is a concrete mio::net::TcpStream, and sim/Cargo.toml has no mio dependency (Q10 removed it). As a result, no BackendDialer can be written outside sozu-lib, and the in-crate StubDialer (router.rs, stamping_a_dialled_backend_allocates_nothing) needs loopback sockets.
    - Outside the Q12 perimeter, and left alone unless G3 below is answered: ExponentialBackoffPolicy::fail and ::can_try (lib/src/retry.rs: rand::rng(), Instant::now, elapsed), PeakEWMA::observe (Instant::now), Random::new and PowerOfTwo::new (SysRng seed; with_seed exists), and the immediate `failures` / retry_policy / set_connection_time(start.elapsed()) writes in Mux::ready_inner. BackendChange documents why those writes are not deltas.
    
    STEP 1 (unconditional, docs only, one PR): fix the record. Correct LIFECYCLE.md §3.2 and add a CHANGELOG correction note that names Mux::dial_backend as the remaining caller. Success:
    - `git grep -q 'has no caller left' -- lib/src/protocol/mux/LIFECYCLE.md` -> prints nothing, exit 1
    - `python3 .github/scripts/check_doc_citations.py` -> exit 0; `--base origin/main` -> exit 0; `--self-test` -> exit 0; `--root .github/scripts/testdata/citations` -> exit 1 (the broken fixture must fail); `--audit` reports no finding more than main does.
    
    GATE (STOP and ask the maintainer on #1684 before writing any more code). Post the options below with the measurements, then halt.
    - G1, `L7Proxy::backends`: (a) remove it from the trait and let Mux hold the Rc<RefCell<BackendMap>> from construction. HttpProxy and HttpsProxy never reassign their `backends` field, and #1615 (`L7Proxy::deregister_socket`) is the precedent for the library API break. Measure the per-session size and refcount cost first. (b) Keep it as the embedder's accessor, so step 1 closes the matter.
    - G2, reaching selection without a socket: (a) the UDP shape, where the dialer returns (BackendId, SocketAddr) and the embedder dials. This reopens the window #1550 closed and needs a BackendChange::ConnectionOpened, a failure return for failures/retry_policy, and a rewrite of invariant 14. (b) Keep one step but inject the connect, which makes the socket type generic through DialedBackend, Router and Connection (a large change). (c) Accept that sim/ does not reach selection: the seam is already covered in-crate by backend_dialer_tests and StubDialer, and Q12 part 2 closes on step 1 alone. (d) Something else the maintainer names. For (a) and (b), also report which pub(super) or pub(crate) items (Router::plan_connect, Router::commit_dialed, BackendRegistry, the HttpContext path) must become pub before sim/ can reach them.
    - G3: whether determinism reaches into lib/src/retry.rs and lib/src/load_balancing.rs. Neither #1337 nor #1338 covers those files.
    
    AFTER THE ANSWER, one PR per chosen option, in sequence. Pre-declared success criteria:
    - G1=(a): `git grep -qE 'fn backends|\.backends\(\)' -- lib/src/lib.rs lib/src/protocol/mux` -> prints nothing, exit 1. Sweep the test doubles NoBackendProxy and RemoveOnlyProxy (mod.rs) and the fixture in router.rs. A CHANGELOG "Removed" entry shaped like #1615's.
    - G2=(a) or (b): a new sim/tests/ test that drives Router::backend_from_request through a dialer the sim owns, under moonpool. `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 for at least 64 seeds, and the same seed replayed twice must give a byte-identical trace. Trace backend choice, BackendId order and the sticky answer, and keep wall-clock values out of it. `git grep -q mio -- sim/Cargo.toml` -> prints nothing, exit 1. Per-dial allocation count measured with test_allocations::allocations(), no higher than before the change (#1550 recorded this path as neutral, not zero). Invariant-14 reconciliation tests (invariant_14_*) are unchanged and green.
    - G3 (only if answered): `git grep -nE 'Instant::now|rand::rng|SysRng' -- lib/src/retry.rs lib/src/load_balancing.rs` production hits -> 0, with clock and RNG injected.
    
    EVERY PR:
    - A small, reviewable sequence, one concern per PR, from a worktree off origin/main. Docs change in the same PR: LIFECYCLE.md, doc/testing.md (simulator recipe, section 5), CHANGELOG.md. Comments cite symbols, not line numbers.
    - Before merging, all of these return exit 0, each judged by its own exit code and never through a pipe: `cargo +nightly fmt --all -- --check`, `cargo clippy --all-targets --locked -- -D warnings`, `cargo clippy --all-targets --all-features --locked -- -D warnings`, `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`, `cargo test --workspace --locked --exclude sozu-e2e`, `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked`, `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::`, and check_doc_citations.py in its four modes.
    - Every new regression test is seen red before green: revert the fix, quote the failing assertion, restore it. Put the red/green evidence in the PR description.
    - Never weaken a check: no skipped or deleted test, no loosened assert, no new allow, no #[ignore] without a reason.
    - Performance comes first: no new allocation or syscall on the dial path. Measure it and paste the numbers.
    - Commits are signed and signed off (`git commit -s -S`), with no AI or generated-by trailers. Never set SKIP_PREPUSH_VALIDATE.
    
    STOP CONDITIONS: stop after step 1 plus the gate comment until a maintainer answers G1 and G2. Allow at most five attempts per failing check, then post the attempt ledger and stop. Stop and report if a baseline fact above no longer holds on main. Budget: step 1 plus at most three follow-up PRs. End each run with one status line: `done=<bool> state=<step> prs=<n> blockedReason=<reason|none>`.
    
  2. FlorentinDUBOIS commented on Sep 29, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Step 1 done, gate reached: G1, G2 and G3 need a maintainer answer

    Baseline re-measured on origin/main at 3ed6e8a6 (2026-09-29). The three commits since e55c8bd1 (#1683, #1682, #1687) touch CHANGELOG.md, bin/, kawa_h1/, mux/h1.rs (4 lines), e2e/ and doc/. None of them touches mux/mod.rs, mux/router.rs, sim/, retry.rs or load_balancing.rs. Every baseline line in the prompt still holds.

    Step 1: #1693 (docs(mux): name the remaining L7Proxy::backends caller, head 55aa5e89). It corrects LIFECYCLE.md §3.2 and the CHANGELOG, and names Mux::dial_backend as the remaining caller. The has no caller left grep exits 1. check_doc_citations.py exits 0 in its default, --base origin/main and --self-test modes and 1 on the broken fixture, as required. --audit output is byte-identical to main's.

    Nothing past this point is implemented. The questions follow.


    G1: L7Proxy::backends

    The .backends() count in lib/ + bin/ is 2. One is production code (Mux::dial_backend). The other is a test fixture in router.rs (the backend_dialer_tests fixture). The trait method has 4 impls: HttpProxy, HttpsProxy, and the test doubles NoBackendProxy and RemoveOnlyProxy in mux/mod.rs. Both HttpProxy and HttpsProxy set their backends field only in struct literals and never reassign it.

    (a) Remove it and let Mux hold the Rc<RefCell<BackendMap>> from construction. Measured cost, from size_of in a throwaway test that was not committed:

    type today with (a)
    Rc<RefCell<BackendMap>> 8 B
    MuxClear 4976 B 4984 B (+0.16 %)
    MuxTls 6152 B 6160 B (+0.13 %)
    HttpSession / HttpsSession 5288 / 6528 B at most +8 B (Mux sits inline in the state-machine enum, so padding may absorb it)
    • Refcount: today every dial does one RefCell::borrow of the proxy plus one Rc clone and drop, because backends() returns a clone. Under (a), the dial path does none of this. The cost moves to one clone when the session is built and one drop when it ends.
    • Sites to sweep: the trait declaration in lib.rs, 4 impls, 3 production Mux { .. } literals (2 in http.rs, 1 in https.rs) and 7 test literals (6 in mux/mod.rs, 1 in mux/h2.rs), plus the router.rs fixture.
    • This is a library API break shaped like lib: remove L7Proxy::deregister_socket, which has no caller since #1568 #1615 (L7Proxy::deregister_socket).

    (b) Keep it as the embedder's accessor. Step 1 closes the matter.

    G2: reaching selection without a socket

    The sim cannot write a BackendDialer. The public surface is not what stops it; two things are:

    • Already pub and reachable from sim/: protocol::mux::router::Router, Router::new, Router::backend_from_request, BackendDialer, Affinity, DialedBackend (all fields pub), kawa_h1::editor::HttpContext and HttpContext::new, and backends::BackendError.
    • Blocker 1, minting a BackendId: BackendId::slot and BackendSlot(usize) are private. The only production minting path is BackendRegistry::id_for, a private fn on a pub(crate) type. The h1.rs and h2.rs tests mint through the private field from inside the module. No code outside sozu-lib can build a BackendId.
    • Blocker 2: DialedBackend.socket is a concrete mio::net::TcpStream, and sim/Cargo.toml has no mio. StubDialer in stamping_a_dialled_backend_allocates_nothing pre-connects loopback sockets for this reason.
    • Only needed if the sim drives the connect flow rather than calling backend_from_request directly: Router::plan_connect, Router::plan_connect_resume and Router::commit_dialed are pub(super).

    Allocations measured today. The router's own stamping is 0 allocations per dial (stamping_a_dialled_backend_allocates_nothing, 64 dials). Steady-state selection is 0 (backend_selection_allocates_nothing_in_steady_state, lib/tests/backend_selection.rs). All 3 backend_dialer_tests pass on main. I did not measure the whole Mux::dial_backend path in this run. #1550 recorded it as neutral, not zero.

    The options:

    • (a) UDP shape. The dialer returns (BackendId, SocketAddr) and the embedder dials. This reopens the window refactor(mux): select and dial through a BackendDialer lent for one call #1550 closed, because Backend::try_connect raises active_connections outside the ledger. It needs a BackendChange::ConnectionOpened, a failure return for failures/retry_policy, and a rewrite of invariant 14. Minimum visibility change: a pub way to mint a BackendId (a constructor or a pub slot). DialedBackend loses its socket.
    • (b) One step with the connect injected. The socket type becomes generic through DialedBackend, Router and Connection, which is a large change. It needs the same BackendId minting change, plus plan_connect/commit_dialed if the sim goes past backend_from_request.
    • (c) Accept that sim/ does not reach selection. The seam is already covered in-crate by backend_dialer_tests (a_second_selection_observes_the_first_dials_connection, a_cookie_pins_only_a_frontend_that_sticks, stamping_a_dialled_backend_allocates_nothing). Q12 part 2 would close on step 1 alone.
    • (d) Something else you name.

    G3: determinism in retry.rs / load_balancing.rs

    Running the pre-declared pattern Instant::now|rand::rng|SysRng over those two files returns 17 raw hits. Once comments, imports and #[cfg(test)] code are excluded, 6 production call sites remain:

    • lib/src/retry.rs (4): 3 × Instant::now in ExponentialBackoffPolicy::new/fail/succeed, and 1 × rand::rng() in fail. The pattern misses 2 more clock reads, .elapsed() in fail and can_try.
    • lib/src/load_balancing.rs (2): SysRng in Random::new and PowerOfTwo::new. Both types already have a with_seed.
    • Scope gap: PeakEWMA lives in lib/src/lib.rs, not load_balancing.rs. PeakEWMA::new and PeakEWMA::observe call Instant::now, and PeakEWMA::get calls observe, so LeastLoaded selection under LoadMetric::ConnectionTime reads the wall clock. The pre-declared G3 grep would pass with those reads still in place. If PeakEWMA is in scope, add lib/src/lib.rs (PeakEWMA) to the criterion.

    Neither #1337 nor #1338 covers these files. Is G3 in scope, and if so, does it include PeakEWMA?


    Stopping here until G1 and G2 are answered.

    done=false state=gate prs=1 blockedReason=awaiting-maintainer-answer-G1-G2

  3. FlorentinDUBOIS commented on Sep 29, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Maintainer decisions on the gate (2026-09-29):

    • G1 = (a): remove L7Proxy::backends; Mux holds the Rc<RefCell<BackendMap>> from construction (+8 B per session, one RefCell borrow and one Rc clone/drop saved per dial).
    • G3 = yes: inject the clock and the RNG into lib/src/retry.rs, lib/src/load_balancing.rs (Random, PowerOfTwo seeds) and PeakEWMA in lib/src/lib.rs — the pre-declared G3 grep is extended to that file so the criterion cannot pass while that clock read remains.
    • G2 = (a), the UDP shape, with reservation at selection so invariant 14 keeps its guarantee:
      • selection returns (BackendId, SocketAddr) (no socket), and the embedder (Mux::dial_backend) dials;
      • active_connections is incremented under the same borrow as the choice, so the next selection sees it exactly as today;
      • a failed dial releases the reservation and applies failures += 1 / retry_policy.fail() through a new BackendChange;
      • LIFECYCLE §9 invariant 14 is rewritten as "selection reserves, failure releases";
      • a BackendId factory reachable from sim/; sim/Cargo.toml stays without mio;
      • no new allocation on the dial path (measured with test_allocations).

    Sequence, one PR each: G1(a) → G3 → G2(a) → deterministic H2 simulation test (≥ 64 seeds, byte-identical trace on replay of the same seed), each with the success criteria pre-declared in the prompt above.

  4. added 2 commits that reference this issue on Sep 30, 2026
    b714b7d
    ac2789f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions