Skip to main content

trusty_code/logging/
mod.rs

1//! Tracing and logging initialisation for tcode.
2//!
3//! Why: All tcode binaries and the library's test harness need consistent
4//! tracing initialisation that writes to stderr (never stdout — stdout is the
5//! API transport channel). Centralising it here prevents duplicated setup and
6//! ensures the `try_init` pattern is used everywhere so test binaries remain
7//! idempotent.
8//! What: `init_tracing` initialises the global tracing subscriber from the
9//! `RUST_LOG` env var. `init_tracing_for_test` is a lightweight variant for
10//! test binaries that silently drops duplicate init errors.
11//! Test: `init_tracing_for_test_is_idempotent` calls the function twice and
12//! asserts no panic.
13//!
14//! ## Log-level convention (#2857)
15//!
16//! trusty-code makes control-flow decisions that change a run's outcome —
17//! caps tripping, retries, delegation refusals, fallbacks, truncations,
18//! skips, gate interceptions. Every such decision point MUST log at the
19//! level below when it fires; the organising principle is:
20//!
21//! - **`warn!`** — the decision silently changes the run's outcome (a cap
22//!   trips, a retry budget is exhausted, a gate refuses/intercepts an
23//!   action, a floor is exceeded). Minimum level for anything that could
24//!   otherwise only be diagnosed via cross-run forensics (the #2852 class
25//!   of bug this ticket exists to prevent).
26//! - **`info!`** — a degradation the model or user acts on, but the run
27//!   proceeds normally (a fallback lane serves results, a redundant
28//!   re-run is suppressed, a budget truncation drops lowest-scored
29//!   content, cadence compression fires on schedule).
30//! - **`debug!`** — detail useful for tracing a run's mechanics but not
31//!   itself a decision that changes the outcome (byte-level truncation of
32//!   a single tool's output, already surfaced in-band to the model).
33//! - **`error!`** — reserved for regression signals: a safeguard fired
34//!   under conditions where it should have been structurally unreachable
35//!   (e.g. threshold compaction firing while the cadence compressor is
36//!   supposed to keep the transcript under budget at all times).
37//!
38//! All logs go to **stderr** via `tracing` (never stdout — see the module
39//! doc above) and are filtered by `RUST_LOG`, falling back to `info` when it
40//! is unset or invalid.
41//!
42//! **Logs vs. events:** structured [`crate::events`] are telemetry for the
43//! UI (a typed, machine-consumed fact stream); `tracing` logs here are for
44//! an operator reading stderr while debugging a run. Both may describe the
45//! same underlying fact, but one must never substitute for the other — an
46//! event emission does not excuse a silent decision point from also logging.
47
48use tracing_subscriber::EnvFilter;
49
50/// Build the tracing filter, falling back to [`DEFAULT_LOG_LEVEL`].
51///
52/// Why: `EnvFilter::from_default_env` yields an EMPTY directive set when
53/// `RUST_LOG` is unset or malformed, which filters everything below `error`
54/// and silences the `warn!` decision points this module's convention requires.
55/// What: parses `RUST_LOG`; on any parse failure builds a filter from
56/// [`DEFAULT_LOG_LEVEL`] instead.
57/// Test: `tests/logging_e2e.rs`.
58fn env_filter() -> EnvFilter {
59    EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOG_LEVEL))
60}
61
62/// Initialise the global tracing subscriber.
63///
64/// Why: All daemons and CLI entry points call this once at startup to ensure
65/// log output is consistently routed to stderr with the `RUST_LOG` filter.
66/// What: Installs a stderr-bound fmt subscriber with [`env_filter`].
67/// Panics if called twice (use `init_tracing_for_test` in test binaries).
68/// Test: Called in `main.rs`; correctness is verified by observing log output.
69pub fn init_tracing() {
70    tracing_subscriber::fmt()
71        .with_env_filter(env_filter())
72        .with_writer(std::io::stderr)
73        .init();
74}
75
76/// Initialise the global tracing subscriber, silently ignoring duplicate inits.
77///
78/// Why: Test binaries may link multiple test modules that all call setup code.
79/// `try_init` returns an error on the second call instead of panicking, so
80/// test runs remain stable regardless of execution order.
81/// What: Calls `try_init()`; swallows the error if already initialised.
82/// Test: `init_tracing_for_test_is_idempotent`.
83pub fn init_tracing_for_test() {
84    let _ = tracing_subscriber::fmt()
85        .with_env_filter(env_filter())
86        .with_writer(std::io::stderr)
87        .try_init();
88}
89
90/// Log level used when no `RUST_LOG` env var is set.
91///
92/// Why: Documents and centralises the default so operators know what to expect
93/// without reading source.
94/// What: A static string literal used by [`env_filter`] as its real fallback.
95/// Test: `tests/logging_e2e.rs` covers unset and invalid `RUST_LOG` values.
96pub const DEFAULT_LOG_LEVEL: &str = "info";
97
98// ── Tests ─────────────────────────────────────────────────────────────────────
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    /// `init_tracing_for_test` must be idempotent across multiple calls.
105    ///
106    /// Why: Test binaries are often multi-crate and may call init from several
107    /// setup functions; a panic on re-init would break the test suite. (#2857)
108    /// This is the ONLY other site in this crate's `--lib` test binary that
109    /// installs a GLOBAL tracing subscriber via `try_init`. Calling
110    /// `crate::test_support::begin_capture()` first guarantees the #2857
111    /// capture module's own `set_global_default` call always wins that
112    /// one-shot race — this test's own `try_init()` then simply no-ops
113    /// (already documented/expected behaviour), regardless of which test the
114    /// harness happens to schedule first.
115    /// What: Calls `init_tracing_for_test` twice; asserts no panic.
116    /// Test: This test.
117    #[test]
118    fn init_tracing_for_test_is_idempotent() {
119        crate::test_support::begin_capture();
120        init_tracing_for_test();
121        init_tracing_for_test(); // second call must not panic
122    }
123
124    /// The default log level constant is non-empty.
125    ///
126    /// Why: Guard against accidental empty string.
127    /// What: Asserts `DEFAULT_LOG_LEVEL` is non-empty.
128    /// Test: This test.
129    #[test]
130    fn default_log_level_is_non_empty() {
131        assert!(!DEFAULT_LOG_LEVEL.is_empty());
132    }
133}