Skip to content

fix(metrics): isolate cluster incarnations - #1845

Merged
FlorentinDUBOIS merged 4 commits into
mainfrom
fix/metrics-cluster-incarnation-1828
Oct 4, 2026
Merged

FlorentinDUBOIS merged 4 commits into
mainfrom
fix/metrics-cluster-incarnation-1828

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1828.

Long-lived sessions can emit cluster and backend metrics after RemoveCluster. When the same cluster, backend id, and address are recreated, those delayed events must not update the replacement lifetime.

This change gives each effective cluster lifetime an internal metrics incarnation captured by the request, route, pipe, or backend owner that may emit later. Labelled cluster and backend metrics reach the drains only while that captured incarnation is still active. Process and frontend aggregates continue to accept the same physical events after their labels are removed, so late decrements still balance the aggregate gauges they previously incremented. The public SessionMetrics literal shape and register_end_of_session behavior remain compatible.

The lifetime rules are:

  • the first legal route can allocate an implicit identity before AddCluster;
  • AddCluster without an intervening removal preserves that identity;
  • RemoveCluster deletes the active identity and tombstones both drains;
  • the first legal route after removal allocates a different identity and re-arms both drains, so a replacement created without AddCluster is visible immediately while the removed identity remains fenced;
  • metrics clear, detail changes, and collection disable/enable do not reset an active identity;
  • identity exhaustion is a distinct invalid capture: labelled metrics fail closed and removed-drain tombstones remain armed.

HTTP captures the identity per routed request or stream, so an H1 keep-alive connection can reroute correctly. TCP static and SNI routing capture once for the selected route and do not adopt a later incarnation during retry. Proxy-level connection metrics remain separate and still record physical closes.

Documentation and regression coverage are included in the same changeset. The decisive strict H1 runtime test holds an old session, removes and recreates the same cluster/backend/address, observes the proxy gauge transition from 2 to 1, verifies the replacement remains at 1, then consumes a new response metric before checking that the old close did not contaminate the new row. Additional tests cover legal routing without AddCluster, implicit identity continuity across an add, remove/clear fencing, replacement re-arm without an add, process/frontend aggregation, exhaustion, public API compatibility, and TCP static/SNI capture.

Validation:

  • cargo test -p sozu-lib metrics::tests --locked -j 4 -- --nocapture: 34 passed
  • cargo test -p sozu-e2e real_http_session_without_add_cluster_records_labelled_metrics --locked -j 4 -- --nocapture: 1 passed
  • cargo test -p sozu-e2e test_old_http_session_metrics_do_not_decrement_same_identity_replacement --locked -j 4 -- --nocapture: 1 passed with proxy 2→1, replacement 1→1, new 2xx metric 1, and clean worker shutdown
  • On the exact intended composition main@9561b24e + #1845 product delta + #1843 tests@2f78aaf928b2241241713cbba28ff4abdc1f0926, the independent checker replayed the retained test(lifecycle): add regression coverage #1843 H1 oracle 1/1 and the new H2/WebSocket oracles 2/2. The test(lifecycle): add regression coverage #1843 H1 case preserves the cluster id but deliberately uses distinct old/new backend ids and addresses; the strict same-cluster/backend/address H1 case above remains the fix(metrics): isolate cluster incarnations #1845 oracle.
  • The H2 oracle uses one real TLS connection negotiated with ALPN, holds stream 1 across remove/recreate, lets stream 3 complete on the replacement over that same connection, then observes the old stream terminate without decrementing the replacement incarnation.
  • The WebSocket oracle observes a real HTTP 101 promotion into Pipe, exchanges structurally valid framed data in both directions for both lifetimes, and preserves access counts 1→1→2 and WebSocket gauges 2→1→0. Its fixture omits Sec-WebSocket-Accept, so it proves pipe lifecycle/accounting rather than a complete RFC 6455 handshake.
  • On the owner overlay #1845@91e8a421 + complete #1843 test content, the functional run passed 628 tests with exactly four existing cargo fuzz wrappers filtered. That overlay predates merged fix(proxy-protocol): preserve payload after short v2 headers #1844; only the focused H1, H2, and WebSocket replays above were checked on the exact main@9561 + #1845 product + #1843 tests composition.
  • cargo clippy -p sozu-lib -p sozu-e2e --all-targets --locked -j 4 -- -D warnings: passed on product-identical source
  • cargo fmt --all -- --check, documentation citations, and git diff --check: passed
  • the replacement-rearm regression was observed red before the fix; an invalid-exhaustion re-arm mutation was observed red before restoration

The accepted H2 and WebSocket runtime tests are published by #1843, not by this PR, so they are absent from #1845's 27/27 CI run at 91e8a421. TCP static and SNI capture remain covered by focused unit tests without a dedicated teardown runtime scenario. The network drain re-arm remains source-coupled with the local drain and compile/lint covered; the decisive post-removal replacement and exhaustion probes exercise the local drain rather than a UDP runtime.

Follow-ups (90fbeb2, 3b73653, 91e8a42)

  • A cluster referenced by a route before any AddCluster gets its metrics identity on that first route; a later AddCluster reuses it and only RemoveCluster ends it. Capture states are Missing / Active / Invalid (exhaustion), and only an Active capture matching the current identity is accepted at Cluster/Backend detail; Process/Frontend aggregates accept every state.
  • A route that recreates a removed id without AddCluster allocates a fresh identity and re-arms the drains; exhaustion leaves them fenced.
  • TCP captures once at routing; record_backend_metrics! checks once per invocation.
  • Known limit: an id never declared with AddCluster cannot be removed (the main process rejects RemoveCluster for it), so its identity entry lives as long as the worker.

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Review of 1bede9e. Fix requested before merge. The #1828 regression test fails on main and passes on this head. The design (an incarnation captured per request and checked when the metric is emitted) looks right. One HIGH issue needs fixing first:

1. HIGH: cluster-labelled metrics are dropped when no incarnation was captured, at every detail level.

  • In receive_metric_for_incarnation (lib/src/metrics/mod.rs), let Some(incarnation) = incarnation else { return; } runs before the matches!(self.effective, Cluster | Backend) check.
  • A cluster that never received AddCluster captures None. That configuration is accepted today:
    • command/src/state.rs add_frontend_to / add_backend do no existence check;
    • router.rs:740-754 routes undeclared clusters with default settings.
  • For such clusters, the following are lost, at Cluster/Backend detail and also from the Process-detail worker aggregate:
    • backend.requests, bytes_in / bytes_out, response_time, connection_time, access_logs.count;
    • the labelled request_time / service_time, connections_per_backend, connections_error, connect_retries_exhausted, …
  • This contradicts the PR body ("process/frontend aggregates retain their existing close semantics") and doc/observability.md.
  • Reproduced: with the same labels at Process detail, plain receive_metric gives Some(Count(1)) and the incarnation path gives None.
  • Suggested fix:
    • drop the early return;
    • inside the Cluster/Backend branch only, compare self.cluster_incarnation(cluster_id) != incarnation as Option == Option. None == None keeps never-declared clusters working, and any Some mismatch is still rejected;
    • rewrite the "None is never a wildcard" sentence in the docs to match;
    • add a None-at-Process case to the unit test.
  • Trade-off: after u64 exhaustion, clusters share None with undeclared ones. That takes 2^64 AddCluster calls; worth one doc line.

2. LOW: the TCP capture is not one-shot.

  • tcp.rs:1693 re-captures on retry when the value is None.
  • A session that started before an AddCluster can therefore take on the new incarnation mid-session and emit a -1 with no matching +1.
  • Capture once at the route.

3. LOW, performance: the incarnation arm of record_backend_metrics! (~1251-1272) does up to 6 map lookups per request; one lookup per macro call is enough. Process detail pays nothing.

Checked and fine:

  • pooled and keep-alive connections cannot cross a remove + re-add (is_retired);
  • the WebSocket pipe incarnation;
  • worker startup, upgrade and state replay;
  • overflow uses a checked add;
  • metric-detail leases;
  • UDP.

Verification:

  • cargo test -p sozu-command-lib --all-features: 235 passed;
  • the metrics / remove_cluster / metrics_lifecycle e2e tests: 9 passed;
  • doc citations: OK;
  • git merge-tree against main: clean.

…once

A cluster referenced by frontends or backends without an AddCluster has
no metrics incarnation, so its owners capture `None`. The incarnation
gate returned early on a `None` capture before checking the effective
detail, which dropped every cluster-labelled metric for such a cluster
at every detail level, including the Process-detail worker aggregate.

Compare the captured and current incarnations as optional values, and
only at cluster and backend detail: `None == None` is recorded, any
mismatch (including a missed `None` capture against a current
incarnation) is still rejected. After the 64-bit incarnation space is
exhausted, new clusters share `None` with undeclared ones.

The TCP session now captures the incarnation exactly when its route is
first set, instead of re-capturing on a retry while the value is `None`
or again in the SNI preread upgrade. `record_backend_metrics!` performs a
single identity lookup per invocation instead of one per emission.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 66fbce8 into main Oct 4, 2026
28 checks passed
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.

Late metrics from a removed cluster contaminate a same-ID replacement

1 participant