mirror of
https://github.com/block/buzz.git
synced 2026-11-29 04:32:08 +00:00
## Summary
Relay pods on large deployments can take over 5 minutes to open their
health port, and right now nothing shows which startup step is slow.
Startup timing ends at `metrics_bind`, and the slow work all happens
after it.
This PR times every startup step from Postgres connect through public
listener bind. It does not change startup behavior.
- Each step logs `Startup phase started` and `Startup phase finished`,
with `phase`, `elapsed_ms`, and `status` (`succeeded` / `degraded` /
`failed`, the same values `buzz_process_lifecycle` records use).
- Gauge `buzz_startup_phase_current{phase}` is `1` while a step runs and
`0` after it ends. A pod that is still starting shows exactly which step
it is on.
- Gauge `buzz_startup_phase_seconds{phase}` records each finished step's
duration.
- The startup NIP-43 membership reconcile logs `NIP-43 startup
reconciliation progress` every 5,000 communities, with `done`, `total`,
`republished`, `failed`, and `elapsed_ms`.
These are gauges rather than counters on purpose. Each value is written
once per boot, and a monotonic-counter scrape drops a series' first
sample, so a one-shot counter never shows up.
## Contract change
`deploy/charts/buzz/README.md` ("Early-startup telemetry contract") said
the early lifecycle phases are log-only. That still holds: `crypto_init`
through `metrics_bind` are unchanged and emit no metrics.
The README now also documents the post-bind steps. The guard in
`boot_lifecycle.rs` now allows exactly the two `buzz_startup_phase_*`
families. It still rejects any other startup, boot, or lifecycle family,
and it also rejects any exported label value that names an early phase.
## Design
- `crates/buzz-relay/src/startup_steps.rs` adds a closed `StartupStep`
vocabulary (18 steps) and a `StepTimer` guard.
- A step ends exactly once:
- `finish()` → `succeeded`
- `degrade()` then `finish()` → `degraded` (a non-fatal error branch)
- dropped without finishing → `failed` (covers `?` early returns and
panics)
- The NIP-43 and large-roster reconciles now return `ReconcileSummary {
repaired, failed }`. A sweep where any item fails ends its step
`degraded`, and the final log line includes the `failed` count. NIP-FI
warm ends `degraded` when any issuer did not warm. The deprecated
`reconcile_nip43_membership_snapshots` wrapper still returns `repaired`.
- Steps that are disabled by config (migrate, audit connect, NIP-FI
warm, git probe, NIP-43 reconcile) are not timed, so their series never
appear.
- The gauges are set once, so they age out after the existing gauge idle
timeout (2700 s with default intervals; logged as `idle_timeout_secs`).
A step that runs longer than that loses its `_current` series. The
README says so.
- Progress logging runs only for the `Bootstrap` reconcile. The 60 s
maintenance sweep stays quiet.
## What got simpler
Little got simpler in the code: this mostly adds instrumentation. One CI
gap closed along the way: the 54 `config` tests and the 9 non-ignored
`boot_lifecycle` tests, which ran in no CI lane, now run in `test-unit`.
The instrumentation is scoped as small as I could make it, and it is the
evidence needed for the follow-up that should delete code: moving the
per-community NIP-43 reconcile off the pre-bind path, after which the
900 s startup-probe override can go back to the chart default.
## Testing
- `startup_steps` unit tests (`DebuggingRecorder`):
- a running step is current and has no duration
- a finished step clears current and records its elapsed time
- dropped and degraded steps clear current and record a duration
- log capture: `finish`, `degrade`+`finish`, drop, and panic each emit
exactly one `Startup phase finished` record with the right `status`.
Mutating `degrade()` to a no-op and removing the ends-once guard makes
these tests fail.
- the vocabulary is unique and shares no names with the early lifecycle
phases
- Tests that capture logs or check callsite interest now share
`test_support::tracing_dispatch_lock()`. These are the `startup_steps`
helpers, two `telemetry` tests, and the `config` and `bridge`
log-capture helpers. tracing-core caches each callsite's interest across
the whole process. Without the lock, the new panic test lost its record
in 60 of 150 parallel runs of `telemetry:: startup_steps:: config::`.
With the lock it failed 0 of 300. Removing the lock from `gauges()`
brings the failures back (53 of 100 runs).
- `nip43_progress_logs_every_interval_inside_the_startup_sweep_only`
checks the cadence at 79,942 communities (15 progress lines, none at the
start or end) and table-tests that the maintenance sweep never logs
progress.
-
`boot_lifecycle::successful_main_emits_complete_lifecycle_and_reports_current_startup_step`
boots the real relay binary against a TCP peer that never speaks
Postgres. It asserts that `/metrics` shows
`buzz_startup_phase_current{phase="db_connect"} 1` and no finished-step
durations, and that no early phase leaks into metrics.
- **CI routing.** `just test-unit` picks relay tests by hand-maintained
filter. Before this PR, CI's filters selected none of the
`startup_steps`, `telemetry`, `config` or non-ignored `boot_lifecycle`
tests above; the NIP-43 cadence test is picked up by the existing
`handlers::side_effects::tests::` clause. Its infra-free relay stanza
now selects `startup_steps::tests::`, `telemetry::tests::` and
`config::tests::` (anchored so `nip_fi_config` is not selected twice),
and a new `cargo nextest run -p buzz-relay --test boot_lifecycle` line
runs the non-ignored `boot_lifecycle` tests (they spawn the real binary
and need no Postgres or Redis; the Postgres cases stay `#[ignore]`d).
`scripts/run-tests.sh` mirrors both, running `telemetry` and `config`
single-threaded because they mutate process env.
### Manual check
1. `just relay` (or run `buzz-relay` against local Postgres and Redis).
2. Once the relay is up: `curl -s localhost:9102/metrics | grep
buzz_startup_phase`. Every step that ran has a `_seconds` value, and
every `_current` value is 0.
3. In the relay logs, `"Startup phase finished"` lines show each step's
`elapsed_ms`.
---------
Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
154 lines
5.8 KiB
Rust
154 lines
5.8 KiB
Rust
const DEFAULT_DATABASE_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials
|
|
|
|
/// Serialize lib tests whose assertions depend on which tracing dispatchers
|
|
/// are live: log-capture and callsite-interest tests, and tests that fire the
|
|
/// callsites they assert on. tracing-core caches each callsite's interest
|
|
/// process-wide from whichever dispatchers are live when it is first hit or
|
|
/// rebuilt, so a parallel test's dispatcher (or a thread with none) can enable
|
|
/// or disable another test's callsites. Not reentrant; take it once per test.
|
|
/// Two async sites install a dispatcher without it, because the guard would be
|
|
/// held across `.await`: `router.rs`'s otel-export test and the
|
|
/// `pause_after_aux_page` helper in
|
|
/// `api/bridge/thread_window/postgres_tests/failure_postgres_tests.rs`.
|
|
pub(crate) fn tracing_dispatch_lock() -> std::sync::MutexGuard<'static, ()> {
|
|
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
}
|
|
|
|
/// Resolve the database URL shared by PostgreSQL-backed relay tests.
|
|
pub(crate) fn database_url() -> String {
|
|
std::env::var("BUZZ_TEST_DATABASE_URL")
|
|
.or_else(|_| std::env::var("TEST_DATABASE_URL"))
|
|
.or_else(|_| std::env::var("DATABASE_URL"))
|
|
.unwrap_or_else(|_| DEFAULT_DATABASE_URL.to_owned())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
const CHILD_TEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
|
#[cfg(test)]
|
|
const MAX_CAPTURE_BYTES: u64 = 1024 * 1024;
|
|
|
|
#[cfg(test)]
|
|
struct CapturedStream {
|
|
retained: Vec<u8>,
|
|
total_bytes: u64,
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn capture_stream(mut stream: impl std::io::Read) -> CapturedStream {
|
|
let mut retained = Vec::new();
|
|
let mut total_bytes = 0_u64;
|
|
let mut chunk = [0_u8; 8192];
|
|
loop {
|
|
let read = stream.read(&mut chunk).expect("read child output pipe");
|
|
if read == 0 {
|
|
break;
|
|
}
|
|
total_bytes = total_bytes.saturating_add(u64::try_from(read).expect("read size fits u64"));
|
|
let remaining = usize::try_from(MAX_CAPTURE_BYTES)
|
|
.expect("capture ceiling fits usize")
|
|
.saturating_sub(retained.len());
|
|
retained.extend_from_slice(&chunk[..read.min(remaining)]);
|
|
}
|
|
CapturedStream {
|
|
retained,
|
|
total_bytes,
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn join_capture(capture: std::thread::JoinHandle<CapturedStream>, stream: &str) -> Vec<u8> {
|
|
let capture = capture.join().expect("child capture thread must not panic");
|
|
assert!(
|
|
capture.total_bytes <= MAX_CAPTURE_BYTES,
|
|
"child {stream} exceeded {MAX_CAPTURE_BYTES} bytes: {}",
|
|
capture.total_bytes,
|
|
);
|
|
capture.retained
|
|
}
|
|
|
|
/// Run exactly one unit test in an isolated, deadline-bounded child process.
|
|
#[cfg(test)]
|
|
pub(crate) fn run_exact_test_child(test_name: &str, child_env: &str) {
|
|
use std::{
|
|
process::{Command, Stdio},
|
|
thread,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
let mut child = Command::new(std::env::current_exe().expect("test executable"))
|
|
.arg("--exact")
|
|
.arg(test_name)
|
|
.arg("--nocapture")
|
|
.env(child_env, "1")
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.spawn()
|
|
.expect("spawn isolated test child");
|
|
let stdout = child.stdout.take().expect("child stdout pipe");
|
|
let stderr = child.stderr.take().expect("child stderr pipe");
|
|
let stdout = thread::spawn(move || capture_stream(stdout));
|
|
let stderr = thread::spawn(move || capture_stream(stderr));
|
|
|
|
let deadline = Instant::now() + CHILD_TEST_TIMEOUT;
|
|
let (status, timed_out) = loop {
|
|
if let Some(status) = child.try_wait().expect("poll isolated test child") {
|
|
break (status, false);
|
|
}
|
|
if Instant::now() >= deadline {
|
|
let _ = child.kill();
|
|
let status = child.wait().expect("reap timed-out test child");
|
|
break (status, true);
|
|
}
|
|
thread::sleep(Duration::from_millis(10));
|
|
};
|
|
|
|
let stdout = join_capture(stdout, "stdout");
|
|
let stderr = join_capture(stderr, "stderr");
|
|
let output = format!(
|
|
"{}{}",
|
|
String::from_utf8_lossy(&stdout),
|
|
String::from_utf8_lossy(&stderr)
|
|
);
|
|
|
|
assert!(
|
|
!timed_out,
|
|
"isolated test child exceeded {CHILD_TEST_TIMEOUT:?}:\n{output}"
|
|
);
|
|
assert!(status.success(), "isolated test child failed:\n{output}");
|
|
assert!(
|
|
output.contains("running 1 test") && output.contains(test_name),
|
|
"exact selector did not run the intended test {test_name}:\n{output}"
|
|
);
|
|
}
|
|
|
|
/// A database handle on which only restriction-state reads fail: its
|
|
/// `search_path` puts a schema first whose `community_bans` is a view that
|
|
/// errors when read, so every other table resolves to `public` as normal.
|
|
/// Returns the handle, an admin pool, and the schema to drop afterwards.
|
|
#[cfg(test)]
|
|
pub(crate) async fn restriction_lookup_failing_db() -> (buzz_db::Db, sqlx::PgPool, String) {
|
|
use sqlx::postgres::PgConnectOptions;
|
|
let url = database_url();
|
|
let admin = sqlx::PgPool::connect(&url)
|
|
.await
|
|
.expect("PostgreSQL must be available");
|
|
let schema = format!("ban_lookup_fails_{}", uuid::Uuid::new_v4().simple());
|
|
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
|
|
"CREATE SCHEMA {schema}; \
|
|
CREATE VIEW {schema}.community_bans AS \
|
|
SELECT * FROM public.community_bans WHERE 1 / (SELECT count(*) * 0 FROM public.communities) = 1;"
|
|
)))
|
|
.execute(&admin)
|
|
.await
|
|
.expect("create failing restriction schema");
|
|
let options = url
|
|
.parse::<PgConnectOptions>()
|
|
.expect("database url")
|
|
.options([("search_path", format!("{schema}, public"))]);
|
|
let pool = sqlx::PgPool::connect_with(options)
|
|
.await
|
|
.expect("failing restriction pool");
|
|
(buzz_db::Db::from_pool(pool), admin, schema)
|
|
}
|