mirror of
https://github.com/block/buzz.git
synced 2026-12-01 05:32:24 +00:00
## Problem A rolling deploy can stall relay startup for 30s per dead mesh peer. - A pod publishes its mesh ready record during `mesh_boot` and clears it only on graceful shutdown. If a later fatal startup check kills the pod, the record lingers until it expires. - Dialing that address never gets an answer, so `MeshEndpoint::connect` waits out QUIC's default 30s idle timeout. `reconcile_once` dials candidates one at a time, so every dead peer adds another 30s, both in the boot-time `mesh_initial_reconcile` step and in every later reconcile pass. - The fatal check that killed those pods was the git conformance probe. A transient S3 `500 InternalError` on one racer was treated as a conformance failure. ## Changes 1. **Bounded, concurrent mesh dials** (`buzz-relay-mesh/src/runtime.rs`). Each connect attempt is wrapped in `DIAL_TIMEOUT` (2s; in-cluster handshakes take milliseconds), and a reconcile pass dials its candidates concurrently. A pass with dead peers now costs about one dial timeout instead of 30s per peer. The candidate set is bounded by the membership table. 2. **Conformance probe before mesh boot** (`buzz-relay/src/main.rs`). This only moves an existing block, so a pod that fails the probe exits before it publishes a ready record peers would dial. 3. **5xx racers are unknown outcomes** (`buzz-relay/src/api/git/store.rs`). The race phases already drop socket/send failures from the observer set as "outcome unknown". A 5xx is the backend declining to classify the write, so it now joins them through one shared `racer_outcome_unknown` helper. 4xx answers, including 412, still count as evidence. A backend that 5xxs every racer still fails closed on the two-observer floor. Because a dropped racer's write may still have landed, every `if_match_race` round now reads the pointer back and requires the winner's exact body and ETag. Otherwise a backend that commits a stale write and then answers 5xx would pass in the last round. §Conformance steps 2–3 in `docs/git-on-object-storage.md` now state this drop-and-floor rule. ## What got simpler The two duplicated drop-classification match arms in the probe now share one helper. The probe/mesh fix is a reorder of existing startup steps, not a new mechanism or rollback path. ## Tests - `runtime::tests::reconcile_pass_bounds_dials_to_unresponsive_peers`: three black-hole peers (bound UDP sockets that never read) plus one live peer. The pass must finish within `2 × DIAL_TIMEOUT` (a serial pass would take at least `3 × DIAL_TIMEOUT`, and without the timeout about 30s), the live peer must connect, and each dead peer must end `Disconnected`. - `store::tests::probe_drops_5xx_racers_but_keeps_4xx_as_evidence`: pins the classification boundary (5xx and I/O are unknown; 400/403/412/499 are evidence). - `store::fault_probe::*`: runs `run_conformance_probe` against an in-process S3 fake that injects racer faults at the HTTP boundary, so responses pass through rust-s3's `fail-on-err` mapping and retry. One 5xx racer in either race phase is dropped and admitted (`transport_drops == 1`). Too few classified observers fail closed: one observer in either phase, and all-5xx in `if_none_match_race`. An unexpected 4xx racer fails closed in both phases. A racer whose stale write lands and is then answered 5xx fails closed on the post-round readback (`dropped_racer_whose_stale_write_lands_fails_closed`). A clean fake passes with zero drops. - CI lane: no `api::store` test ran in any CI lane before, including the existing ones. The `just test-unit` nextest filter and the `scripts/run-tests.sh` fallback now select `api:
:store::tests` and `::fault_probe`. The live-MinIO `::probe` module stays opt-in. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
399 lines
14 KiB
Rust
399 lines
14 KiB
Rust
//! Timing for the relay's startup work between metrics bind and serving.
|
|
//!
|
|
//! [`crate::lifecycle`] covers the earliest phases, which run before the
|
|
//! metrics exporter exists, as log-only records. Everything after
|
|
//! `metrics_bind` runs with a working recorder and structured logging, so
|
|
//! each step logs `Startup phase finished` (`phase`, `elapsed_ms`, `status`)
|
|
//! and sets two gauges:
|
|
//!
|
|
//! - `buzz_startup_phase_current{phase}` is `1` while the step runs and `0`
|
|
//! once it ends, so a pod that is still starting shows which step it is on.
|
|
//! - `buzz_startup_phase_seconds{phase}` is the step's wall-clock duration,
|
|
//! set once when the step ends.
|
|
//!
|
|
//! The `phase` label values are a closed vocabulary ([`StartupStep::ALL`]).
|
|
//! They never overlap the early lifecycle phase names.
|
|
//!
|
|
//! A step may contain sub-steps: `mesh_boot` runs `mesh_bind`,
|
|
//! `mesh_publish`, then `mesh_initial_reconcile`, so a pod stuck in mesh boot
|
|
//! shows both `mesh_boot` and the sub-step it is on as current.
|
|
|
|
use std::time::Instant;
|
|
|
|
use tracing::{info, warn};
|
|
|
|
/// Gauge that is `1` while a startup step is running.
|
|
pub const CURRENT_METRIC: &str = "buzz_startup_phase_current";
|
|
/// Gauge holding a finished startup step's duration in seconds.
|
|
pub const SECONDS_METRIC: &str = "buzz_startup_phase_seconds";
|
|
|
|
/// Register the startup-step gauge descriptions.
|
|
pub(crate) fn describe_metrics() {
|
|
metrics::describe_gauge!(
|
|
CURRENT_METRIC,
|
|
"1 while the labelled post-metrics-bind startup phase is running, 0 once it ends"
|
|
);
|
|
metrics::describe_gauge!(
|
|
SECONDS_METRIC,
|
|
metrics::Unit::Seconds,
|
|
"Wall-clock duration of the labelled post-metrics-bind startup phase"
|
|
);
|
|
}
|
|
|
|
/// One timed unit of startup work after the metrics listener is up.
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum StartupStep {
|
|
/// Connect the Postgres writer (and lazy reader) pools.
|
|
DbConnect,
|
|
/// Apply database migrations (only when `BUZZ_AUTO_MIGRATE` is on).
|
|
DbMigrate,
|
|
/// Ensure or audit future event partitions.
|
|
PartitionEnsure,
|
|
/// Verify the community-deletion serving fences.
|
|
DeletionFenceVerify,
|
|
/// Verify the replica floor guard and start the fence probe.
|
|
ReplicaFenceProbe,
|
|
/// Ensure the deployment community, backfill the allowlist, and bootstrap the owner.
|
|
MembershipBootstrap,
|
|
/// Connect the audit database pool (only when audit is enabled).
|
|
AuditConnect,
|
|
/// Connect Redis commands and pub/sub.
|
|
RedisConnect,
|
|
/// Warm NIP-FI JWKS snapshots (only when NIP-FI is configured).
|
|
NipFiJwksWarm,
|
|
/// Load the first NIP-FI binding snapshot (only for the `database` source).
|
|
NipFiSnapshotLoad,
|
|
/// Run the git object-store conformance probe (when enabled).
|
|
GitConformanceProbe,
|
|
/// Start the inter-relay mesh (no-op when the mesh is off).
|
|
MeshBoot,
|
|
/// Inside `MeshBoot`: bind the mesh UDP endpoint.
|
|
MeshBind,
|
|
/// Inside `MeshBoot`: publish this runtime's ready record to Redis.
|
|
MeshPublish,
|
|
/// Inside `MeshBoot`: the first registry scan and peer-dial pass.
|
|
MeshInitialReconcile,
|
|
/// Repair large NIP-29 channel roster snapshots.
|
|
LargeRosterReconcile,
|
|
/// Bind the private health listener.
|
|
HealthBind,
|
|
/// Bind the public relay listener.
|
|
ListenerBind,
|
|
}
|
|
|
|
impl StartupStep {
|
|
/// The complete `phase` label vocabulary.
|
|
pub const ALL: &[Self] = &[
|
|
Self::DbConnect,
|
|
Self::DbMigrate,
|
|
Self::PartitionEnsure,
|
|
Self::DeletionFenceVerify,
|
|
Self::ReplicaFenceProbe,
|
|
Self::MembershipBootstrap,
|
|
Self::AuditConnect,
|
|
Self::RedisConnect,
|
|
Self::NipFiJwksWarm,
|
|
Self::NipFiSnapshotLoad,
|
|
Self::GitConformanceProbe,
|
|
Self::MeshBoot,
|
|
Self::MeshBind,
|
|
Self::MeshPublish,
|
|
Self::MeshInitialReconcile,
|
|
Self::LargeRosterReconcile,
|
|
Self::HealthBind,
|
|
Self::ListenerBind,
|
|
];
|
|
|
|
/// Stable `phase` label value.
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::DbConnect => "db_connect",
|
|
Self::DbMigrate => "db_migrate",
|
|
Self::PartitionEnsure => "partition_ensure",
|
|
Self::DeletionFenceVerify => "deletion_fence_verify",
|
|
Self::ReplicaFenceProbe => "replica_fence_probe",
|
|
Self::MembershipBootstrap => "membership_bootstrap",
|
|
Self::AuditConnect => "audit_connect",
|
|
Self::RedisConnect => "redis_connect",
|
|
Self::NipFiJwksWarm => "nip_fi_jwks_warm",
|
|
Self::NipFiSnapshotLoad => "nip_fi_snapshot_load",
|
|
Self::GitConformanceProbe => "git_conformance_probe",
|
|
Self::MeshBoot => "mesh_boot",
|
|
Self::MeshBind => "mesh_bind",
|
|
Self::MeshPublish => "mesh_publish",
|
|
Self::MeshInitialReconcile => "mesh_initial_reconcile",
|
|
Self::LargeRosterReconcile => "large_roster_reconcile",
|
|
Self::HealthBind => "health_bind",
|
|
Self::ListenerBind => "listener_bind",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// How a startup step ended (same values as `buzz_process_lifecycle` `status`).
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
enum StepStatus {
|
|
Succeeded,
|
|
/// Non-fatal error; startup continued.
|
|
Degraded,
|
|
/// Dropped without [`StepTimer::finish`] — an early return or a panic.
|
|
Failed,
|
|
}
|
|
|
|
impl StepStatus {
|
|
const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::Succeeded => "succeeded",
|
|
Self::Degraded => "degraded",
|
|
Self::Failed => "failed",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A running startup step. Ends exactly once: [`StepTimer::finish`] reports
|
|
/// `succeeded` (or `degraded` after [`StepTimer::degrade`]); dropping it
|
|
/// without finishing reports `failed`, which covers `?` returns and panics.
|
|
#[must_use = "a dropped step timer reports the step as failed"]
|
|
pub struct StepTimer {
|
|
step: StartupStep,
|
|
started: Instant,
|
|
degraded: bool,
|
|
ended: bool,
|
|
}
|
|
|
|
impl StepTimer {
|
|
/// Start timing `step` and mark it as the pod's current step.
|
|
pub fn start(step: StartupStep) -> Self {
|
|
metrics::gauge!(CURRENT_METRIC, "phase" => step.as_str()).set(1.0);
|
|
info!(phase = step.as_str(), "Startup phase started");
|
|
Self {
|
|
step,
|
|
started: Instant::now(),
|
|
degraded: false,
|
|
ended: false,
|
|
}
|
|
}
|
|
|
|
/// Record that the step hit a non-fatal error; it will end as `degraded`.
|
|
pub fn degrade(&mut self) {
|
|
self.degraded = true;
|
|
}
|
|
|
|
/// End the step as `succeeded`, or `degraded` if [`Self::degrade`] was called.
|
|
pub fn finish(mut self) {
|
|
let status = if self.degraded {
|
|
StepStatus::Degraded
|
|
} else {
|
|
StepStatus::Succeeded
|
|
};
|
|
self.end(status);
|
|
}
|
|
|
|
fn end(&mut self, status: StepStatus) {
|
|
if self.ended {
|
|
return;
|
|
}
|
|
self.ended = true;
|
|
let elapsed = self.started.elapsed();
|
|
let phase = self.step.as_str();
|
|
metrics::gauge!(SECONDS_METRIC, "phase" => phase).set(elapsed.as_secs_f64());
|
|
metrics::gauge!(CURRENT_METRIC, "phase" => phase).set(0.0);
|
|
let elapsed_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
|
|
match status {
|
|
StepStatus::Succeeded => {
|
|
info!(
|
|
phase,
|
|
elapsed_ms,
|
|
status = status.as_str(),
|
|
"Startup phase finished"
|
|
)
|
|
}
|
|
StepStatus::Degraded | StepStatus::Failed => {
|
|
warn!(
|
|
phase,
|
|
elapsed_ms,
|
|
status = status.as_str(),
|
|
"Startup phase finished"
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for StepTimer {
|
|
fn drop(&mut self) {
|
|
self.end(StepStatus::Failed);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
|
|
|
use super::*;
|
|
use crate::lifecycle::StartupPhase;
|
|
|
|
/// Gauge values keyed by `(metric, phase)` after running `body`.
|
|
///
|
|
/// Holds the tracing dispatch lock: `body` fires the step log callsites
|
|
/// with no dispatcher, which must not race a `finished_records` capture.
|
|
fn gauges(body: impl FnOnce()) -> HashMap<(String, String), f64> {
|
|
let _tracing = crate::test_support::tracing_dispatch_lock();
|
|
let recorder = DebuggingRecorder::new();
|
|
let snapshotter = recorder.snapshotter();
|
|
metrics::with_local_recorder(&recorder, body);
|
|
snapshotter
|
|
.snapshot()
|
|
.into_vec()
|
|
.into_iter()
|
|
.filter_map(|(key, _, _, value)| {
|
|
let key = key.key();
|
|
let phase = key
|
|
.labels()
|
|
.find(|l| l.key() == "phase")?
|
|
.value()
|
|
.to_owned();
|
|
match value {
|
|
DebugValue::Gauge(v) => Some(((key.name().to_owned(), phase), v.into_inner())),
|
|
_ => None,
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct CapturedLogs(Arc<Mutex<Vec<u8>>>);
|
|
|
|
impl std::io::Write for CapturedLogs {
|
|
fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
|
|
self.0
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
.extend_from_slice(data);
|
|
Ok(data.len())
|
|
}
|
|
fn flush(&mut self) -> std::io::Result<()> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs {
|
|
type Writer = Self;
|
|
fn make_writer(&'a self) -> Self::Writer {
|
|
self.clone()
|
|
}
|
|
}
|
|
|
|
/// `(phase, status)` of every `Startup phase finished` record `body` emits.
|
|
fn finished_records(body: impl FnOnce()) -> Vec<(String, String)> {
|
|
let _tracing = crate::test_support::tracing_dispatch_lock();
|
|
let logs = CapturedLogs::default();
|
|
let subscriber = tracing_subscriber::fmt()
|
|
.json()
|
|
.with_writer(logs.clone())
|
|
.finish();
|
|
tracing::subscriber::with_default(subscriber, body);
|
|
let bytes = logs
|
|
.0
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
.clone();
|
|
String::from_utf8_lossy(&bytes)
|
|
.lines()
|
|
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
|
|
.filter(|record| record["fields"]["message"] == "Startup phase finished")
|
|
.map(|record| {
|
|
let field = |name: &str| record["fields"][name].as_str().unwrap_or("").to_owned();
|
|
(field("phase"), field("status"))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn get(gauges: &HashMap<(String, String), f64>, metric: &str, phase: &str) -> Option<f64> {
|
|
gauges.get(&(metric.to_owned(), phase.to_owned())).copied()
|
|
}
|
|
|
|
#[test]
|
|
fn running_step_is_current_and_has_no_duration() {
|
|
let mut held = None;
|
|
let gauges = gauges(|| held = Some(StepTimer::start(StartupStep::LargeRosterReconcile)));
|
|
assert_eq!(
|
|
get(&gauges, CURRENT_METRIC, "large_roster_reconcile"),
|
|
Some(1.0)
|
|
);
|
|
assert_eq!(get(&gauges, SECONDS_METRIC, "large_roster_reconcile"), None);
|
|
std::mem::forget(held);
|
|
}
|
|
|
|
#[test]
|
|
fn finished_step_clears_current_and_records_duration() {
|
|
let gauges = gauges(|| {
|
|
let step = StepTimer::start(StartupStep::DbConnect);
|
|
std::thread::sleep(std::time::Duration::from_millis(5));
|
|
step.finish();
|
|
});
|
|
assert_eq!(get(&gauges, CURRENT_METRIC, "db_connect"), Some(0.0));
|
|
let seconds = get(&gauges, SECONDS_METRIC, "db_connect").expect("duration gauge");
|
|
assert!(seconds >= 0.005, "duration {seconds} shorter than the step");
|
|
}
|
|
|
|
#[test]
|
|
fn dropped_and_degraded_steps_clear_current_and_record_duration() {
|
|
let gauges = gauges(|| {
|
|
drop(StepTimer::start(StartupStep::RedisConnect));
|
|
let mut step = StepTimer::start(StartupStep::PartitionEnsure);
|
|
step.degrade();
|
|
step.finish();
|
|
});
|
|
for phase in ["redis_connect", "partition_ensure"] {
|
|
assert_eq!(get(&gauges, CURRENT_METRIC, phase), Some(0.0));
|
|
assert!(get(&gauges, SECONDS_METRIC, phase).is_some());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn each_terminal_path_logs_exactly_one_finished_record_with_its_status() {
|
|
let records = finished_records(|| {
|
|
StepTimer::start(StartupStep::DbConnect).finish();
|
|
let mut degraded = StepTimer::start(StartupStep::PartitionEnsure);
|
|
degraded.degrade();
|
|
degraded.finish();
|
|
drop(StepTimer::start(StartupStep::RedisConnect));
|
|
});
|
|
let expected = [
|
|
("db_connect", "succeeded"),
|
|
("partition_ensure", "degraded"),
|
|
("redis_connect", "failed"),
|
|
]
|
|
.map(|(phase, status)| (phase.to_owned(), status.to_owned()));
|
|
assert_eq!(records, expected);
|
|
}
|
|
|
|
#[test]
|
|
fn a_panic_inside_a_step_logs_it_failed() {
|
|
let records = finished_records(|| {
|
|
let result = std::panic::catch_unwind(|| {
|
|
let _step = StepTimer::start(StartupStep::MeshBoot);
|
|
panic!("step body panicked");
|
|
});
|
|
assert!(result.is_err());
|
|
});
|
|
assert_eq!(records, [("mesh_boot".to_owned(), "failed".to_owned())]);
|
|
}
|
|
|
|
#[test]
|
|
fn vocabulary_is_unique_and_disjoint_from_early_lifecycle_phases() {
|
|
let names: HashSet<_> = StartupStep::ALL.iter().map(|s| s.as_str()).collect();
|
|
assert_eq!(names.len(), StartupStep::ALL.len());
|
|
for phase in StartupPhase::ALL {
|
|
assert!(
|
|
!names.contains(phase.as_str()),
|
|
"{} overlaps",
|
|
phase.as_str()
|
|
);
|
|
}
|
|
}
|
|
}
|
