Skip to content

feat(observability): close #892 — per-cluster availability + access-log timeout discriminator - #1245

Merged
FlorentinDUBOIS merged 10 commits into
mainfrom
fix/892-cluster-availability
May 4, 2026
Merged

FlorentinDUBOIS merged 10 commits into
mainfrom
fix/892-cluster-availability

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Summary

Closes #892. Two operator-visible surfaces, plumbed through one branch:

  1. Per-cluster availability tracker. Replaces the single process-wide BackendMap.available: bool (which silently swallowed every cluster's transition the moment any single cluster tripped it) with a per-cluster Cell<ClusterAvailability> latched on BackendList. Driven from BackendMap paths (control-plane mutation + connect routing + the HC tick) so the transition log + counter + Event fires exactly once per Available ↔ AllDown flip per cluster.
  2. Access-log timeout discriminator. Timeout-driven 408/504 default-answer responses now surface a stable, structured token in the existing RequestRecord.message field so operator pipelines can distinguish a timeout from a backend-error response with the same status code. Vocabulary aligned with HAProxy cR/cH/sH/sD and Envoy DT/UT.

What changes for operators

New metrics (cluster-scope)

Metric Type Description
cluster.available_backends gauge Backends currently passing status == Normal && health.is_healthy() && !retry_policy.is_down()
cluster.total_backends gauge Backends configured for the cluster regardless of state
cluster.no_available_backends counter Incremented exactly once per Available → AllDown transition
cluster.available_recovered counter Incremented exactly once per AllDown → Available transition
backend.available gauge Per-(cluster, backend) 0/1, emitted only at transition sites

health_check.healthy_backends is now labelled with cluster_id; previously the unlabelled gauge collapsed every cluster's value into a single bucket — a multi-cluster operator dashboard could only ever observe the last-checked cluster (Fixed in CHANGELOG).

New event

EventKind::ClusterRecovered = 29 on the SubscribeEvents bus. Pairs with the existing NoAvailableBackends (tag 2). Subscribers tracking the all-down event get the recovery side for free without polling.

New log lines (per cluster, exactly once per transition)

  • error!("cluster X: all N backends are down") on Available → AllDown
  • info!("cluster X: backends recovered (i/N available)") on AllDown → Available

Access-log message token vocabulary

Token Trigger Status
client_timeout Frontend timer fired before request fully received 408
client_timeout_during_response Frontend timer fired while awaiting backend response 504
backend_timeout Backend silent before first response byte 504
backend_response_timeout Backend stalled mid-response-body 504 (H1) / RST_STREAM(INTERNAL_ERROR) (H2)

Non-timeout default-answer paths leave the field as None and emit message: None exactly as before. Caller-supplied parser-error messages keep precedence.

Implementation notes

  • BackendList::availability: Cell<ClusterAvailability> chosen over RefCell because the receiver is &self and the state is Copy. Worker runtime is single-threaded, so a Cell is sound — no synchronisation needed.
  • BackendMap::record_cluster_availability(&self, cluster_id) takes &self so callers that already hold &mut BackendMap can drop their &mut BackendList borrow before invoking it without re-borrowing. This is the borrow-shape the session-side passive paths cannot achieve (they hold Backend::borrow_mut()), so the helper is driven exclusively from BackendMap paths plus the HC tick — recovery is detected at the next routing call against the cluster, the next health-check tick, or when a single backend successfully serves traffic.
  • Access-log token is plumbed via HttpContext.access_log_message: Option<&'static str> — static-string-only by construction (closed enum of operator-visible tokens, not arbitrary user input). Set in kawa_h1::Http::timeout and MuxState::timeout arms before set_answer / forcefully_terminate_answer. Consumed by log_default_answer_success (H1) and Stream::generate_access_log (mux). The H1 backend invariant-break arm (`got backend timeout while waiting for a request`) collapses into the same `backend_timeout` token as the regular arm because the operator-visible cause is identical; the internal error! log keeps the diagnostic signal for sozu maintainers.

Commit list (8 commits)

  1. `feat(events): add ClusterRecovered event (proto tag 29)`
  2. `feat(metrics): per-backend availability gauge + labelled gauge! overload`
  3. `feat(backends): per-cluster availability tracker with recovery event`
  4. `feat(logging): access-log discriminator for timeout outcomes`
  5. `docs(observability): document Write a log when backends are detected down or up. #892 cluster-availability surface + access-log discriminator`
  6. `docs(mux): note access-log discriminator on timeout exit paths`
  7. `test(backends): unit tests for evaluate_availability + record_cluster_availability`
  8. `test(backends): cover Backend::is_available and per-cluster transitions`

Test plan

  • `cargo build --locked` (debug) — clean
  • `cargo build --all-features --locked` — clean
  • `cargo +nightly fmt --all -- --check` — clean
  • `cargo clippy --all-targets --locked` — no findings (the previously-known `clippy::if_same_then_else` in `e2e/src/tests/h2_correctness_tests.rs` no longer fires on current toolchain)
  • `cargo test --workspace --locked --no-fail-fast` — 998 passed, 7 ignored, 0 failed
  • Unit tests for `evaluate_availability` (empty cluster, mixed health, retry-policy is_down exclusion) and `record_cluster_availability` (idempotent within regime, recovery transition, empty cluster stays Available, missing cluster is no-op)
  • Follow-up: e2e log-line scraping for `cluster_all_down_emits_log` / `cluster_recovered_emits_log` / per-token access-log assertions. The fixture cost (slow async backend that holds the queue without responding, plus a tracing subscriber that writes to an in-memory ring) does not justify itself for this PR; existing unit coverage validates the per-cluster transition logic and the four token strings are static, so the access-log assertion is mechanical to add later.

Closes #892

@FlorentinDUBOIS FlorentinDUBOIS self-assigned this May 3, 2026
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/892-cluster-availability branch from 3238b3f to 43034b2 Compare May 4, 2026 08:20
Pairs with the existing NoAvailableBackends event (tag 2) so dashboards
can plot per-cluster recovery as well as the all-down transition.
Highest existing tag was 28 (HealthCheckUnhealthy); 29 was free.

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Adds `backend.available` (per-(cluster, backend) boolean gauge) emitted
on every up/down transition site:
- active health check (lib/src/health_check.rs) UP/DOWN arms
- passive connect-success/failure in kawa_h1, mux, and tcp paths

The gauge piggybacks the existing transition guards (already gated on
`!already_unavailable && retry_policy.is_down()` for fail and on
`retry_policy.is_down()` for success), so emission happens only on real
state changes — no per-request overhead.

Backend::is_available() encapsulates the canonical availability check
(health.is_healthy && status == Normal && retry_policy not in backoff),
mirroring can_open() but reachable from &self contexts.

Also extends gauge! macro with a labelled (key, value, cluster, backend)
arm mirroring gauge_add!, routed through Subscriber::receive_metric so
filter_labels_for_detail collapses correctly at every MetricDetailLevel.
Health-check `health_check.healthy_backends` gauge is now labelled with
cluster_id (was overwritten across clusters — pre-existing bug).

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Replaces the single process-wide BackendMap.available bool with a
per-cluster Cell<ClusterAvailability> latched on BackendList. Driven
exclusively from BackendMap paths via record_cluster_availability(&self,
cluster_id) so the transition log + counter + Event fires exactly once
per state change.

What changes for operators:
- New per-cluster gauges cluster.available_backends and
  cluster.total_backends emitted on every routing decision and HC tick.
- New per-cluster counters cluster.no_available_backends (Available ->
  AllDown) and cluster.available_recovered (AllDown -> Available).
- New EventKind::ClusterRecovered emitted on the recovery transition,
  pairing with the existing NoAvailableBackends event.
- Per-cluster all-down log: error!("cluster X: all N backends are down").
- Per-cluster recovery log: info!("cluster X: backends recovered (i/N
  available)").

Wiring sites:
- BackendMap::backend_from_cluster_id failure arms (both empty-cluster
  and no-available-backend) call the helper after dropping the &mut
  BackendList borrow.
- BackendMap::add_backend/remove_backend re-evaluate after mutation.
- HealthChecker::evaluate_in_flight_check re-evaluates after the
  health_check.healthy_backends gauge update — the only path that
  captures passive-only recoveries (HC saw a backend come back but no
  session has hit it yet).

The previous global `available` flag was per-process, so the first
cluster to trip it silently swallowed every other cluster's all-down
transitions. The new tracker is per-cluster and idempotent (Cell::replace
returns the prior state; the helper only logs/emits on a real flip).

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Populates the existing RequestRecord.message field with a stable,
HAProxy/Pingora/Envoy-aligned vocabulary so operators can distinguish
timeout-driven 408/504 responses from backend-error 408/504.

Vocabulary (operator-visible API once shipped):

| Token                              | Trigger                                             | Status |
|------------------------------------|-----------------------------------------------------|--------|
| client_timeout                     | frontend timeout, request not fully received        | 408    |
| client_timeout_during_response     | frontend timeout while awaiting backend response    | 504    |
| backend_timeout                    | backend silent before first response byte           | 504    |
| backend_response_timeout           | backend stalled mid-response-body                   | 504/RST |

The discriminator rides on a new HttpContext.access_log_message field
(static-string-only, populated only inside the timeout handlers). H1's
log_default_answer_success forwards it to log_request, and the mux
side's Stream::generate_access_log falls back to it when the caller
does not pass an explicit message — caller-supplied messages (parser
errors, etc.) keep precedence.

Mux StreamState arms collapse onto the same vocabulary:
- Idle (H1 only) and Linked (back not consumed) -> client_timeout /
  client_timeout_during_response
- backend timeout, response not started -> backend_timeout
- backend timeout, response in progress -> backend_response_timeout
- Link arm (503, no backend yet) is NOT a timeout outcome — leave
  message as None.

The H1 invariant-break arm (`backend timeout while waiting for a
request, this should not happen`) collapses into backend_timeout for
operators while keeping its existing error! log for sozu maintainers.

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
…ess-log discriminator

CHANGELOG: Fixed entry for the labelled `health_check.healthy_backends`,
Added entries for the per-cluster availability surface (gauges, counters,
events, log lines) and the access-log timeout discriminator vocabulary,
Changed entry for the now-per-cluster `NoAvailableBackends` event.

doc/configure.md:
- New "#### Cluster availability" subsection under "### Available metrics"
  documenting cluster.{available_backends,total_backends,no_available_backends,
  available_recovered} and backend.available.
- New "#### Access-log `message` field on timeout" subsection under
  "### Observability" pinning the closed token vocabulary
  (client_timeout / client_timeout_during_response / backend_timeout /
  backend_response_timeout) with HTTP-status mapping.
- Note that EventKind::ClusterRecovered (proto tag 29) pairs with the
  existing NoAvailableBackends event on the SubscribeEvents bus.

doc/health_checks.md:
- Add the labelled health_check.healthy_backends row to the metrics table.
- Cross-reference the cluster-availability subsection in configure.md so
  operators do not search twice.
- Document NoAvailableBackends and ClusterRecovered in the Events section,
  noting they carry only cluster_id (not backend identity).

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Cross-reference the new HttpContext.access_log_message field from the
mux state-machine reference (LIFECYCLE.md sections 7.1 and 7.3) so
sections describing where set_default_answer and forcefully_terminate_answer
fire also point at the operator-visible discriminator vocabulary
documented in doc/configure.md.

No code change. Refs #892.

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

Six focused unit tests cover the per-cluster availability tracker:
- evaluate_availability returns (0, 0) for an empty BackendList.
- counts only Normal/Healthy/!retry-down backends; total stays at the
  configured count regardless of state.
- excludes retry_policy.is_down() backends even when health.is_healthy().
- record_cluster_availability flips the Cell to AllDown on a single
  unhealthy backend and stays idempotent on repeat calls in the same
  regime.
- recovers to Available when the unhealthy backend heals.
- empty cluster (total == 0) keeps the cell at the default Available so
  log spam is avoided during cluster bootstrap.
- missing cluster_id is a no-op (does not insert a BackendList).

The metric/event emission path (`gauge!`, `incr!`, `push_event`) is not
asserted here — those go through global thread-local sinks and are
covered indirectly by the existing e2e harness; an end-to-end test for
the cluster_all_down / cluster_recovered log lines is left as a
follow-up because the fixture cost (slow async backend that holds the
queue without responding) does not justify itself for this PR.

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Adds unit coverage for the new availability surface introduced for
issue #892:

- Backend::is_available combinatorics (fresh, unhealthy, retry-down,
  Closing).
- BackendList::evaluate_availability over mixed health states and
  empty lists.
- BackendMap::record_cluster_availability transitions: fresh empty
  cluster stays Available, Available -> AllDown flips on the first
  fully-unhealthy iteration, AllDown -> AllDown is idempotent (no
  duplicate emissions), recovery flips back to Available, missing
  cluster is a no-op (no insert, no panic).

Also harmonises the predicate: `Backend::is_available` now uses
`!retry_policy.is_down()` (matching `BackendList::evaluate_availability`
and Steven's "operationally up" reading from #892) instead of the
stricter `can_try() == OKAY`. Without this change the per-backend
gauge would flicker to 0 on every transient backoff window —
drowning real `is_down()` transitions in noise. The `can_open()`
predicate keeps its strict `can_try()` check because connect-time
routing must respect the wait window, but that path is a separate
concern from availability accounting.

Test plumbing: introduces a #[cfg(test)] `force_down` helper on
ExponentialBackoffPolicy + RetryPolicyWrapper. Driving the budget
to exhaustion via repeated `fail()` would otherwise require
sleeping through 1+2+4+8+16+32 s of exponential-backoff windows.

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Clarifies that the per-cluster availability surface and the per-backend
`backend.available` gauge work for clusters that have not configured an
active `[clusters.<id>.health_check]` block.

Transitions on the no-HC path are driven by Backend::retry_policy:
- Each TCP connect failure on tcp.rs / kawa_h1::fail_backend_connection /
  mux/mod.rs calls retry_policy.fail() and arms the backoff window. When
  every backend in the cluster reaches retry_policy.is_down() the next
  routing call flips the cell to AllDown and emits the error log +
  cluster.no_available_backends counter + EventKind::NoAvailableBackends.
- Each successful TCP connect calls retry_policy.succeed() which clears
  is_down() immediately; the success arm of backend_from_cluster_id then
  re-evaluates and flips the cell back to Available, emitting the info
  log + cluster.available_recovered counter + EventKind::ClusterRecovered.

The predicate is intentionally !retry_policy.is_down() rather than
Backend::can_open() so backends in the brief WAIT backoff window stay
counted as available — the cluster is still healthy, just briefly
throttled. Only budget exhaustion (current_tries >= max_tries) drives
AllDown.

An active health check is therefore an *additional* observation cadence,
not a prerequisite. It is useful when a cluster is idle (no requests
means no passive observations) but is not required for the surface to
function.

doc/health_checks.md gets a one-paragraph mirror of the same point so
operators reading from the HC side reach the same conclusion.

Refs #892

Signed-off-by: Florentin Dubois <[email protected]>
Reflow CHANGELOG.md, doc/configure.md, doc/health_checks.md, and
lib/src/protocol/mux/LIFECYCLE.md through `prettier --prose-wrap always`
(default printWidth = 80). Pure formatting; no semantic content change.

Reapplied after the rebase onto origin/main since the previous prettier
commit conflicted heavily with the new tcp-rtt access-log work and was
skipped during conflict resolution. Running prettier once at the rebased
tip keeps the touched files consistent.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/892-cluster-availability branch from 43034b2 to 6355a3f Compare May 4, 2026 11:40
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 9b9d123 into main May 4, 2026
7 of 33 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/892-cluster-availability branch May 4, 2026 12:43
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.

Write a log when backends are detected down or up.

1 participant