Skip to content

fix(state): apply a listener patch all-or-nothing on main and workers - #1708

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/atomic-listener-patch
Sep 30, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/atomic-listener-patch

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1703

Problem

ConfigState::update_http_listener / update_https_listener (command/src/state.rs) wrote a patch field by field and validated alpn_protocols, sozu_id_header and forwarded_headers in between. A patch refused on a late field kept every field written before it, so sozu listener list, SaveState and upgrade replay showed a configuration nobody asked for.

The workers had the same problem. HttpListener::update_config and HttpsListener::update_config wrote every field into self.config before parsing the answer templates. HttpsListener also checked hsts.enabled last, after swapping in the new rustls context and templates.

Main and workers also disagreed on two patches that main accepted and every worker refused: an unparseable answer template, and an hsts block without enabled.

Design

  • Main state: every check runs before the first write. The lookup order (flood knobs → listener lookup → field checks) and the error variants are unchanged. A new validate_hsts_patch refuses hsts without enabled with the existing StateError::InvalidValue.
  • Workers: validate first, including the hoisted HstsEnabledRequired check (same variant) and the patch templates. The patch is then applied to a clone of the listener config, and the rustls context and HttpAnswers are built from that clone. Config, context and answers are committed only once everything has succeeded, and the HSTS refresh runs after the commit. The cost is one config clone per patch, on the command path only; nothing touches the hot path.
  • Same verdict on both sides: a new HttpAnswers::validate_patch_templates (lib/src/protocol/kawa_h1/answers.rs) is run by the worker and by validate_listener_request (bin/src/command/requests.rs) before dispatch, since command cannot parse templates itself. The main process now refuses exactly the patches the workers refuse, with one exception listed under residual risks.
  • TCP: nothing can fail after the listener lookup, so it was already all-or-nothing; a test pins it.

Tests (red → green)

  • update_http_listener_rejected_patch_leaves_the_state_unchanged and update_https_listener_rejected_patch_leaves_the_state_unchanged: red on unmodified code. The hsts case was also shown red on its own by removing the check. update_tcp_listener_rejected_patch_leaves_the_state_unchanged pins current behaviour.
  • a_rejected_patch_leaves_the_listener_unchanged (HTTP and HTTPS workers): red, then green. Checks the config, Rc/Arc identity of the answers and rustls context, and the HSTS the frontends serve.
  • listener_patches_are_refused_by_the_main_process_exactly_when_a_worker_refuses_them (bin): compares the main verdict with the worker verdict, and checks that list_listeners is unchanged on refusal. Red with the new validate_listener_request arms removed.
  • e2e test_rejected_patch_changes_nothing: red with lib/src/http.rs from main (the worker served rfc7239 after answering Failure), green with the fix.

Validation (after rebasing on 080351b)

  • cargo build --all-features
  • cargo +stable clippy and cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings
  • cargo +nightly fmt --all -- --check
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked
  • cargo test -p sozu-command-lib, -p sozu, -p sozu-lib
  • e2e listener_update (16/16) and listener (29/29); before the rebase, also x_real_ip (10/10) and forward (23/23)
  • cd fuzz && cargo +nightly fuzz build
  • check_doc_citations.py in its four modes

All exited 0.

Docs are updated in doc/configure.md (hot-update section and HSTS partial update), bin/src/command/LIFECYCLE.md and CHANGELOG.md.

Residual risks

  • patch.answers (the map) and patch.hsts are validated but not stored in the main state, so SaveState and replay lose them. This is the same class as fix(state): record hot x_real_ip listener patches in the main state #1694 and is left for a follow-up.
  • A worker that fails to rebuild its rustls context on an ALPN change keeps its listener unchanged, but the main process has already recorded the patch. Main cannot predict this refusal; it is documented.
  • Tightening: a legacy http_answers template shadowed only by an entry the listener already holds is now parsed, and refused if it does not parse. Before, it was stored unused.
  • When a patch has several invalid fields, the worker may now report a different one first. The error variants are unchanged.

ConfigState::update_http_listener and update_https_listener wrote a patch
field by field and validated alpn_protocols, sozu_id_header and
forwarded_headers in between, so a patch refused on one of them kept every
field written before it: `sozu listener list`, SaveState and upgrade replay
then carried a configuration nobody asked for. HttpListener::update_config
and HttpsListener::update_config did the same on the workers with an answer
template that does not parse, and HttpsListener checked an hsts block
without `enabled` last, after committing the new rustls context and
templates.

The main state now runs every check before its first write. The workers
apply the patch to a copy of the listener configuration, build the rustls
context and the answer registry from it, and commit all of it only once
everything succeeded.

The main process also refuses the patches only the workers used to refuse,
so a patch it records is one the workers apply: validate_listener_request
parses the patch templates before dispatch with the worker's own
HttpAnswers::validate_patch_templates, and update_https_listener refuses an
hsts block without `enabled` (StateError::InvalidValue). A worker failing to
build its rustls context for a new ALPN list remains the one refusal the
main process cannot predict. TCP patches validate nothing past the listener
lookup and were already all-or-nothing; a test pins it.

Closes #1703

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/atomic-listener-patch branch from 2a05457 to 7095442 Compare September 30, 2026 06:40
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 9d78850 into main Sep 30, 2026
51 of 52 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/atomic-listener-patch branch September 30, 2026 08:24
FlorentinDUBOIS added a commit that referenced this pull request Sep 30, 2026
…y key (#1712)

Refs #524 (PR 2 of 2: shuffle sharding over the HRW ranking; PR 1 was #1706).

## What

A cluster can serve each client from a **shard** of its backends instead of all of them. A client that overloads or poisons its backends then takes down only the clients whose shard lies inside its own.

References:
- Colm MacCárthaigh, [*Workload isolation using shuffle sharding*](https://aws.amazon.com/builders-library/workload-isolation-using-shuffle-sharding/), Amazon Builders' Library, 2019. It gives `C(N, k)` shards against `N / k` partitions: 28 against 4 for eight backends in shards of two.
- The shard is the top of the rendezvous ranking: Thaler & Ravishankar, *Using name-based mappings to increase hit rates*, IEEE/ACM ToN 1998, [doi:10.1109/90.663936](https://doi.org/10.1109/90.663936).

## Decisions implemented (maintainer comment on #524)

- **Key:** the affinity key from #1706. That is the source IP (post PROXY protocol), or the `affinity_header` / `affinity_cookie` value, falling back to the IP when absent.
- **Shard:** `k = max(2, ceil(shard_percent × N / 100))`, capped at `N`. It is the top `k` of the weighted HRW ranking (`hrw_score`, now public) over the cluster's **configured primary** backends.
  - Backends that are down stay members, so a shard can be exhausted.
  - It is deterministic across workers and restarts.
  - A change of `N` moves a client only at the tail of its ranking.
- **Activation:** only when `N >= shard_min_backends`, which defaults to 8. Off until `shard_percent` is set.
- **Exhausted shard:**
  - `FALLBACK` (default) spills over to the rest of the cluster, backup tier and fail-open included, and counts `backend.shard.spillover`.
  - `STRICT` selects nothing (HTTP 503, TCP close) and counts `backend.shard.exhausted`.
  - In the fail-open regime a strict shard fails open inside itself only.
- **Priority:** a sticky cookie naming a live backend wins, even outside the shard. Connection reuse keeps priority.
- **Upgrade note:** explicit in `CHANGELOG.md` and `doc/configure.md`.
  - Nothing changes until `shard_percent` is set.
  - Once set, the cluster derives a key under every policy.
  - Every client behind one NAT, or behind an L4 balancer without PROXY, shares one shard.

## Design

- `BackendList::select_with_key` (`lib/src/backends.rs`) narrows the primary candidates to the shard before the cluster's `load_balancing` policy runs. Any policy therefore picks inside the shard (`LEAST_LOADED` balances within it, `HRW` pins to its top member with in-shard failover), and retries stay in it.
- `next_available_backend_with_key` keeps its signature. `BackendMap::select_backend` (HTTP reserve and TCP connect) and the UDP keyed path read the `ShardOutcome` and count it under the cluster id.
- **Zero allocation:** two scratch buffers (`shard_scores`, `shard`) are reserved in `add_backend` beside `candidates`. `select_nth_unstable_by` partitions the ranking in O(N), and `retain` keeps the candidates in list order for `Candidates::new`.
- **Key derivation widened:** `cluster_reads_affinity_key` (`router.rs`, shared by the TCP proxy) is true for `HRW`/`MAGLEV` **or** `shard_percent`. Without this, a sharded `ROUND_ROBIN` cluster would silently not shard.
- **Config:**
  - `Cluster` proto fields `shard_percent = 20`, `shard_min_backends = 21`, `shard_mode = 22` (new enum `ShardMode { FALLBACK, STRICT }`).
  - TOML keys; `--shard-percent` / `--shard-min-backends` / `--shard-strict` on `sozu cluster add`; a `shuffle_sharding` column in the cluster table; the fields in `Debug`.
  - `validate_shuffle_sharding` runs at config load and on every `AddCluster`: percent in `1..=100`, min ≥ 2, and the knobs are refused without `shard_percent`.
  - Hot-updatable through `BackendMap::set_shuffle_sharding_for_cluster` from `server.rs::add_cluster`.
- **Retry budget interaction (documented):** `CONN_RETRIES = 3`.
  - With `k = 2`, a request whose two members refuse spills over, or is refused, on its third attempt.
  - With `k ≥ 3`, that request exhausts its attempts inside the shard (503), and the next one, finding the members in back-off, spills over or is refused at once.
- **UDP:** sharding lives in the backend list, so a sharded UDP cluster shards its flows by their flow key.

Protocol/security impact: selection narrowing only; no parser, framing or TLS change. `STRICT` can answer 503 while other backends are healthy, by design.

## Red → green

Each fix was reverted, the test run, the fix restored, and the test run again.

| Mutation | Fails | Evidence |
|---|---|---|
| `compute_shard` never shards | e2e in-shard, e2e strict, `a_sharded_selection_stays_in_the_shard`, `an_exhausted_shard_refuses_in_strict_and_spills_in_fallback` | `shard ["pong0", "pong2"], reached ["pong0", "pong1", "pong2", "pong3", …]`, `strict answered Some((200, "pong2"))` |
| `STRICT` spills over | e2e strict, unit strict | `shard [2, 3] down, strict answered Some((200, "pong0"))`, `key 0: strict never leaves the shard` |
| `FALLBACK` refuses | e2e fallback | `shard [0, 3] down, fallback answered Some((503, …))` |
| no key for a sharded non-HRW cluster | `only_hrw_maglev_and_sharded_clusters_derive_a_key` | `a sharded cluster derives a key whatever its policy` |
| shard collected into a fresh `Vec` | `a_sharded_selection_allocates_nothing` | `256 sharded selections made 256 allocations` |

Green: every test above passes after restoring.

## Tests added

- **Unit (`lib/src/backends.rs`):**
  - `a_shard_is_the_top_of_the_hrw_ranking`
  - `a_shard_changes_only_at_its_tail_when_backends_change`: add with `k` fixed, add with `k` growing, remove a non-member, remove a member
  - `a_sharded_selection_stays_in_the_shard` (ROUND_ROBIN, LEAST_LOADED, RANDOM, HRW)
  - `an_exhausted_shard_refuses_in_strict_and_spills_in_fallback`
  - `a_strict_shard_fails_open_inside_itself`
  - `a_sticky_backend_outside_the_shard_wins`
  - `a_sharded_selection_allocates_nothing`
- **Unit (`load_balancing.rs`):** `a_shard_size_follows_the_decided_formula`.
- **Unit (`router.rs`):** `only_hrw_maglev_and_sharded_clusters_derive_a_key`.
- **Command crate:** `shuffle_sharding_reaches_the_add_cluster_order_and_is_validated`, `add_cluster_with_invalid_shuffle_sharding_rejected`.
- **e2e (`e2e/src/tests/shuffle_sharding_tests.rs`):** four backends, `shard_percent = 50`, `shard_min_backends = 4`, with the shard predicted via `hrw_score`. The shard's members are left without a listener, so connections to them are refused.
  - in-shard: every request lands in the predicted shard
  - FALLBACK: 200 from a non-member
  - STRICT: 503

## Validation (head 2cda4f0 on main 2e55942)

- `cargo +nightly fmt --all -- --check`: 0.
- `cargo clippy --all-features --all-targets --locked -- -D warnings`: 0.
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings`: 0.
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`: 0.
- `cargo test -p sozu-lib`: 1420 passed. `-p sozu-command-lib`: 217. `-p sozu`: 123. `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim`: ok.
- `cargo test -p sozu-e2e -- shuffle_sharding_tests affinity_key_tests cluster_ip_limit`: 15/15. The full e2e suite (before the rebase onto #1708): 532 passed, 0 failed.
- `cd fuzz && cargo +nightly fuzz build`: 0.
- `check_doc_citations.py`: `--self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .` all 0.

## Docs

- `doc/configure.md`:
  - a new "Shuffle sharding" section: literature, formula, stability, keys, TOML example, composition with policy, retries, sticky, reuse and backups, UDP, and the enable-time note
  - metrics rows
  - a "Client affinity" cross-reference
- `doc/metrics.md`, `doc/configure_cli.md`, `doc/architecture.md`, `lib/src/protocol/mux/LIFECYCLE.md`, `doc/testing.md`, `bin/config.toml`, `CHANGELOG.md` (Added, with the before-enabling note).
- The line citations of `cluster_h2_command` in `doc/configure_admin_ops.md` became prose, because they drift with every edit of `request_builder.rs`.

## Review fixes (FIX-FIRST on a029ac6)

- **M1:** `STRICT` now decides between refusing and failing open on the **primary** tier only. The `cluster_can_open` that also counted backups is replaced by `primaries_can_open`, so a healthy backup no longer turns a strict shard's fail-open into a 503. Test: `a_healthy_backup_does_not_turn_a_strict_fail_open_into_a_refusal`. Red with backups counted: `panicked … a strict shard fails open inside itself`. `doc/configure.md` "Backups are outside every shard" now states the STRICT/backup interaction explicitly.
- **M2:** the upgrade note in `CHANGELOG.md` and in the `doc/configure.md` "Before enabling it" note now says:
  - Upgrade the main process and every worker before setting `shard_*`: an older worker ignores fields 20–22 and serves unsharded.
  - An older CLI's `QueryClusterById` → `AddCluster` read-modify-write (`cluster h2`) drops the fields and silently disables sharding.
- **L2:** a `FALLBACK` fail-open pick that lands back in the shard is reported `InShard` (`settle_spill_outcome`) and not counted as `backend.shard.spillover`. Test: `a_fallback_fail_open_pick_inside_the_shard_is_not_a_spill_over`. Red without the settle: `127.0.0.1:20004 is a shard member, left: SpilledOver right: InShard`.
- **L3:** tests added.
  - `a_strict_shard_failing_health_checks_refuses_while_others_are_healthy`. Red with the `primaries_can_open` guard forced false: `key 0: strict must refuse, not fail open`.
  - Non-uniform weights in `a_shard_is_the_top_of_the_hrw_ranking`, which also asserts that the weights move some shard.
  - e2e `test_re_adding_a_cluster_without_shard_percent_turns_sharding_off`, re-added under `HRW` so the key is still derived. Red when `Server::add_cluster` skips `set_shuffle_sharding_for_cluster` without `shard_percent`: `sharded Some((503, …)), then unsharded Some((503, …))`.
  - The backup-tier interaction is covered by M1's test.
- **L4:** `compute_shard` counts the primaries and checks `shard_size` / `min_backends` before hashing, so a cluster below the threshold pays no hash. The `has_tier_candidate` walk is gone, including for unsharded clusters.
- **L5:**
  - The weight wording now reads "ranks higher for more keys, not proportional once `k > 1`".
  - The UDP `DefaultHasher` cross-toolchain caveat is on "across restarts".
  - The `backend.shard.*` rows are aligned between `configure.md` and `metrics.md`.
  - The `--affinity-header` / `--affinity-cookie` help mentions that sharding reads the key under any policy.
- **L1 (done):** the worker mirrors `validate_shuffle_sharding` on `AddCluster` next to the health-check mirror in `server.rs`.



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.

state: a rejected listener patch is partially applied in the main state

1 participant