Skip to main content

aft_base/
logging.rs

1//! Durable process logging and low-cost periodic performance summaries.
2//!
3//! Rust module processes use one file per PID. That avoids cross-process rename
4//! races while preserving a single greppable directory for all AFT activity.
5
6use crate::executor::{Executor, ExecutorContext};
7use crate::process_identity::is_process_alive;
8use crate::tool_progress::{ToolCallPhaseDurations, WaitingOn};
9use sha2::{Digest, Sha256};
10use std::cell::RefCell;
11use std::collections::{BTreeMap, HashMap, VecDeque};
12#[cfg(unix)]
13use std::fs::OpenOptions;
14use std::fs::{self, File};
15use std::io::{self, BufWriter, Write};
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
18use std::sync::mpsc::{self, SyncSender, TrySendError};
19use std::sync::{Arc, LazyLock, Mutex, OnceLock};
20use std::thread;
21use std::time::{Duration, Instant, SystemTime};
22
23mod stderr_mirror;
24
25static SUBC_LOGGING: AtomicBool = AtomicBool::new(false);
26static STDERR_MIRROR: OnceLock<stderr_mirror::Mirror> = OnceLock::new();
27static STDERR_MIRROR_HEALTH: LazyLock<Arc<stderr_mirror::MirrorHealth>> =
28    LazyLock::new(|| Arc::new(stderr_mirror::MirrorHealth::default()));
29
30/// Maximum size of an active Rust or plugin log before its single backup rotates in.
31const LOG_FILE_BYTES: u64 = 32 * 1024 * 1024;
32/// Keep one backup generation; retention is hygiene rather than a user setting.
33const LOG_GENERATIONS: usize = 1;
34/// Check the active file on every write so the cap is not exceeded by a burst.
35const ROTATION_CHECK_EVERY: u64 = 1;
36const LOG_CHANNEL_CAPACITY: usize = 4096;
37const LOG_WRITE_RETRY_MIN: Duration = Duration::from_secs(1);
38const LOG_WRITE_RETRY_MAX: Duration = Duration::from_secs(30);
39/// Do not reap a dead PID's file until it has been quiet for at least one day.
40const DEAD_PROCESS_LOG_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
41/// Limit the total regular-file footprint left in the log directory.
42const LOG_DIRECTORY_BUDGET_BYTES: u64 = 200 * 1024 * 1024;
43/// Maintenance ticks may call the sweep, but actual directory work is hourly.
44const LOG_SWEEP_INTERVAL: Duration = Duration::from_secs(60 * 60);
45const DEFAULT_PERF_TICK_INTERVAL: Duration = Duration::from_secs(60);
46const PERF_SAMPLE_INTERVAL: Duration = Duration::from_millis(250);
47#[rustfmt::skip]
48test_support_visibility! {
49pub(crate) const SLOW_TOOL_CALL_THRESHOLD: Duration = Duration::from_millis(50);
50}
51const TOOL_CALL_SAMPLE_CAPACITY: usize = 256;
52/// Census lines stay greppable and short; extra fields are dropped past this.
53const INDEX_EVENT_MAX_BYTES: usize = 300;
54/// Reserve independent space for the message and trace: a huge panic payload
55/// must not crowd every stack frame out of the diagnostic.
56const PANIC_MESSAGE_BYTES: usize = 4 * 1024;
57const PANIC_BACKTRACE_BYTES: usize = 24 * 1024;
58const PANIC_TRUNCATION: &str = "\n[panic diagnostic truncated]";
59
60/// Standing-index plane recorded on every `index_event` line.
61#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
62pub enum IndexPlane {
63    Callgraph,
64    Search,
65    Semantic,
66    Tier2,
67}
68
69impl IndexPlane {
70    pub(crate) fn as_str(self) -> &'static str {
71        match self {
72            Self::Callgraph => "callgraph",
73            Self::Search => "search",
74            Self::Semantic => "semantic",
75            Self::Tier2 => "tier2",
76        }
77    }
78}
79
80/// Lifecycle kind recorded on every `index_event` line.
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum IndexEventKind {
83    BuildStarted,
84    BuildProgress,
85    BuildReady,
86    BuildSuperseded,
87    #[allow(dead_code)]
88    BuildCancelled,
89    BuildFailed,
90    FirstQuery,
91}
92
93impl IndexEventKind {
94    pub(crate) fn as_str(self) -> &'static str {
95        match self {
96            Self::BuildStarted => "build_started",
97            Self::BuildProgress => "build_progress",
98            Self::BuildReady => "build_ready",
99            Self::BuildSuperseded => "build_superseded",
100            Self::BuildCancelled => "build_cancelled",
101            Self::BuildFailed => "build_failed",
102            Self::FirstQuery => "first_query",
103        }
104    }
105
106    fn is_terminal(self) -> bool {
107        matches!(
108            self,
109            Self::BuildReady | Self::BuildSuperseded | Self::BuildCancelled | Self::BuildFailed
110        )
111    }
112}
113
114/// One structured standing-index lifecycle record.
115#[derive(Clone, Debug)]
116pub struct IndexEvent {
117    pub kind: IndexEventKind,
118    pub plane: IndexPlane,
119    pub build_id: String,
120    pub root: PathBuf,
121    pub key: String,
122    extra: Vec<(&'static str, String)>,
123}
124
125impl IndexEvent {
126    pub(crate) fn new(
127        kind: IndexEventKind,
128        plane: IndexPlane,
129        build_id: impl Into<String>,
130        root: impl AsRef<Path>,
131        key: impl Into<String>,
132    ) -> Self {
133        Self {
134            kind,
135            plane,
136            build_id: build_id.into(),
137            root: root.as_ref().to_path_buf(),
138            key: key.into(),
139            extra: Vec::new(),
140        }
141    }
142
143    pub fn from_scope(kind: IndexEventKind, scope: &IndexBuildScope) -> Self {
144        Self::new(
145            kind,
146            scope.plane,
147            scope.build_id.clone(),
148            &scope.root,
149            scope.key.clone(),
150        )
151    }
152
153    pub fn field(mut self, key: &'static str, value: impl ToString) -> Self {
154        self.extra.push((key, value.to_string()));
155        self
156    }
157}
158
159/// Identity of one in-flight build attempt, carried on a thread-local so nested
160/// helpers such as `ensure_cold_build_current` can emit without extra params.
161#[derive(Clone, Debug)]
162pub struct IndexBuildScope {
163    pub plane: IndexPlane,
164    pub build_id: String,
165    pub root: PathBuf,
166    pub key: String,
167    pub started_at: Instant,
168}
169
170impl IndexBuildScope {
171    pub fn new(plane: IndexPlane, root: impl AsRef<Path>, key: impl Into<String>) -> Self {
172        Self {
173            plane,
174            build_id: mint_index_build_id(),
175            root: root.as_ref().to_path_buf(),
176            key: key.into(),
177            started_at: Instant::now(),
178        }
179    }
180
181    pub fn elapsed_ms(&self) -> u64 {
182        self.started_at.elapsed().as_millis().min(u64::MAX as u128) as u64
183    }
184}
185
186struct InFlightBuild {
187    build_id: String,
188}
189
190struct UnclaimedReady {
191    build_id: String,
192    key: String,
193    ready_at: Instant,
194}
195
196#[derive(Default)]
197struct IndexLifecycle {
198    in_flight: Mutex<HashMap<(String, IndexPlane), InFlightBuild>>,
199    unclaimed: Mutex<HashMap<(String, IndexPlane), UnclaimedReady>>,
200}
201
202#[derive(Default)]
203struct IndexBuildStartSignals {
204    sequence: u64,
205    last_by_root_plane: HashMap<(String, IndexPlane), u64>,
206    in_flight_by_root_plane: HashMap<(String, IndexPlane), u64>,
207    waiters: HashMap<(String, IndexPlane), Vec<(u64, crossbeam_channel::Sender<()>)>>,
208}
209
210struct ToolCallWaitState {
211    waiting_on: WaitingOn,
212    waiting_on_build_id: Option<String>,
213    wait_ms: u64,
214    queue_ms: u64,
215}
216
217impl Default for ToolCallWaitState {
218    fn default() -> Self {
219        Self {
220            waiting_on: WaitingOn::None,
221            waiting_on_build_id: None,
222            wait_ms: 0,
223            queue_ms: 0,
224        }
225    }
226}
227
228static INDEX_BUILD_COUNTER: AtomicU64 = AtomicU64::new(1);
229static INDEX_LIFECYCLE: LazyLock<IndexLifecycle> = LazyLock::new(IndexLifecycle::default);
230static INDEX_BUILD_START_SIGNALS: LazyLock<Mutex<IndexBuildStartSignals>> =
231    LazyLock::new(|| Mutex::new(IndexBuildStartSignals::default()));
232
233thread_local! {
234    static CURRENT_INDEX_BUILD: RefCell<Option<IndexBuildScope>> = const { RefCell::new(None) };
235    static TOOL_CALL_WAIT: RefCell<ToolCallWaitState> = const {
236        RefCell::new(ToolCallWaitState {
237            waiting_on: WaitingOn::None,
238            waiting_on_build_id: None,
239            wait_ms: 0,
240            queue_ms: 0,
241        })
242    };
243}
244
245#[cfg(any(test, feature = "test-support"))]
246static INDEX_EVENT_CAPTURE: LazyLock<Mutex<Option<Vec<String>>>> =
247    LazyLock::new(|| Mutex::new(None));
248#[cfg(any(test, feature = "test-support"))]
249static INDEX_EVENT_CAPTURE_LOCK: Mutex<()> = Mutex::new(());
250
251#[cfg(any(test, feature = "test-support"))]
252thread_local! {
253    static LOG_LINE_CAPTURE: RefCell<Option<Arc<Mutex<Vec<String>>>>> = const { RefCell::new(None) };
254}
255
256#[cfg(any(test, feature = "test-support"))]
257pub fn capture_log_lines<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
258    let capture = Arc::new(Mutex::new(Vec::new()));
259    let result = capture_log_lines_into(capture.clone(), f);
260    let lines = capture.lock().unwrap().clone();
261    (result, lines)
262}
263
264/// Share a worker thread's captured records with the test while it is running.
265#[cfg(any(test, feature = "test-support"))]
266pub fn capture_log_lines_into<R>(capture: Arc<Mutex<Vec<String>>>, f: impl FnOnce() -> R) -> R {
267    // Keep the test representative of a libtest process where another test
268    // may already have installed the global logger.
269    let _ = env_logger::builder().is_test(true).try_init();
270    let previous = LOG_LINE_CAPTURE.with(|slot| slot.replace(Some(capture)));
271    let result = f();
272    LOG_LINE_CAPTURE.with(|slot| slot.replace(previous));
273    result
274}
275
276#[cfg(any(test, feature = "test-support"))]
277fn capture_log_line(level: log::Level, line: &str) {
278    LOG_LINE_CAPTURE.with(|slot| {
279        if let Some(lines) = slot.borrow().as_ref() {
280            lines.lock().unwrap().push(format!("{level} {line}"));
281        }
282    });
283}
284
285/// Whether this thread is collecting slog records for a unit test.
286#[doc(hidden)]
287#[cfg(any(test, feature = "test-support"))]
288#[inline]
289pub fn capture_active() -> bool {
290    LOG_LINE_CAPTURE.with(|slot| slot.borrow().is_some())
291}
292
293/// Production builds never capture log lines in memory.
294#[doc(hidden)]
295#[cfg(not(any(test, feature = "test-support")))]
296#[inline]
297pub fn capture_active() -> bool {
298    false
299}
300
301// Keep the session-log filters people set against AFT working across crate boundaries.
302fn canonical_slog_target(target: &str) -> std::borrow::Cow<'_, str> {
303    match target.split_once("::") {
304        Some(("aft_base" | "aft_db" | "aft_parse", module)) => format!("aft::{module}").into(),
305        _ => target.into(),
306    }
307}
308
309#[doc(hidden)]
310#[inline]
311pub fn slog_info_enabled(target: &'static str) -> bool {
312    log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Info)
313        || capture_active()
314}
315
316#[doc(hidden)]
317#[inline]
318pub fn slog_warn_enabled(target: &'static str) -> bool {
319    log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Warn)
320        || capture_active()
321}
322
323#[doc(hidden)]
324#[inline]
325pub fn slog_error_enabled(target: &'static str) -> bool {
326    log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Error)
327        || capture_active()
328}
329
330#[doc(hidden)]
331#[inline]
332pub fn slog_debug_enabled(target: &'static str) -> bool {
333    log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Debug)
334        || capture_active()
335}
336
337// Exported slog macros expand outside this module, so their entry points must
338// be public even though callers should use the macros instead.
339#[doc(hidden)]
340pub fn emit_slog_info(target: &'static str, message: String) {
341    emit_slog(target, log::Level::Info, message);
342}
343
344#[doc(hidden)]
345pub fn emit_slog_warn(target: &'static str, message: String) {
346    emit_slog(target, log::Level::Warn, message);
347}
348
349#[doc(hidden)]
350pub fn emit_slog_error(target: &'static str, message: String) {
351    emit_slog(target, log::Level::Error, message);
352}
353
354#[doc(hidden)]
355pub fn emit_slog_debug(target: &'static str, message: String) {
356    emit_slog(target, log::Level::Debug, message);
357}
358
359fn emit_slog(target: &'static str, level: log::Level, message: String) {
360    #[cfg(any(test, feature = "test-support"))]
361    capture_log_line(level, &message);
362    log::log!(target: canonical_slog_target(target).as_ref(), level, "{message}");
363}
364
365/// Mint a stable per-attempt id (`b-<pid>-<n>`) at `build_started`.
366pub(crate) fn mint_index_build_id() -> String {
367    let n = INDEX_BUILD_COUNTER.fetch_add(1, Ordering::Relaxed);
368    format!("b-{}-{n}", std::process::id())
369}
370
371/// RAII install of the current index-build attempt on this thread.
372pub struct IndexBuildGuard {
373    previous: Option<IndexBuildScope>,
374}
375
376impl Drop for IndexBuildGuard {
377    fn drop(&mut self) {
378        CURRENT_INDEX_BUILD.with(|slot| {
379            *slot.borrow_mut() = self.previous.take();
380        });
381    }
382}
383
384/// Install `scope` as the current index-build attempt until the guard drops.
385pub fn install_index_build(scope: IndexBuildScope) -> IndexBuildGuard {
386    let previous = CURRENT_INDEX_BUILD.with(|slot| slot.replace(Some(scope)));
387    IndexBuildGuard { previous }
388}
389
390/// Emits `build_failed` if the attempt returns without a terminal event.
391pub struct IndexBuildFailureGuard {
392    armed: bool,
393}
394
395impl IndexBuildFailureGuard {
396    pub fn new() -> Self {
397        Self { armed: true }
398    }
399
400    pub fn disarm(&mut self) {
401        self.armed = false;
402    }
403}
404
405impl Drop for IndexBuildFailureGuard {
406    fn drop(&mut self) {
407        if !self.armed {
408            return;
409        }
410        let Some(scope) = current_index_build() else {
411            return;
412        };
413        // A prior terminal event already cleared the in-flight slot.
414        if in_flight_build_id(scope.plane, &scope.root).as_deref() != Some(scope.build_id.as_str())
415        {
416            return;
417        }
418        log_current_index_event(
419            IndexEventKind::BuildFailed,
420            &[("reason", "error".to_string())],
421        );
422    }
423}
424
425pub fn current_index_build() -> Option<IndexBuildScope> {
426    CURRENT_INDEX_BUILD.with(|slot| slot.borrow().clone())
427}
428
429/// Normalize a project root for `index_event` (`\` → `/`).
430pub fn normalize_index_root(root: &Path) -> String {
431    root.to_string_lossy().replace('\\', "/")
432}
433
434fn sanitize_index_value(value: &str) -> String {
435    let mut out = String::with_capacity(value.len().max(1));
436    for ch in value.chars() {
437        match ch {
438            ' ' | '\t' | '\n' | '\r' | '=' => out.push('_'),
439            '\\' => out.push('/'),
440            c if c.is_ascii_graphic() || c == '/' => out.push(c),
441            _ => out.push('_'),
442        }
443    }
444    if out.is_empty() {
445        out.push('-');
446    }
447    out
448}
449
450fn push_index_field(line: &mut String, key: &str, value: &str, max_bytes: usize) {
451    let sanitized = sanitize_index_value(value);
452    let addition = format!(" {key}={sanitized}");
453    if line.len() + addition.len() > max_bytes {
454        return;
455    }
456    line.push_str(&addition);
457}
458
459/// Keep the last two components when possible, with a stable hash to distinguish worktrees.
460fn left_truncate_root(root: &str, max_bytes: usize) -> String {
461    if root.len() <= max_bytes {
462        return root.to_string();
463    }
464    let hash = format!("{:x}", Sha256::digest(root.as_bytes()));
465    let marker = format!(".../{}", &hash[..8]);
466    if max_bytes <= marker.len() {
467        return marker[..max_bytes].to_string();
468    }
469    let root = root.trim_end_matches('/');
470    let suffix_start = root.rmatch_indices('/').nth(1).map_or(0, |(i, _)| i + 1);
471    let keep = max_bytes.saturating_sub(marker.len() + 1);
472    let mut start = suffix_start.max(root.len().saturating_sub(keep));
473    while start < root.len() && !root.is_char_boundary(start) {
474        start += 1;
475    }
476    if start == root.len() {
477        marker
478    } else {
479        format!("{marker}/{}", &root[start..])
480    }
481}
482
483fn format_index_event_line(event: &IndexEvent) -> String {
484    let kind = sanitize_index_value(event.kind.as_str());
485    let plane = sanitize_index_value(event.plane.as_str());
486    let build_id = sanitize_index_value(&event.build_id);
487    let key = sanitize_index_value(&event.key);
488    let mut root = sanitize_index_value(&normalize_index_root(&event.root));
489    let prefix = format!("index_event kind={kind} plane={plane} build_id={build_id} root=");
490    let key_field = format!(" key={key}");
491    // Reserve measurements before descriptive fields, and give the root only the
492    // remaining bytes. Keep root/key in their current positions so existing readers
493    // can parse the record.
494    let extra_budget = INDEX_EVENT_MAX_BYTES
495        .saturating_sub(prefix.len() + key_field.len())
496        .saturating_sub(root.len().min(".../00000000".len()));
497    let mut extra_fields = String::new();
498    for numeric in [true, false] {
499        for (key, value) in &event.extra {
500            if value.parse::<u64>().is_ok() == numeric {
501                push_index_field(&mut extra_fields, key, value, extra_budget);
502            }
503        }
504    }
505    let root_budget = INDEX_EVENT_MAX_BYTES
506        .saturating_sub(prefix.len())
507        .saturating_sub(key_field.len())
508        .saturating_sub(extra_fields.len());
509    if root.len() > root_budget {
510        root = left_truncate_root(&root, root_budget);
511    }
512    format!("{prefix}{root}{key_field}{extra_fields}")
513}
514
515fn root_plane_key(root: &Path, plane: IndexPlane) -> (String, IndexPlane) {
516    (normalize_index_root(root), plane)
517}
518
519fn remember_in_flight(event: &IndexEvent) {
520    let key = root_plane_key(&event.root, event.plane);
521    if event.kind == IndexEventKind::BuildStarted {
522        if let Ok(mut signals) = INDEX_BUILD_START_SIGNALS.lock() {
523            signals.sequence = signals.sequence.wrapping_add(1);
524            let sequence = signals.sequence;
525            signals.last_by_root_plane.insert(key.clone(), sequence);
526            signals
527                .in_flight_by_root_plane
528                .insert(key.clone(), sequence);
529            if let Some(waiters) = signals.waiters.remove(&key) {
530                for (baseline, sender) in waiters {
531                    if sequence > baseline {
532                        let _ = sender.send(());
533                    }
534                }
535            }
536        }
537        if let Ok(mut in_flight) = INDEX_LIFECYCLE.in_flight.lock() {
538            in_flight.insert(
539                key,
540                InFlightBuild {
541                    build_id: event.build_id.clone(),
542                },
543            );
544        }
545        return;
546    }
547    if event.kind.is_terminal() {
548        if let Ok(mut in_flight) = INDEX_LIFECYCLE.in_flight.lock() {
549            in_flight.remove(&key);
550        }
551        if let Ok(mut signals) = INDEX_BUILD_START_SIGNALS.lock() {
552            signals.in_flight_by_root_plane.remove(&key);
553        }
554        release_index_build_start_waiters(event.plane, &event.root);
555    }
556    if event.kind == IndexEventKind::BuildReady {
557        if let Ok(mut unclaimed) = INDEX_LIFECYCLE.unclaimed.lock() {
558            unclaimed.insert(
559                key,
560                UnclaimedReady {
561                    build_id: event.build_id.clone(),
562                    key: event.key.clone(),
563                    ready_at: Instant::now(),
564                },
565            );
566        }
567    }
568}
569
570fn emit_index_event_line(line: String) {
571    #[cfg(any(test, feature = "test-support"))]
572    if let Ok(mut slot) = INDEX_EVENT_CAPTURE.lock() {
573        if let Some(events) = slot.as_mut() {
574            events.push(line.clone());
575        }
576    }
577    crate::slog_info!("{}", line);
578}
579
580/// Write one greppable `index_event` info line through the house slog path.
581pub fn log_index_event(event: IndexEvent) {
582    remember_in_flight(&event);
583    emit_index_event_line(format_index_event_line(&event));
584}
585
586pub fn log_watcher_rescan(
587    root: &Path,
588    reason: RescanReason,
589    cost_ms: u64,
590    rss_delta_bytes: Option<i64>,
591    raw_events_since_last: u64,
592) {
593    let reason = sanitize_index_value(reason.as_str());
594    let rss_delta = rss_delta_bytes
595        .map(|delta| delta.to_string())
596        .unwrap_or_else(|| "unavailable".to_string());
597    let prefix = "index_event kind=watcher_rescan plane=watcher root=";
598    let suffix = format!(
599        " reason={reason} cost_ms={cost_ms} rss_delta_bytes={rss_delta} raw_events_since_last={raw_events_since_last}"
600    );
601    let mut root = sanitize_index_value(&normalize_index_root(root));
602    let root_budget = INDEX_EVENT_MAX_BYTES
603        .saturating_sub(prefix.len())
604        .saturating_sub(suffix.len());
605    if root.len() > root_budget {
606        root = left_truncate_root(&root, root_budget);
607    }
608    emit_index_event_line(format!("{prefix}{root}{suffix}"));
609}
610
611/// Emit an event for the current thread's index-build scope, if any.
612pub(crate) fn log_current_index_event(kind: IndexEventKind, extra: &[(&'static str, String)]) {
613    let Some(scope) = current_index_build() else {
614        return;
615    };
616    let mut event = IndexEvent::from_scope(kind, &scope);
617    for (key, value) in extra {
618        event.extra.push((key, value.clone()));
619    }
620    log_index_event(event);
621}
622
623/// Release start waiters when a build attempt ends before emitting `build_started`.
624pub fn release_index_build_start_waiters(plane: IndexPlane, root: &Path) {
625    let waiters = INDEX_BUILD_START_SIGNALS
626        .lock()
627        .ok()
628        .and_then(|mut signals| signals.waiters.remove(&root_plane_key(root, plane)))
629        .unwrap_or_default();
630    for (_, sender) in waiters {
631        let _ = sender.send(());
632    }
633}
634
635/// In-flight `build_id` for a root/plane, if a cold build has started and not yet terminated.
636pub(crate) fn in_flight_build_id(plane: IndexPlane, root: &Path) -> Option<String> {
637    INDEX_LIFECYCLE
638        .in_flight
639        .lock()
640        .ok()?
641        .get(&root_plane_key(root, plane))
642        .map(|build| build.build_id.clone())
643}
644
645/// Consume the per-root unclaimed ready slot for `plane` and emit `first_query` once.
646pub(crate) fn claim_first_query(
647    plane: IndexPlane,
648    root: &Path,
649    tool: &str,
650    queue_ms: u64,
651    service_ms: u64,
652    status: &str,
653) -> bool {
654    let slot = {
655        let Ok(mut unclaimed) = INDEX_LIFECYCLE.unclaimed.lock() else {
656            return false;
657        };
658        unclaimed.remove(&root_plane_key(root, plane))
659    };
660    let Some(slot) = slot else {
661        return false;
662    };
663    let ready_to_first_query_ms = slot.ready_at.elapsed().as_millis().min(u64::MAX as u128) as u64;
664    log_index_event(
665        IndexEvent::new(
666            IndexEventKind::FirstQuery,
667            plane,
668            slot.build_id,
669            root,
670            slot.key,
671        )
672        .field("tool", tool)
673        .field("queue_ms", queue_ms)
674        .field("service_ms", service_ms)
675        .field("status", status)
676        .field("ready_to_first_query_ms", ready_to_first_query_ms),
677    );
678    true
679}
680
681/// Query-path helper: claim `first_query` on a ready plane, or attribute a Building wait.
682pub fn note_index_query(plane: IndexPlane, root: &Path, tool: &str, service_ms: u64, status: &str) {
683    match status {
684        "building" | "rebuilding" => {
685            let build_id = in_flight_build_id(plane, root);
686            note_tool_call_wait(WaitingOn::Build, build_id.as_deref(), 0);
687        }
688        _ => {
689            let queue_ms = TOOL_CALL_WAIT.with(|slot| slot.borrow().queue_ms);
690            claim_first_query(plane, root, tool, queue_ms, service_ms, status);
691        }
692    }
693}
694
695/// Reset causal-wait state on the executor worker at job admission.
696pub fn reset_tool_call_wait() {
697    TOOL_CALL_WAIT.with(|slot| *slot.borrow_mut() = ToolCallWaitState::default());
698}
699
700#[rustfmt::skip]
701test_support_visibility! {
702
703/// Record what the current tool-call thread waited on.
704pub(crate) fn note_tool_call_wait(waiting_on: WaitingOn, build_id: Option<&str>, wait_ms: u64) {
705    TOOL_CALL_WAIT.with(|slot| {
706        let mut state = slot.borrow_mut();
707        state.waiting_on = waiting_on;
708        state.waiting_on_build_id = build_id.map(str::to_string);
709        state.wait_ms = state.wait_ms.saturating_add(wait_ms);
710    });
711}
712}
713
714pub fn note_tool_call_queue_ms(queue_ms: u64) {
715    TOOL_CALL_WAIT.with(|slot| slot.borrow_mut().queue_ms = queue_ms);
716}
717
718pub fn take_tool_call_wait() -> (WaitingOn, Option<String>, u64) {
719    TOOL_CALL_WAIT.with(|slot| {
720        let state = std::mem::take(&mut *slot.borrow_mut());
721        (state.waiting_on, state.waiting_on_build_id, state.wait_ms)
722    })
723}
724
725/// A step of the shared edit pipeline whose time a slow tool call reports.
726#[derive(Clone, Copy, Debug, Eq, PartialEq)]
727pub enum EditPhase {
728    /// Writing the undo snapshot under the backup store's lock.
729    Backup,
730    /// Atomic writes of the new content (and of a rollback).
731    Write,
732    /// The project formatter.
733    Format,
734    /// Tree-sitter syntax checks before and after the write.
735    Syntax,
736    /// The opt-in full type check.
737    Validate,
738    /// Line diffs for the reply's counts and the host's patch.
739    Diff,
740    /// Language-server notification and the optional diagnostics wait.
741    Lsp,
742}
743
744impl EditPhase {
745    const ALL: [EditPhase; 7] = [
746        EditPhase::Backup,
747        EditPhase::Write,
748        EditPhase::Format,
749        EditPhase::Syntax,
750        EditPhase::Validate,
751        EditPhase::Diff,
752        EditPhase::Lsp,
753    ];
754
755    fn as_str(self) -> &'static str {
756        match self {
757            EditPhase::Backup => "backup",
758            EditPhase::Write => "write",
759            EditPhase::Format => "format",
760            EditPhase::Syntax => "syntax",
761            EditPhase::Validate => "validate",
762            EditPhase::Diff => "diff",
763            EditPhase::Lsp => "lsp",
764        }
765    }
766
767    fn index(self) -> usize {
768        self as usize
769    }
770}
771
772/// Time spent in each [`EditPhase`] by the current tool call's thread.
773struct EditPhaseTimes {
774    elapsed: [Duration; 7],
775    /// Open timers per phase, so a timed helper called from another timed
776    /// helper of the same phase is counted once.
777    depth: [u8; 7],
778    touched: bool,
779}
780
781thread_local! {
782    static EDIT_PHASES: RefCell<EditPhaseTimes> = const {
783        RefCell::new(EditPhaseTimes {
784            elapsed: [Duration::ZERO; 7],
785            depth: [0; 7],
786            touched: false,
787        })
788    };
789}
790
791/// Adds the time until it is dropped to one [`EditPhase`] of this thread's
792/// tool call. Only the outermost open timer of a phase counts.
793pub struct EditPhaseTimer {
794    phase: EditPhase,
795    started: Instant,
796}
797
798/// Start timing `phase` on this thread; see [`EditPhaseTimer`].
799pub fn time_edit_phase(phase: EditPhase) -> EditPhaseTimer {
800    EDIT_PHASES.with(|slot| {
801        let mut times = slot.borrow_mut();
802        times.depth[phase.index()] = times.depth[phase.index()].saturating_add(1);
803    });
804    EditPhaseTimer {
805        phase,
806        started: Instant::now(),
807    }
808}
809
810impl Drop for EditPhaseTimer {
811    fn drop(&mut self) {
812        let elapsed = self.started.elapsed();
813        EDIT_PHASES.with(|slot| {
814            let mut times = slot.borrow_mut();
815            let index = self.phase.index();
816            times.depth[index] = times.depth[index].saturating_sub(1);
817            if times.depth[index] == 0 {
818                times.elapsed[index] += elapsed;
819                times.touched = true;
820            }
821        });
822    }
823}
824
825/// Clear this thread's edit phase times at the start of a tool call.
826pub fn reset_edit_phase_times() {
827    EDIT_PHASES.with(|slot| {
828        let mut times = slot.borrow_mut();
829        times.elapsed = [Duration::ZERO; 7];
830        times.touched = false;
831    });
832}
833
834/// This thread's edit phase times since the last reset, rendered as
835/// `backup:1,write:0,format:0,syntax:12,validate:0,diff:3,lsp:0` (whole
836/// milliseconds), or `None` when the call ran no edit step. Clears them.
837pub fn take_edit_phase_times() -> Option<String> {
838    EDIT_PHASES.with(|slot| {
839        let mut times = slot.borrow_mut();
840        if !times.touched {
841            return None;
842        }
843        let rendered = EditPhase::ALL
844            .iter()
845            .map(|phase| {
846                format!(
847                    "{}:{}",
848                    phase.as_str(),
849                    duration_millis_u64(times.elapsed[phase.index()])
850                )
851            })
852            .collect::<Vec<_>>()
853            .join(",");
854        times.elapsed = [Duration::ZERO; 7];
855        times.touched = false;
856        Some(rendered)
857    })
858}
859
860#[cfg(any(test, feature = "test-support"))]
861pub fn capture_index_events<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
862    let _serial = INDEX_EVENT_CAPTURE_LOCK
863        .lock()
864        .unwrap_or_else(std::sync::PoisonError::into_inner);
865    if let Ok(mut slot) = INDEX_EVENT_CAPTURE.lock() {
866        *slot = Some(Vec::new());
867    }
868    let result = f();
869    let events = INDEX_EVENT_CAPTURE
870        .lock()
871        .ok()
872        .and_then(|mut slot| slot.take())
873        .unwrap_or_default();
874    (result, events)
875}
876
877/// Initialize the `RUST_LOG`-filtered stderr logger and its additive file sink.
878pub fn init() {
879    init_with_stderr_mode(false);
880}
881
882/// Initialize logging before the supervised module starts its frame runtime.
883/// Stderr is a bounded best-effort mirror; the independent file sink is unchanged.
884pub fn init_subc() {
885    init_with_stderr_mode(true);
886}
887
888fn init_with_stderr_mode(subc: bool) {
889    SUBC_LOGGING.store(subc, Ordering::Relaxed);
890    if subc {
891        STDERR_MIRROR.get_or_init(|| {
892            stderr_mirror::Mirror::spawn(
893                io::stderr(),
894                stderr_mirror::QUEUE_CAPACITY,
895                Arc::clone(&STDERR_MIRROR_HEALTH),
896            )
897            .map(|(mirror, _worker)| mirror)
898            .unwrap_or_else(|_| stderr_mirror::Mirror::disabled(Arc::clone(&STDERR_MIRROR_HEALTH)))
899        });
900    }
901    let storage_root = crate::storage_path::storage_dir(None);
902    let logs_dir = storage_root.join("logs");
903    let file_name = format!("aft-{}.log", std::process::id());
904    let file_path = logs_dir.join(file_name);
905    let (sink, startup_sweep) =
906        initial_file_sink(&logs_dir, &file_path, Arc::clone(&LOG_WRITE_HEALTH));
907    let (tx, rx) = mpsc::sync_channel(LOG_CHANNEL_CAPACITY);
908    let sink = Arc::new(Mutex::new(Some(sink)));
909    let worker_sink = Arc::clone(&sink);
910    let file_tx = thread::Builder::new()
911        .name("aft-log-writer".to_string())
912        .spawn(move || {
913            run_file_writer(
914                worker_sink,
915                rx,
916                Arc::clone(&LOG_WRITE_HEALTH),
917                LOG_WRITE_RETRY_MIN,
918            )
919        })
920        .map(|_| {
921            if let Ok(mut control) = FILE_CONTROL.lock() {
922                control.tx = Some(tx.clone());
923                control.sink = Some(sink);
924                control.storage_root = Some(storage_root.clone());
925            }
926            Some(tx)
927        })
928        .unwrap_or_else(|error| {
929            write_stderr_once(&format!(
930                "[aft] WARN durable log disabled: cannot start writer thread: {error}\n"
931            ));
932            None
933        });
934
935    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
936        .target(env_logger::Target::Pipe(Box::new(TeeWriter::new(file_tx))))
937        .format(|buf, record| {
938            // Wall-clock stamp so post-hoc log forensics can correlate
939            // lines with external events (health probes, module bounces).
940            // Seconds precision is enough; chrono is avoided on purpose —
941            // this hand-rolls UTC from the epoch to keep deps flat.
942            write_log_line(
943                buf,
944                &format_utc_timestamp(),
945                record.level(),
946                record.target(),
947                record.args(),
948            )
949        })
950        .init();
951
952    install_panic_hook(file_path);
953
954    if let Some(summary) = startup_sweep {
955        log_sweep_summary(summary);
956    }
957}
958
959#[cfg(any(test, feature = "test-support"))]
960pub fn subc_stderr_tee_for_test() -> impl Write + Send {
961    TeeWriter::new(None)
962}
963
964/// Log before delegating to the previous hook. Do not change RUST_BACKTRACE:
965/// stderr retains the default hook's normal short/full/disabled behavior while
966/// the durable diagnostic always includes the stack needed after a respawn.
967fn install_panic_hook(initial_path: PathBuf) {
968    let previous = std::panic::take_hook();
969    std::panic::set_hook(Box::new(move |info| {
970        let message = bounded_panic_text(format_args!("{info}"), PANIC_MESSAGE_BYTES);
971        let trace = std::backtrace::Backtrace::force_capture();
972        let trace = bounded_panic_text(format_args!("{trace}"), PANIC_BACKTRACE_BYTES);
973        let report = crate::log_redact::aft_redact_bytes(
974            format!(
975                "{} [aft] ERROR panic {message}\nforced backtrace:\n{trace}\n",
976                format_utc_timestamp()
977            )
978            .as_bytes(),
979        )
980        .into_owned();
981        // Never enter env_logger or wait on the file writer from its panic
982        // hook: the panicking thread may already hold either logger lock.
983        let path = FILE_CONTROL
984            .try_lock()
985            .ok()
986            .and_then(|control| control.storage_root.clone())
987            .map(|root| {
988                root.join("logs")
989                    .join(format!("aft-{}.log", std::process::id()))
990            })
991            .unwrap_or_else(|| initial_path.clone());
992        let persisted = open_private_log_file(&path, false).and_then(|mut file| {
993            file.write_all(&report)?;
994            // Panic hooks must not enter the logger or its warning-set lock.
995            aft_store::sync::sync_all_in_panic(&file, &path)
996        });
997        if persisted.is_err() {
998            let _ = io::stderr().write_all(&report);
999        }
1000        previous(info);
1001    }));
1002}
1003
1004/// The process log follows storage-root reconfiguration, not a caller's project.
1005pub fn daemon_log_path() -> PathBuf {
1006    let root = FILE_CONTROL
1007        .lock()
1008        .unwrap_or_else(std::sync::PoisonError::into_inner)
1009        .storage_root
1010        .clone()
1011        .unwrap_or_else(|| crate::storage_path::storage_dir(None));
1012    root.join("logs")
1013        .join(format!("aft-{}.log", std::process::id()))
1014}
1015
1016/// Best-effort watchdog evidence, independent of the logger and writer locks.
1017/// Reopen for each line so normal log rotation does not strand later evidence
1018/// on a renamed file. The caller must write its guaranteed stderr copy first.
1019pub fn write_watchdog_line(path: &Path, message: &str) -> io::Result<()> {
1020    let mut line = Vec::new();
1021    write_log_line(
1022        &mut line,
1023        &format_utc_timestamp(),
1024        log::Level::Warn,
1025        "aft::subc::stall_watchdog",
1026        &format_args!("{message}"),
1027    )?;
1028    open_private_log_file(path, false)?.write_all(&crate::log_redact::aft_redact_bytes(&line))
1029}
1030
1031/// The standalone gh shim runs before logger initialization. Preserve its rare
1032/// authority diagnostics in the process log without adding agent-visible stderr.
1033pub fn write_preinit_warning(message: &str) -> io::Result<()> {
1034    write_preinit_warning_to(&daemon_log_path(), message)
1035}
1036
1037fn write_preinit_warning_to(path: &Path, message: &str) -> io::Result<()> {
1038    if let Some(parent) = path.parent() {
1039        create_private_log_dir(parent)?;
1040    }
1041    let mut line = Vec::new();
1042    write_log_line(
1043        &mut line,
1044        &format_utc_timestamp(),
1045        log::Level::Warn,
1046        "aft::gh_shim_speech",
1047        &format_args!("{message}"),
1048    )?;
1049    let mut file = open_private_log_file(path, false)?;
1050    file.write_all(&crate::log_redact::aft_redact_bytes(&line))?;
1051    aft_store::sync::sync_all(&file, path)
1052}
1053
1054fn bounded_panic_text(args: std::fmt::Arguments<'_>, max_bytes: usize) -> String {
1055    use std::fmt::Write;
1056
1057    let mut text = PanicText {
1058        text: String::new(),
1059        budget: max_bytes.saturating_sub(PANIC_TRUNCATION.len()),
1060        truncated: false,
1061    };
1062    let _ = text.write_fmt(args);
1063    if text.truncated {
1064        text.text.push_str(PANIC_TRUNCATION);
1065    }
1066    text.text
1067}
1068
1069struct PanicText {
1070    text: String,
1071    budget: usize,
1072    truncated: bool,
1073}
1074
1075impl std::fmt::Write for PanicText {
1076    fn write_str(&mut self, value: &str) -> std::fmt::Result {
1077        let remaining = self.budget.saturating_sub(self.text.len());
1078        let mut end = value.len().min(remaining);
1079        while !value.is_char_boundary(end) {
1080            end -= 1;
1081        }
1082        self.text.push_str(&value[..end]);
1083        self.truncated |= end != value.len();
1084        Ok(())
1085    }
1086}
1087
1088/// Write one log line in the shared format used by both the stderr copy and
1089/// the durable file copy (`TeeWriter` receives these exact bytes):
1090/// `<timestamp> [aft] LEVEL <message>`.
1091///
1092/// The level sits after the `[aft]`/`[aft-lsp]` tag rather than before it so
1093/// every existing reader that anchors on `<timestamp> [aft]` (the health
1094/// sentinel's CLI-line filter, the plugins' stderr relay tag check, ad-hoc
1095/// greps) keeps matching, while `grep ' WARN '` or `' ERROR '` now works.
1096fn write_log_line<W: Write + ?Sized>(
1097    out: &mut W,
1098    timestamp: &str,
1099    level: log::Level,
1100    target: &str,
1101    message: &std::fmt::Arguments<'_>,
1102) -> io::Result<()> {
1103    let prefix = if target.starts_with("aft::lsp") || target.starts_with("aft_lsp") {
1104        "[aft-lsp]"
1105    } else {
1106        "[aft]"
1107    };
1108    writeln!(out, "{timestamp} {prefix} {level} {message}")
1109}
1110
1111/// Render `now` as `YYYY-MM-DDTHH:MM:SSZ` without a date-time dependency.
1112///
1113/// Civil-date math uses the days-from-epoch algorithm (Howard Hinnant's
1114/// `civil_from_days`); u64 seconds keep it valid far past 2100.
1115fn format_utc_timestamp() -> String {
1116    let since_epoch = SystemTime::now()
1117        .duration_since(SystemTime::UNIX_EPOCH)
1118        .unwrap_or_default();
1119    let seconds = format_epoch_secs(since_epoch.as_secs());
1120    format!(
1121        "{}.{:03}Z",
1122        seconds.trim_end_matches('Z'),
1123        since_epoch.subsec_millis()
1124    )
1125}
1126
1127fn format_epoch_secs(secs: u64) -> String {
1128    let (days, rem) = (secs / 86_400, secs % 86_400);
1129    let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
1130    // Howard Hinnant's civil_from_days: adding 719,468 shifts Unix epoch day 0
1131    // into the algorithm's era, which begins on 0000-03-01 (putting the leap
1132    // day last in each year simplifies the month/day arithmetic below).
1133    let z = days as i64 + 719_468;
1134    let era = z.div_euclid(146_097);
1135    let doe = z.rem_euclid(146_097);
1136    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1137    let y = yoe + era * 400;
1138    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1139    let mp = (5 * doy + 2) / 153;
1140    let d = doy - (153 * mp + 2) / 5 + 1;
1141    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1142    let y = if m <= 2 { y + 1 } else { y };
1143    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
1144}
1145
1146fn prepare_file_sink(
1147    logs_dir: &Path,
1148    file_path: &Path,
1149) -> io::Result<(RotatingFile, SweepSummary)> {
1150    create_private_log_dir(logs_dir)?;
1151    let summary = sweep_logs(
1152        logs_dir,
1153        SystemTime::now(),
1154        DEAD_PROCESS_LOG_MAX_AGE,
1155        LOG_DIRECTORY_BUDGET_BYTES,
1156    )?;
1157    mark_log_sweep_ran();
1158    let sink = RotatingFile::open(
1159        file_path.to_path_buf(),
1160        LOG_FILE_BYTES,
1161        LOG_GENERATIONS,
1162        ROTATION_CHECK_EVERY,
1163    )?;
1164    Ok((sink, summary))
1165}
1166
1167fn initial_file_sink(
1168    logs_dir: &Path,
1169    file_path: &Path,
1170    health: Arc<LogWriteHealth>,
1171) -> (RotatingFile, Option<SweepSummary>) {
1172    match prepare_file_sink(logs_dir, file_path) {
1173        Ok((sink, summary)) => (sink, Some(summary)),
1174        Err(error) => {
1175            LogWriteRecovery::new(health, LOG_WRITE_RETRY_MIN).failed(&error, 0, Instant::now());
1176            write_stderr_once(&format!(
1177                "[aft] WARN durable log will retry opening {}: {error}\n",
1178                file_path.display()
1179            ));
1180            (
1181                RotatingFile::unopened(
1182                    file_path.to_path_buf(),
1183                    LOG_FILE_BYTES,
1184                    LOG_GENERATIONS,
1185                    ROTATION_CHECK_EVERY,
1186                ),
1187                None,
1188            )
1189        }
1190    }
1191}
1192
1193enum LogMessage {
1194    Write(Vec<u8>),
1195    Reconfigure(PathBuf),
1196    /// Write everything queued before this message, then signal the sender.
1197    Flush(SyncSender<bool>),
1198}
1199
1200type SharedFileSink<S = RotatingFile> = Arc<Mutex<Option<S>>>;
1201
1202/// Only the writer thread performs sink I/O. Tests inject failures at this
1203/// boundary without consuming disk space or changing the global logger.
1204trait FileLogSink: Send {
1205    fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()>;
1206    fn reopen(&mut self) -> io::Result<()>;
1207    fn discard_buffer(&mut self);
1208    fn reconfigure(&mut self, storage_root: &Path) -> io::Result<SweepSummary>;
1209}
1210
1211#[derive(Default)]
1212struct LogWriteHealth {
1213    dropped_lines_total: AtomicU64,
1214    last_write_error: Mutex<Option<String>>,
1215    failing_since: Mutex<Option<String>>,
1216}
1217
1218static LOG_WRITE_HEALTH: LazyLock<Arc<LogWriteHealth>> =
1219    LazyLock::new(|| Arc::new(LogWriteHealth::default()));
1220
1221/// Read error metadata, never the file or the sink's I/O lock. The cumulative
1222/// counter includes queue overflow and unconfirmed/deferred file batches;
1223/// recovery markers count the latter over each write outage. Partial writes
1224/// cannot confirm a record, so an errored batch is counted in full.
1225pub fn durable_log_health() -> serde_json::Value {
1226    let mut health = LOG_WRITE_HEALTH.snapshot();
1227    let mut mirror = STDERR_MIRROR_HEALTH.snapshot();
1228    mirror["best_effort"] = SUBC_LOGGING.load(Ordering::Relaxed).into();
1229    health["stderr_mirror"] = mirror;
1230    health
1231}
1232
1233impl LogWriteHealth {
1234    fn snapshot(&self) -> serde_json::Value {
1235        serde_json::json!({
1236            "dropped_lines_total": self.dropped_lines_total.load(Ordering::Relaxed),
1237            "last_write_error": self.last_write_error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(),
1238            "failing_since": self.failing_since.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(),
1239        })
1240    }
1241
1242    fn drop_lines(&self, count: u64) {
1243        self.dropped_lines_total.fetch_add(count, Ordering::Relaxed);
1244        PERF.file_lines_dropped.fetch_add(count, Ordering::Relaxed);
1245    }
1246}
1247
1248fn log_line_count(bytes: &[u8]) -> u64 {
1249    bytes.iter().filter(|&&byte| byte == b'\n').count().max(1) as u64
1250}
1251
1252struct LogWriteOutage {
1253    since: String,
1254    first_error: String,
1255    last_error: String,
1256    dropped_lines: u64,
1257    retry_at: Instant,
1258}
1259
1260struct LogWriteRecovery {
1261    health: Arc<LogWriteHealth>,
1262    outage: Option<LogWriteOutage>,
1263    retry_min: Duration,
1264    retry_delay: Duration,
1265}
1266
1267impl LogWriteRecovery {
1268    fn new(health: Arc<LogWriteHealth>, retry_min: Duration) -> Self {
1269        // Initialization can itself fail on a full volume. Retain its path
1270        // and error, and let the same worker retry instead of disabling it.
1271        let since = health
1272            .failing_since
1273            .lock()
1274            .unwrap_or_else(std::sync::PoisonError::into_inner)
1275            .clone();
1276        let error = health
1277            .last_write_error
1278            .lock()
1279            .unwrap_or_else(std::sync::PoisonError::into_inner)
1280            .clone();
1281        let outage = since.zip(error).map(|(since, error)| LogWriteOutage {
1282            since,
1283            first_error: error.clone(),
1284            last_error: error,
1285            dropped_lines: 0,
1286            retry_at: Instant::now(),
1287        });
1288        Self {
1289            health,
1290            outage,
1291            retry_min,
1292            retry_delay: retry_min,
1293        }
1294    }
1295
1296    fn failed(&mut self, error: &io::Error, dropped_lines: u64, now: Instant) {
1297        let error = crate::log_redact::aft_redactor(&error.to_string()).into_owned();
1298        let outage = self.outage.get_or_insert_with(|| {
1299            let since = format_utc_timestamp();
1300            *self
1301                .health
1302                .failing_since
1303                .lock()
1304                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(since.clone());
1305            LogWriteOutage {
1306                since,
1307                first_error: error.clone(),
1308                last_error: error.clone(),
1309                dropped_lines: 0,
1310                retry_at: now,
1311            }
1312        });
1313        outage.last_error = error.clone();
1314        outage.dropped_lines = outage.dropped_lines.saturating_add(dropped_lines);
1315        outage.retry_at = now + self.retry_delay;
1316        self.retry_delay = self.retry_delay.saturating_mul(2).min(LOG_WRITE_RETRY_MAX);
1317        *self
1318            .health
1319            .last_write_error
1320            .lock()
1321            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(error);
1322        self.health.drop_lines(dropped_lines);
1323    }
1324
1325    fn write_batch(
1326        &mut self,
1327        sink: &mut impl FileLogSink,
1328        lines: &[Vec<u8>],
1329        now: Instant,
1330    ) -> bool {
1331        if lines.is_empty() {
1332            return true;
1333        }
1334        let dropped_lines = lines.iter().map(|line| log_line_count(line)).sum();
1335        if let Some(outage) = self.outage.as_mut() {
1336            if now < outage.retry_at {
1337                // Drain rather than sleep: logging stays bounded even when a
1338                // full disk remains unavailable for hours.
1339                outage.dropped_lines = outage.dropped_lines.saturating_add(dropped_lines);
1340                self.health.drop_lines(dropped_lines);
1341                return false;
1342            }
1343            let recovered_at = format_utc_timestamp();
1344            let errors = if outage.first_error == outage.last_error {
1345                outage.first_error.clone()
1346            } else {
1347                format!("{}; last error: {}", outage.first_error, outage.last_error)
1348            };
1349            let marker = format!(
1350                "{recovered_at} [aft] WARN log writes failed from {} to {recovered_at} ({errors}); {} lines dropped\n",
1351                outage.since, outage.dropped_lines
1352            );
1353            // Flush the marker separately. No normal line may precede it on
1354            // the replacement handle, including buffered data from a failure.
1355            if let Err(error) = sink
1356                .reopen()
1357                .and_then(|()| sink.write_batch(&[marker.into_bytes()]))
1358            {
1359                sink.discard_buffer();
1360                self.failed(&error, dropped_lines, now);
1361                return false;
1362            }
1363            self.outage = None;
1364            self.retry_delay = self.retry_min;
1365            *self
1366                .health
1367                .failing_since
1368                .lock()
1369                .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
1370        }
1371        if let Err(error) = sink.write_batch(lines) {
1372            sink.discard_buffer();
1373            // Some bytes may have reached disk before a write/flush error.
1374            // Count the whole unconfirmed batch as lost, rather than silently
1375            // claiming partially written records were durable.
1376            self.failed(&error, dropped_lines, now);
1377            return false;
1378        }
1379        true
1380    }
1381}
1382
1383#[derive(Default)]
1384struct FileControl {
1385    tx: Option<SyncSender<LogMessage>>,
1386    storage_root: Option<PathBuf>,
1387    sink: Option<SharedFileSink>,
1388}
1389
1390static FILE_CONTROL: LazyLock<Mutex<FileControl>> =
1391    LazyLock::new(|| Mutex::new(FileControl::default()));
1392
1393struct TeeWriter {
1394    file_tx: Option<SyncSender<LogMessage>>,
1395    stderr: StderrOutput,
1396}
1397
1398impl TeeWriter {
1399    fn new(file_tx: Option<SyncSender<LogMessage>>) -> Self {
1400        Self {
1401            file_tx,
1402            stderr: StderrOutput::for_process(),
1403        }
1404    }
1405}
1406
1407enum StderrOutput {
1408    Standalone,
1409    Subc(stderr_mirror::Mirror),
1410}
1411
1412impl StderrOutput {
1413    fn for_process() -> Self {
1414        if SUBC_LOGGING.load(Ordering::Relaxed) {
1415            Self::Subc(STDERR_MIRROR.get().cloned().unwrap_or_else(|| {
1416                stderr_mirror::Mirror::disabled(Arc::clone(&STDERR_MIRROR_HEALTH))
1417            }))
1418        } else {
1419            Self::Standalone
1420        }
1421    }
1422}
1423
1424impl Write for StderrOutput {
1425    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1426        match self {
1427            Self::Standalone => {
1428                let _ = io::stderr().write_all(bytes);
1429            }
1430            Self::Subc(mirror) => mirror.record(bytes),
1431        }
1432        Ok(bytes.len())
1433    }
1434
1435    fn flush(&mut self) -> io::Result<()> {
1436        match self {
1437            Self::Standalone => {
1438                let _ = io::stderr().flush();
1439            }
1440            Self::Subc(mirror) => mirror.flush(),
1441        }
1442        Ok(())
1443    }
1444}
1445
1446impl Write for TeeWriter {
1447    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1448        // Mask credentials before either copy. Standalone writes stderr
1449        // synchronously so the plugin can save it in its log; subc uses the
1450        // best-effort mirror.
1451        let line = crate::log_redact::aft_redact_bytes(buf);
1452        // The durable file copy goes first and does not depend on stderr: in
1453        // subc mode stderr is a pipe the daemon reads, and once the daemon is
1454        // shutting down that pipe can be closed. A failed stderr write used to
1455        // return early here and drop the file copy too, which is how a module
1456        // exit could leave no line explaining it.
1457        enqueue_file_line(&mut self.file_tx, &line, &LOG_WRITE_HEALTH);
1458        let _ = self.stderr.write_all(&line);
1459        Ok(buf.len())
1460    }
1461
1462    fn flush(&mut self) -> io::Result<()> {
1463        let _ = self.stderr.flush();
1464        Ok(())
1465    }
1466}
1467
1468fn enqueue_file_line(
1469    file_tx: &mut Option<SyncSender<LogMessage>>,
1470    line: &[u8],
1471    health: &LogWriteHealth,
1472) {
1473    if let Some(tx) = file_tx.as_ref() {
1474        match tx.try_send(LogMessage::Write(line.to_vec())) {
1475            Ok(()) => {}
1476            Err(TrySendError::Full(_)) => health.drop_lines(log_line_count(line)),
1477            Err(TrySendError::Disconnected(_)) => {
1478                health.drop_lines(log_line_count(line));
1479                *file_tx = None;
1480            }
1481        }
1482    }
1483}
1484
1485fn run_file_writer<S: FileLogSink>(
1486    shared_sink: SharedFileSink<S>,
1487    rx: mpsc::Receiver<LogMessage>,
1488    health: Arc<LogWriteHealth>,
1489    retry_min: Duration,
1490) {
1491    let mut recovery = LogWriteRecovery::new(health, retry_min);
1492    let mut durable = true;
1493    // Test-only: hold each batch so a test can prove exit paths wait for the
1494    // writer instead of racing it. Debug builds only; release ignores it.
1495    #[cfg(debug_assertions)]
1496    let test_delay = std::env::var("AFT_TEST_LOG_WRITER_DELAY_MS")
1497        .ok()
1498        .and_then(|value| value.parse::<u64>().ok())
1499        .map(std::time::Duration::from_millis);
1500    // Test-only: acknowledge each flush request no sooner than this long after
1501    // the writer collects it. The batch delay above does not bound that: a
1502    // flush queued near the end of a delayed batch is collected and
1503    // acknowledged with it almost at once. Debug builds only.
1504    #[cfg(debug_assertions)]
1505    let test_flush_hold = std::env::var("AFT_TEST_LOG_FLUSH_HOLD_MS")
1506        .ok()
1507        .and_then(|value| value.parse::<u64>().ok())
1508        .map(std::time::Duration::from_millis);
1509    while let Ok(message) = rx.recv() {
1510        #[cfg(debug_assertions)]
1511        if let Some(delay) = test_delay {
1512            thread::sleep(delay);
1513        }
1514        let mut lines = Vec::new();
1515        let mut reconfigure = None;
1516        let mut flushed = None;
1517        match message {
1518            LogMessage::Write(line) => {
1519                lines.push(line);
1520                while lines.len() < 256 {
1521                    match rx.try_recv() {
1522                        Ok(LogMessage::Write(line)) => lines.push(line),
1523                        Ok(LogMessage::Reconfigure(storage_root)) => {
1524                            reconfigure = Some(storage_root);
1525                            break;
1526                        }
1527                        Ok(LogMessage::Flush(done)) => {
1528                            flushed = Some(done);
1529                            break;
1530                        }
1531                        Err(_) => break,
1532                    }
1533                }
1534            }
1535            LogMessage::Reconfigure(storage_root) => reconfigure = Some(storage_root),
1536            LogMessage::Flush(done) => flushed = Some(done),
1537        }
1538        // Exit can take the sink while the worker is delayed. Serialize terminal
1539        // writes with rotation and reconfiguration, but not with queue waits.
1540        let mut slot = shared_sink
1541            .lock()
1542            .unwrap_or_else(std::sync::PoisonError::into_inner);
1543        let Some(sink) = slot.as_mut() else { break };
1544        durable &= recovery.write_batch(sink, &lines, Instant::now());
1545        // The channel is FIFO, so every line queued before the flush request
1546        // has been attempted by now. Report losses instead of confirming that
1547        // a failed batch was durable; the receiver stays alive for recovery.
1548        if let Some(done) = flushed {
1549            let confirmed = durable;
1550            durable = true;
1551            #[cfg(debug_assertions)]
1552            if let Some(hold) = test_flush_hold {
1553                // Release the sink first: the exit path takes it to write its
1554                // terminal line, and must not wait out this hold.
1555                drop(slot);
1556                thread::sleep(hold);
1557                let _ = done.try_send(confirmed);
1558                continue;
1559            }
1560            let _ = done.try_send(confirmed);
1561        }
1562        if let Some(storage_root) = reconfigure {
1563            let logs_dir = storage_root.join("logs");
1564            let path = logs_dir.join(format!("aft-{}.log", std::process::id()));
1565            match sink.reconfigure(&storage_root) {
1566                Ok(summary) => {
1567                    if let Some(outage) = recovery.outage.as_mut() {
1568                        outage.retry_at = Instant::now();
1569                    }
1570                    log_sweep_summary(summary);
1571                }
1572                Err(error) => write_stderr_once(&format!(
1573                    "[aft] WARN durable log could not switch to {}: {error}\n",
1574                    path.display()
1575                )),
1576            }
1577        }
1578    }
1579}
1580
1581fn write_stderr_once(message: &str) {
1582    write_stderr_diagnostic(message);
1583}
1584
1585/// Emit a process diagnostic without making subc callers wait on its stderr pipe.
1586/// Standalone retains its synchronous stderr behavior.
1587pub fn write_stderr_diagnostic(message: &str) {
1588    let line = crate::log_redact::aft_redact_bytes(message.as_bytes());
1589    let _ = StderrOutput::for_process().write_all(&line);
1590}
1591
1592/// Wait, at most `timeout`, until the durable log writer has written every line
1593/// logged before this call.
1594///
1595/// The file sink is a background thread fed by a channel, so a process that
1596/// exits right after logging loses whatever is still queued: the lines closest
1597/// to an exit, which are the ones forensics needs. Every exit path calls this
1598/// first. Returns false when the writer did not confirm in time (or the durable
1599/// log is disabled), so an exit is never held longer than `timeout`.
1600pub fn flush_durable_log(timeout: std::time::Duration) -> bool {
1601    let tx = match FILE_CONTROL.lock() {
1602        Ok(control) => control.tx.clone(),
1603        Err(_) => None,
1604    };
1605    let Some(tx) = tx else {
1606        return false;
1607    };
1608    let (done_tx, done_rx) = mpsc::sync_channel(1);
1609    // A blocking send: a full queue is exactly when there is the most to lose.
1610    // The writer drains continuously, so this waits for space rather than
1611    // dropping the request.
1612    if tx.send(LogMessage::Flush(done_tx)).is_err() {
1613        return false;
1614    }
1615    done_rx.recv_timeout(timeout).unwrap_or(false)
1616}
1617
1618/// Wait only during process exit for the queued stderr flush fence.
1619/// File-log durability is a separate fence; ordinary log flushes never wait here.
1620pub fn flush_stderr_on_exit(timeout: std::time::Duration) -> bool {
1621    STDERR_MIRROR
1622        .get()
1623        .is_none_or(|mirror| mirror.drain_on_exit(timeout))
1624}
1625
1626/// Test-only (debug builds): stop the stderr mirror from writing until
1627/// [`flush_stderr_on_exit`] starts, so the lines logged in between are still
1628/// queued when the exit fence runs. Without the fence they would be lost.
1629#[cfg(debug_assertions)]
1630pub fn hold_stderr_mirror_until_exit_fence() {
1631    if let Some(mirror) = STDERR_MIRROR.get() {
1632        mirror.hold_until_exit_fence();
1633    }
1634}
1635
1636/// Persist the last process-exit line without depending on the async writer.
1637/// Taking its active sink prevents later rotation or reconfiguration from
1638/// moving the marker. Queued diagnostics may be abandoned once their bounded
1639/// flush expires, but this line is appended and synced before exit proceeds.
1640pub fn write_terminal_log_sync(message: &str) -> io::Result<()> {
1641    let shared = FILE_CONTROL
1642        .lock()
1643        .map_err(|_| io::Error::other("log control poisoned"))?
1644        .sink
1645        .clone()
1646        .ok_or_else(|| io::Error::other("durable log disabled"))?;
1647    let mut slot = shared
1648        .lock()
1649        .unwrap_or_else(std::sync::PoisonError::into_inner);
1650    let mut sink = slot
1651        .take()
1652        .ok_or_else(|| io::Error::other("log sink already stopped"))?;
1653    if let Some(mut writer) = sink.writer.take() {
1654        writer.flush()?;
1655    }
1656    write_terminal_line(&sink, &mut StderrOutput::for_process(), message)
1657}
1658
1659fn write_terminal_line(
1660    sink: &RotatingFile,
1661    stderr: &mut impl Write,
1662    message: &str,
1663) -> io::Result<()> {
1664    let mut line = Vec::new();
1665    write_log_line(
1666        &mut line,
1667        &format_utc_timestamp(),
1668        log::Level::Info,
1669        "aft",
1670        &format_args!("{message}"),
1671    )?;
1672    let line = crate::log_redact::aft_redact_bytes(&line);
1673    let _ = stderr.write_all(&line);
1674    let mut file = open_private_log_file(&sink.path, false)?;
1675    file.write_all(&line)?;
1676    aft_store::sync::sync_all(&file, &sink.path)?;
1677    sink.write_counter.credit_logical(line.len() as u64);
1678    Ok(())
1679}
1680
1681struct RotatingFile {
1682    path: PathBuf,
1683    writer: Option<BufWriter<File>>,
1684    size: u64,
1685    threshold: u64,
1686    generations: usize,
1687    check_every: u64,
1688    writes_since_check: u64,
1689    write_counter: crate::write_counters::Counter,
1690}
1691
1692impl RotatingFile {
1693    fn unopened(path: PathBuf, threshold: u64, generations: usize, check_every: u64) -> Self {
1694        Self {
1695            path,
1696            writer: None,
1697            size: 0,
1698            threshold,
1699            generations,
1700            check_every: check_every.max(1),
1701            writes_since_check: 0,
1702            write_counter: crate::write_counters::process_root_counter(
1703                crate::write_counters::Domain::Logs,
1704            ),
1705        }
1706    }
1707
1708    fn open(
1709        path: PathBuf,
1710        threshold: u64,
1711        generations: usize,
1712        check_every: u64,
1713    ) -> io::Result<Self> {
1714        let file = open_private_log_file(&path, false)?;
1715        #[cfg(unix)]
1716        {
1717            // Files from before logs were private keep their old mode across
1718            // opens and renames, so tighten the live file and its backups.
1719            tighten_if_owned(&path, LOG_FILE_MODE);
1720            for generation in 1..=generations {
1721                tighten_if_owned(&rotated_path(&path, generation), LOG_FILE_MODE);
1722            }
1723        }
1724        let size = file.metadata()?.len();
1725        let mut sink = Self::unopened(path, threshold, generations, check_every);
1726        sink.writer = Some(BufWriter::new(file));
1727        sink.size = size;
1728        if size > threshold {
1729            sink.rotate()?;
1730        }
1731        Ok(sink)
1732    }
1733
1734    fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
1735        let batch_bytes = lines.iter().map(Vec::len).sum::<usize>() as u64;
1736        self.writes_since_check = self.writes_since_check.saturating_add(lines.len() as u64);
1737        if self.writes_since_check >= self.check_every
1738            && self.size > 0
1739            && self.size.saturating_add(batch_bytes) > self.threshold
1740        {
1741            self.rotate()?;
1742        }
1743        let writer = self
1744            .writer
1745            .as_mut()
1746            .ok_or_else(|| io::Error::other("log writer unavailable"))?;
1747        for line in lines {
1748            writer.write_all(line)?;
1749        }
1750        // The worker batches channel messages before this flush. File I/O never
1751        // runs on request, watcher, executor, or transport threads.
1752        writer.flush()?;
1753        self.write_counter.credit_logical(batch_bytes);
1754        self.size = self.size.saturating_add(batch_bytes);
1755        if self.writes_since_check >= self.check_every {
1756            self.writes_since_check = 0;
1757        }
1758        Ok(())
1759    }
1760
1761    fn rotate(&mut self) -> io::Result<()> {
1762        if let Some(mut writer) = self.writer.take() {
1763            if let Err(error) = writer.flush() {
1764                let _ = writer.into_parts();
1765                return Err(error);
1766            }
1767        }
1768        if self.generations > 0 {
1769            let oldest = rotated_path(&self.path, self.generations);
1770            remove_file_if_present(&oldest)?;
1771            for generation in (1..self.generations).rev() {
1772                let from = rotated_path(&self.path, generation);
1773                let to = rotated_path(&self.path, generation + 1);
1774                rename_if_present(&from, &to)?;
1775            }
1776            rename_if_present(&self.path, &rotated_path(&self.path, 1))?;
1777        } else {
1778            remove_file_if_present(&self.path)?;
1779        }
1780        let file = open_private_log_file(&self.path, true)?;
1781        self.writer = Some(BufWriter::new(file));
1782        self.size = 0;
1783        self.writes_since_check = 0;
1784        Ok(())
1785    }
1786}
1787
1788impl FileLogSink for RotatingFile {
1789    fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
1790        RotatingFile::write_batch(self, lines)
1791    }
1792
1793    fn reopen(&mut self) -> io::Result<()> {
1794        self.discard_buffer();
1795        create_private_log_dir(
1796            self.path
1797                .parent()
1798                .ok_or_else(|| io::Error::other("log path has no parent"))?,
1799        )?;
1800        let file = open_private_log_file(&self.path, false)?;
1801        self.size = file.metadata()?.len();
1802        self.writer = Some(BufWriter::new(file));
1803        self.writes_since_check = 0;
1804        Ok(())
1805    }
1806
1807    fn discard_buffer(&mut self) {
1808        if let Some(writer) = self.writer.take() {
1809            // BufWriter::drop flushes implicitly. A failed batch is already
1810            // counted as lost; never replay it ahead of the recovery marker.
1811            let _ = writer.into_parts();
1812        }
1813    }
1814
1815    fn reconfigure(&mut self, storage_root: &Path) -> io::Result<SweepSummary> {
1816        let logs_dir = storage_root.join("logs");
1817        let path = logs_dir.join(format!("aft-{}.log", std::process::id()));
1818        let (sink, summary) = prepare_file_sink(&logs_dir, &path)?;
1819        self.discard_buffer();
1820        *self = sink;
1821        Ok(summary)
1822    }
1823}
1824
1825fn rotated_path(base: &Path, generation: usize) -> PathBuf {
1826    let mut path = base.as_os_str().to_os_string();
1827    path.push(format!(".{generation}"));
1828    PathBuf::from(path)
1829}
1830
1831/// Owner read/write only for every log file AFT creates.
1832#[cfg(unix)]
1833const LOG_FILE_MODE: u32 = crate::private_storage::FILE_MODE;
1834
1835/// Create the log directory owner-only, and tighten one left over from before
1836/// logs were private. Only the storage root and its log directory are tightened.
1837fn create_private_log_dir(dir: &Path) -> io::Result<()> {
1838    crate::private_storage::open_dir(dir.parent().unwrap_or(dir), dir)
1839}
1840
1841/// Open a log file for appending (or truncate it, for a fresh generation after
1842/// rotation). A newly created file is owner read/write only on Unix.
1843fn open_private_log_file(path: &Path, truncate: bool) -> io::Result<File> {
1844    let mut options = crate::private_storage::options();
1845    options.create(true);
1846    if truncate {
1847        options.write(true).truncate(true);
1848    } else {
1849        options.append(true);
1850    }
1851    #[cfg(unix)]
1852    {
1853        use std::os::unix::fs::OpenOptionsExt;
1854        options.mode(LOG_FILE_MODE);
1855    }
1856    options.open(path)
1857}
1858
1859/// Drop group/other permission bits from `path` when the current user owns it.
1860/// Best effort: a path owned by someone else (a shared storage root) or one
1861/// that cannot be changed is left as it is rather than failing log setup.
1862#[cfg(unix)]
1863fn tighten_if_owned(path: &Path, mode: u32) {
1864    use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
1865    if path
1866        .parent()
1867        .into_iter()
1868        .chain(path.parent().and_then(Path::parent))
1869        .any(|dir| fs::symlink_metadata(dir).is_ok_and(|metadata| metadata.is_symlink()))
1870    {
1871        return;
1872    }
1873    let Ok(file) = OpenOptions::new()
1874        .read(true)
1875        .custom_flags(libc::O_NOFOLLOW)
1876        .open(path)
1877    else {
1878        return;
1879    };
1880    let Ok(metadata) = file.metadata() else {
1881        return;
1882    };
1883    // SAFETY: geteuid has no preconditions and cannot fail.
1884    let euid = unsafe { libc::geteuid() };
1885    if metadata.uid() != euid || metadata.mode() & 0o777 & !mode == 0 {
1886        return;
1887    }
1888    let _ = file.set_permissions(fs::Permissions::from_mode(mode));
1889}
1890
1891fn remove_file_if_present(path: &Path) -> io::Result<()> {
1892    match fs::remove_file(path) {
1893        Ok(()) => Ok(()),
1894        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1895        Err(error) => Err(error),
1896    }
1897}
1898
1899fn rename_if_present(from: &Path, to: &Path) -> io::Result<()> {
1900    match fs::rename(from, to) {
1901        Ok(()) => Ok(()),
1902        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1903        Err(error) => Err(error),
1904    }
1905}
1906
1907#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1908struct SweepSummary {
1909    removed_files: usize,
1910    bytes_freed: u64,
1911    /// Files whose PID number is live but belongs to a process started after
1912    /// the file's last write. Reported separately so a sweep that removes
1913    /// nothing can be read from the log as "nothing was dead" versus "the
1914    /// recycled-PID verdict never fired".
1915    recycled_pids: usize,
1916    /// Bytes the directory still holds above its budget after the sweep,
1917    /// because the only remaining candidates were protected (the newest dead
1918    /// process log inside its forensic window). Zero when the budget was met.
1919    over_budget_bytes: u64,
1920}
1921
1922struct ProcessLogFile {
1923    path: PathBuf,
1924    modified: Option<SystemTime>,
1925    bytes: u64,
1926    dead: bool,
1927    old_enough: bool,
1928    removed: bool,
1929}
1930
1931/// A numbered rotation the plugin logger no longer owns. The TypeScript sink
1932/// keeps exactly one backup generation (`aft-plugin.log.1`); higher numbers
1933/// are relics of an earlier multi-generation policy and nothing rotates or
1934/// removes them, so they sat at 140 MB of a 200 MB budget for months.
1935fn relic_plugin_rotation(name: &str) -> bool {
1936    let Some(rest) = name.strip_prefix("aft-plugin") else {
1937        return false;
1938    };
1939    let Some((_, generation)) = rest.rsplit_once(".log.") else {
1940        return false;
1941    };
1942    generation
1943        .parse::<u32>()
1944        .is_ok_and(|generation| generation >= 2)
1945}
1946
1947fn log_sweep_summary(summary: SweepSummary) {
1948    crate::slog_info!(
1949        "log retention sweep: removed_files={} bytes_freed={} recycled_pids={}",
1950        summary.removed_files,
1951        summary.bytes_freed,
1952        summary.recycled_pids
1953    );
1954    if summary.over_budget_bytes > 0 {
1955        crate::slog_warn!(
1956            "log directory over budget by {} bytes after sweep: the newest dead process log is kept as the record of that process's exit",
1957            summary.over_budget_bytes
1958        );
1959    }
1960}
1961
1962/// Sweep dead Rust process logs, then enforce the directory budget without ever
1963/// deleting a live PID's file or the plugin logger's pid-less file.
1964fn sweep_logs(
1965    dir: &Path,
1966    now: SystemTime,
1967    max_age: Duration,
1968    budget_bytes: u64,
1969) -> io::Result<SweepSummary> {
1970    let mut total_bytes = 0_u64;
1971    let mut process_logs = Vec::new();
1972    let mut relic_rotations = Vec::new();
1973    let mut live_pids = BTreeMap::new();
1974    let mut recycled_count = 0_usize;
1975    let own_pid = std::process::id();
1976
1977    for entry in fs::read_dir(dir)? {
1978        let entry = match entry {
1979            Ok(entry) => entry,
1980            Err(_) => continue,
1981        };
1982        let metadata = match entry.metadata() {
1983            Ok(metadata) if metadata.is_file() => metadata,
1984            Ok(_) | Err(_) => continue,
1985        };
1986        let bytes = metadata.len();
1987        total_bytes = total_bytes.saturating_add(bytes);
1988        let name = entry.file_name();
1989        let name = name.to_string_lossy();
1990        if relic_plugin_rotation(&name) {
1991            relic_rotations.push((entry.path(), bytes));
1992            continue;
1993        }
1994        let pid = match name.as_ref() {
1995            // This shared TypeScript-owned file has no PID. Keep this explicit
1996            // so a future default branch cannot accidentally make it reaped.
1997            "aft-plugin.log" => continue,
1998            _ => process_log_pid(&name),
1999        };
2000        let Some(pid) = pid else {
2001            continue;
2002        };
2003        let modified = metadata.modified().ok();
2004        let old_enough = modified
2005            .and_then(|modified| now.duration_since(modified).ok())
2006            .is_some_and(|age| age >= max_age);
2007        let alive = *live_pids.entry(pid).or_insert_with(|| {
2008            if !is_process_alive(pid) {
2009                return false;
2010            }
2011            let recycled = pid_started_after_last_write(pid, modified);
2012            if recycled {
2013                recycled_count += 1;
2014            }
2015            !recycled
2016        });
2017        process_logs.push(ProcessLogFile {
2018            path: entry.path(),
2019            modified,
2020            bytes,
2021            dead: pid != own_pid && !alive,
2022            old_enough,
2023            removed: false,
2024        });
2025    }
2026
2027    let mut summary = SweepSummary {
2028        recycled_pids: recycled_count,
2029        ..SweepSummary::default()
2030    };
2031    for file in &mut process_logs {
2032        if file.dead && file.old_enough && remove_sweep_candidate(&file.path) {
2033            file.removed = true;
2034            total_bytes = total_bytes.saturating_sub(file.bytes);
2035            summary.removed_files += 1;
2036            summary.bytes_freed = summary.bytes_freed.saturating_add(file.bytes);
2037        }
2038    }
2039
2040    // Relic rotations have no owner and no reader; they go unconditionally,
2041    // and before any process log is weighed against the budget.
2042    for (path, bytes) in &relic_rotations {
2043        if remove_sweep_candidate(path) {
2044            total_bytes = total_bytes.saturating_sub(*bytes);
2045            summary.removed_files += 1;
2046            summary.bytes_freed = summary.bytes_freed.saturating_add(*bytes);
2047        }
2048    }
2049
2050    // The budget backstop is deliberately separate from the age-gated reap:
2051    // once liveness says a PID is dead, budget pressure may remove even a fresh
2052    // dead file so the directory can actually converge under its hard limit.
2053    // Live files remain ineligible regardless of age or budget pressure.
2054    //
2055    // One dead file is exempt: the newest one, while it is younger than the
2056    // age reap. It is the log of the process that died last — the record of
2057    // an unexplained exit — and on 2026-09-18 a successor's startup sweep
2058    // deleted exactly that file (the directory was over budget on relic
2059    // rotations, and the predecessor's log was the only eligible candidate)
2060    // while the supervisor's own exit record died with the daemon restart
2061    // that caused the exit. Losing budget headroom for one 32 MB file is the
2062    // cheaper failure.
2063    process_logs.sort_by_key(|file| file.modified);
2064    let protected = process_logs
2065        .iter()
2066        .rposition(|file| file.dead && !file.removed && !file.old_enough);
2067    for (index, file) in process_logs
2068        .iter_mut()
2069        .enumerate()
2070        .filter(|(_, file)| file.dead && !file.removed)
2071    {
2072        if total_bytes <= budget_bytes {
2073            break;
2074        }
2075        if Some(index) == protected {
2076            continue;
2077        }
2078        if remove_sweep_candidate(&file.path) {
2079            file.removed = true;
2080            total_bytes = total_bytes.saturating_sub(file.bytes);
2081            summary.removed_files += 1;
2082            summary.bytes_freed = summary.bytes_freed.saturating_add(file.bytes);
2083        }
2084    }
2085    summary.over_budget_bytes = total_bytes.saturating_sub(budget_bytes);
2086
2087    Ok(summary)
2088}
2089
2090/// Slack for clock and filesystem timestamp granularity when comparing a
2091/// process start time against a log file's last write.
2092const PID_REUSE_TOLERANCE_MS: u64 = 2_000;
2093
2094/// The PID number outlives the process that wrote the log. After a reboot the
2095/// kernel hands low numbers to system daemons, so a liveness check by number
2096/// alone pinned sixteen-day-old files under the age reap and the budget
2097/// backstop alike. The real owner started before it wrote the file, so a start
2098/// time later than the file's last write proves the number was recycled.
2099/// Platforms without a start-time source keep the number-only verdict.
2100fn pid_started_after_last_write(pid: u32, modified: Option<SystemTime>) -> bool {
2101    let Some(modified_ms) = modified
2102        .and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok())
2103        .map(|since_epoch| since_epoch.as_millis() as u64)
2104    else {
2105        return false;
2106    };
2107    crate::process_identity::process_start_time_ms(pid)
2108        .is_some_and(|started_ms| started_ms > modified_ms.saturating_add(PID_REUSE_TOLERANCE_MS))
2109}
2110
2111fn remove_sweep_candidate(path: &Path) -> bool {
2112    // A sharing violation means another process has the file pinned (notably on
2113    // Windows). Leave it for a later sweep instead of failing the maintenance pass.
2114    fs::remove_file(path).is_ok()
2115}
2116
2117fn process_log_pid(name: &str) -> Option<u32> {
2118    let rest = name.strip_prefix("aft-")?;
2119    let (pid, suffix) = rest.split_once(".log")?;
2120    if !suffix.is_empty()
2121        && !(suffix.starts_with('.') && suffix[1..].chars().all(|ch| ch.is_ascii_digit()))
2122    {
2123        return None;
2124    }
2125    pid.parse().ok()
2126}
2127
2128static LAST_LOG_SWEEP: LazyLock<Mutex<Option<Instant>>> = LazyLock::new(|| Mutex::new(None));
2129
2130fn mark_log_sweep_ran() {
2131    if let Ok(mut last_run) = LAST_LOG_SWEEP.lock() {
2132        *last_run = Some(Instant::now());
2133    }
2134}
2135
2136/// Run log maintenance from an existing idle/maintenance tick at most hourly.
2137/// The sweep walks and deletes files, so it runs on its own thread: callers
2138/// include the subc frame loop, which must not wait on the filesystem.
2139pub fn maybe_sweep_logs() {
2140    let now = Instant::now();
2141    let should_run = LAST_LOG_SWEEP
2142        .lock()
2143        .map(|mut last_run| {
2144            if last_run.is_some_and(|last| now.duration_since(last) < LOG_SWEEP_INTERVAL) {
2145                false
2146            } else {
2147                *last_run = Some(now);
2148                true
2149            }
2150        })
2151        .unwrap_or(false);
2152    if !should_run {
2153        return;
2154    }
2155
2156    let spawned = std::thread::Builder::new()
2157        .name("aft-log-sweep".to_owned())
2158        .spawn(sweep_logs_now);
2159    if let Err(error) = spawned {
2160        crate::slog_warn!("log retention sweep could not start: {}", error);
2161    }
2162}
2163
2164fn sweep_logs_now() {
2165    let storage_root = FILE_CONTROL
2166        .lock()
2167        .ok()
2168        .and_then(|control| control.storage_root.clone())
2169        .unwrap_or_else(|| crate::storage_path::storage_dir(None));
2170    let logs_dir = storage_root.join("logs");
2171    match sweep_logs(
2172        &logs_dir,
2173        SystemTime::now(),
2174        DEAD_PROCESS_LOG_MAX_AGE,
2175        LOG_DIRECTORY_BUDGET_BYTES,
2176    ) {
2177        Ok(summary) => log_sweep_summary(summary),
2178        Err(error) => crate::slog_warn!(
2179            "log retention sweep failed for {}: {}",
2180            logs_dir.display(),
2181            error
2182        ),
2183    }
2184}
2185
2186#[derive(Default)]
2187struct PerfMetrics {
2188    watcher_ingested: AtomicU64,
2189    watcher_paths: AtomicU64,
2190    watcher_dropped: AtomicU64,
2191    drain_slices: AtomicU64,
2192    semantic_collects: AtomicU64,
2193    semantic_files: AtomicU64,
2194    semantic_chunks: AtomicU64,
2195    semantic_ms: AtomicU64,
2196    callgraph_invalidations: AtomicU64,
2197    file_lines_dropped: AtomicU64,
2198    tool_call_count: AtomicU64,
2199    tool_calls: Mutex<VecDeque<ToolCallPerfSample>>,
2200    tier2: Mutex<BTreeMap<String, (u64, u64)>>,
2201    next_sample_ns: AtomicU64,
2202    reporter: Mutex<PerfReporter>,
2203}
2204
2205struct PerfReporter {
2206    last_report: Instant,
2207    last_completed_interactive: u64,
2208    last_completed_maintenance: u64,
2209    last_tool_call_count: u64,
2210}
2211
2212impl Default for PerfReporter {
2213    fn default() -> Self {
2214        Self {
2215            last_report: Instant::now(),
2216            last_completed_interactive: 0,
2217            last_completed_maintenance: 0,
2218            last_tool_call_count: 0,
2219        }
2220    }
2221}
2222
2223#[derive(Clone, Copy)]
2224struct ToolCallPerfSample {
2225    total_ms: u64,
2226    queue_ms: u64,
2227}
2228
2229#[derive(Clone, Copy, Default)]
2230struct ToolCallPerfSummary {
2231    window: usize,
2232    p50_total_ms: u64,
2233    max_total_ms: u64,
2234    p50_queue_ms: u64,
2235    max_queue_ms: u64,
2236}
2237
2238#[derive(Clone, Copy, Default)]
2239struct ExecutorSample {
2240    interactive_running: usize,
2241    maintenance_running: usize,
2242    interactive_queued: usize,
2243    maintenance_queued: usize,
2244    interactive_oldest_ms: Option<u64>,
2245    maintenance_oldest_ms: Option<u64>,
2246}
2247
2248static PERF: LazyLock<PerfMetrics> = LazyLock::new(PerfMetrics::default);
2249
2250/// Move subsequent file log writes to a newly configured storage root.
2251///
2252/// Reconfiguration is queued behind existing writes and is a no-op when the
2253/// root has not changed. Initialization and explicit configure changes call
2254/// this directly, avoiding storage-root polling on transport drain turns.
2255pub fn sync_storage_root(storage_root: PathBuf) {
2256    let Ok(mut control) = FILE_CONTROL.lock() else {
2257        return;
2258    };
2259    if control.storage_root.as_ref() == Some(&storage_root) {
2260        return;
2261    }
2262    let Some(tx) = control.tx.as_ref() else {
2263        return;
2264    };
2265    if tx
2266        .try_send(LogMessage::Reconfigure(storage_root.clone()))
2267        .is_ok()
2268    {
2269        control.storage_root = Some(storage_root);
2270    }
2271}
2272
2273/// Called by `drain_watcher_events_bounded` for dispatch events actually received.
2274pub fn note_watcher_events(count: usize) {
2275    PERF.watcher_ingested
2276        .fetch_add(count as u64, Ordering::Relaxed);
2277}
2278
2279/// Called when a watcher drain slice takes paths from dispatch continuation state.
2280pub fn note_drain_paths(count: usize) {
2281    PERF.watcher_paths
2282        .fetch_add(count as u64, Ordering::Relaxed);
2283}
2284
2285/// Called when `drain_watcher_events_bounded` receives a rescan-required overflow signal.
2286pub fn note_watcher_overflow() {
2287    PERF.watcher_dropped.fetch_add(1, Ordering::Relaxed);
2288}
2289
2290/// Called by the standalone request loop before a request-triggered runtime drain.
2291pub fn note_drain_slice() {
2292    PERF.drain_slices.fetch_add(1, Ordering::Relaxed);
2293}
2294
2295/// Called after `SemanticIndex::collect_chunks` has collected one real file batch.
2296pub fn note_semantic_collect(chunks: usize, files: usize, elapsed_ms: u64) {
2297    PERF.semantic_collects.fetch_add(1, Ordering::Relaxed);
2298    PERF.semantic_chunks
2299        .fetch_add(chunks as u64, Ordering::Relaxed);
2300    PERF.semantic_files
2301        .fetch_add(files as u64, Ordering::Relaxed);
2302    PERF.semantic_ms.fetch_add(elapsed_ms, Ordering::Relaxed);
2303}
2304
2305/// Called by `Tier2PhaseTimings::log` after a Tier-2 scan performs measurable work.
2306pub fn note_tier2_scan(category: String, elapsed_ms: u64) {
2307    if let Ok(mut tier2) = PERF.tier2.lock() {
2308        let entry = tier2.entry(category).or_default();
2309        entry.0 = entry.0.saturating_add(1);
2310        entry.1 = entry.1.saturating_add(elapsed_ms);
2311    }
2312}
2313
2314/// Called after watcher-driven callgraph `refresh_files` succeeds for concrete paths.
2315pub fn note_callgraph_invalidations(files: usize) {
2316    PERF.callgraph_invalidations
2317        .fetch_add(files as u64, Ordering::Relaxed);
2318}
2319
2320/// Who made a tool call, which decides how loudly a slow one is logged.
2321#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2322pub enum ToolCallCaller {
2323    /// A tool call made on behalf of the model (an agent-facing tool).
2324    Agent,
2325    /// A background call the plugins make on their own (completion drains,
2326    /// task status polls, permission previews). Nobody waits on these
2327    /// interactively, so a slow one is not worth a warning.
2328    Plumbing,
2329}
2330
2331#[cfg(any(test, feature = "test-support"))]
2332thread_local! {
2333    pub static SLOW_TOOL_CALL_CAPTURE: RefCell<Vec<(log::Level, String)>> =
2334        const { RefCell::new(Vec::new()) };
2335}
2336
2337#[cfg(any(test, feature = "test-support"))]
2338pub fn take_slow_tool_call_logs_for_test() -> Vec<String> {
2339    SLOW_TOOL_CALL_CAPTURE.with(|captured| {
2340        captured
2341            .borrow_mut()
2342            .drain(..)
2343            .map(|(_, message)| message)
2344            .collect()
2345    })
2346}
2347
2348/// Log level for a tool call that exceeded `SLOW_TOOL_CALL_THRESHOLD`.
2349///
2350/// Plugin plumbing calls (completion drains, status polls, detach checks) run
2351/// in the background and made up about half of all slow-call warnings, which
2352/// buried the slow calls an agent actually waited on. They still log at debug
2353/// so a slow drain can be investigated with debug logging on.
2354fn slow_tool_call_level(caller: ToolCallCaller) -> log::Level {
2355    match caller {
2356        ToolCallCaller::Agent => log::Level::Warn,
2357        ToolCallCaller::Plumbing => log::Level::Debug,
2358    }
2359}
2360
2361/// Record a completed subc tool call or provider read for slow-call diagnostics
2362/// and the standing perf-tick window. The writer calls this only after
2363/// `write_all` has handed the complete response frame to the transport.
2364pub fn note_tool_call_trace(
2365    name: &str,
2366    session: &str,
2367    root: &Path,
2368    channel: u16,
2369    corr: u64,
2370    phases: ToolCallPhaseDurations,
2371    caller: ToolCallCaller,
2372) {
2373    let sample = ToolCallPerfSample {
2374        total_ms: duration_millis_u64(phases.total),
2375        queue_ms: duration_millis_u64(phases.queue),
2376    };
2377    if let Ok(mut samples) = PERF.tool_calls.lock() {
2378        if samples.len() == TOOL_CALL_SAMPLE_CAPACITY {
2379            samples.pop_front();
2380        }
2381        samples.push_back(sample);
2382        PERF.tool_call_count.fetch_add(1, Ordering::Relaxed);
2383    }
2384
2385    let waiting_on_build_id = phases.waiting_on_build_id.as_deref().unwrap_or("-");
2386    crate::slog_debug!(
2387        "tool_call phase name={} session={} channel={} corr={} total_ms={:.3} queue_ms={:.3} setup_ms={:.3} translate_ms={:.3} exec_ms={:.3} format_ms={:.3} finalize_ms={:.3} egress_ms={:.3} egress_enqueue_ms={:.3} egress_queue_ms={:.3} egress_prepare_ms={:.3} egress_write_ms={:.3} frame_bytes={} writer_queue_depth={} writer_active={} writer_queue_full={} reserve_timeouts={} waiting_on={} waiting_on_build_id={} wait_ms={} root={}",
2388        name,
2389        session,
2390        channel,
2391        corr,
2392        duration_millis_f64(phases.total),
2393        duration_millis_f64(phases.queue),
2394        duration_millis_f64(phases.setup),
2395        duration_millis_f64(phases.translate),
2396        duration_millis_f64(phases.execute),
2397        duration_millis_f64(phases.format),
2398        duration_millis_f64(phases.finalize),
2399        duration_millis_f64(phases.egress),
2400        duration_millis_f64(phases.egress_enqueue),
2401        duration_millis_f64(phases.egress_queue),
2402        duration_millis_f64(phases.egress_prepare),
2403        duration_millis_f64(phases.egress_write),
2404        phases.frame_bytes,
2405        phases.writer_queue_depth,
2406        phases.writer_active_at_enqueue,
2407        phases.writer_queue_was_full,
2408        phases.writer_reserve_timeouts,
2409        phases.waiting_on.as_str(),
2410        waiting_on_build_id,
2411        phases.wait_ms,
2412        root.display(),
2413    );
2414
2415    // Waiting tools do not separate their requested wait from execution work.
2416    // Exclude that whole phase rather than warning about an intentional wait;
2417    // queueing, translation, formatting and transport delays still warrant a warning.
2418    let diagnostic_elapsed = if phases.intentional_wait {
2419        phases.total.saturating_sub(phases.execute)
2420    } else {
2421        phases.total
2422    };
2423    if diagnostic_elapsed > SLOW_TOOL_CALL_THRESHOLD {
2424        let level = slow_tool_call_level(caller);
2425        // The argument shape and edit phase times go before `root=`, which
2426        // stays last because a root path may contain spaces.
2427        let mut detail = String::new();
2428        if let Some(shape) = phases.arg_shape.as_deref() {
2429            detail.push(' ');
2430            detail.push_str(shape);
2431        }
2432        if let Some(edit_phases) = phases.edit_phases.as_deref() {
2433            detail.push_str(" edit_phases=");
2434            detail.push_str(edit_phases);
2435        }
2436        let message = format!(
2437            "slow tool_call name={} session={} channel={} corr={} total={}ms queue={} setup={} translate={} exec={} format={} finalize={} egress={} egress_enqueue={} egress_queue={} egress_prepare={} egress_write={} frame_bytes={} writer_queue_depth={} writer_active={} writer_queue_full={} reserve_timeouts={} waiting_on={} waiting_on_build_id={} wait_ms={}{} root={}",
2438            name,
2439            session,
2440            channel,
2441            corr,
2442            duration_millis_u64(phases.total),
2443            slow_phase_time(phases.queue, None),
2444            slow_phase_time(phases.setup, phases.cpu.setup),
2445            slow_phase_time(phases.translate, phases.cpu.translate),
2446            slow_phase_time(phases.execute, phases.cpu.execute),
2447            slow_phase_time(phases.format, phases.cpu.format),
2448            slow_phase_time(phases.finalize, phases.cpu.finalize),
2449            slow_phase_time(phases.egress, None),
2450            slow_phase_time(phases.egress_enqueue, None),
2451            slow_phase_time(phases.egress_queue, None),
2452            slow_phase_time(phases.egress_prepare, phases.cpu.egress_prepare),
2453            slow_phase_time(phases.egress_write, None),
2454            phases.frame_bytes,
2455            phases.writer_queue_depth,
2456            phases.writer_active_at_enqueue,
2457            phases.writer_queue_was_full,
2458            phases.writer_reserve_timeouts,
2459            phases.waiting_on.as_str(),
2460            waiting_on_build_id,
2461            phases.wait_ms,
2462            detail,
2463            root.display(),
2464        );
2465        #[cfg(any(test, feature = "test-support"))]
2466        SLOW_TOOL_CALL_CAPTURE
2467            .with(|captured| captured.borrow_mut().push((level, message.clone())));
2468        log::log!(level, "{}{}", crate::log_ctx::session_prefix(), message);
2469    }
2470}
2471
2472fn slow_phase_time(wall: Duration, cpu: Option<Duration>) -> String {
2473    // Fractional milliseconds keep microsecond translation work visible beside
2474    // scheduling delay. Unknown CPU is explicit, not a misleading zero.
2475    match cpu {
2476        Some(cpu) => format!(
2477            "{:.3}ms/cpu={:.3}ms",
2478            duration_millis_f64(wall),
2479            duration_millis_f64(cpu)
2480        ),
2481        None => format!("{:.3}ms/cpu=?", duration_millis_f64(wall)),
2482    }
2483}
2484
2485/// Sample executor liveness and emit one busy-only aggregate at the configured cadence.
2486///
2487/// The transport may call this every loop turn; an atomic deadline keeps all
2488/// executor sampling and reporter locking off that path between drain ticks.
2489pub fn perf_tick<C: ExecutorContext>(executor: Option<&Executor<C>>) {
2490    if !perf_sample_due() {
2491        return;
2492    }
2493
2494    let sample = executor.and_then(|executor| {
2495        executor
2496            .try_dispatch_liveness_snapshot()
2497            .map(|snapshot| ExecutorSample {
2498                interactive_running: snapshot.running.interactive,
2499                maintenance_running: snapshot.running.maintenance,
2500                interactive_queued: snapshot.interactive.queued,
2501                maintenance_queued: snapshot.maintenance.queued,
2502                interactive_oldest_ms: snapshot.interactive.oldest_age_ms,
2503                maintenance_oldest_ms: snapshot.maintenance.oldest_age_ms,
2504            })
2505    });
2506
2507    let completion_counts = executor.map_or((0, 0), Executor::<C>::completion_counts);
2508    report_perf_tick(&PERF, sample, completion_counts);
2509}
2510
2511fn report_perf_tick(
2512    perf: &PerfMetrics,
2513    sample: Option<ExecutorSample>,
2514    completion_counts: (u64, u64),
2515) {
2516    let tool_call_count = perf.tool_call_count.load(Ordering::Relaxed);
2517    let (completed_interactive, completed_maintenance, new_tool_calls) = {
2518        let Ok(mut reporter) = perf.reporter.lock() else {
2519            return;
2520        };
2521        if reporter.last_report.elapsed() < perf_tick_interval() {
2522            return;
2523        }
2524        reporter.last_report = Instant::now();
2525        let completed = (
2526            completion_counts
2527                .0
2528                .saturating_sub(reporter.last_completed_interactive),
2529            completion_counts
2530                .1
2531                .saturating_sub(reporter.last_completed_maintenance),
2532            tool_call_count.saturating_sub(reporter.last_tool_call_count),
2533        );
2534        reporter.last_completed_interactive = completion_counts.0;
2535        reporter.last_completed_maintenance = completion_counts.1;
2536        reporter.last_tool_call_count = tool_call_count;
2537        completed
2538    };
2539
2540    let watcher_ingested = perf.watcher_ingested.swap(0, Ordering::Relaxed);
2541    let watcher_paths = perf.watcher_paths.swap(0, Ordering::Relaxed);
2542    let watcher_dropped = perf.watcher_dropped.swap(0, Ordering::Relaxed);
2543    let drain_slices = perf.drain_slices.swap(0, Ordering::Relaxed);
2544    let semantic_collects = perf.semantic_collects.swap(0, Ordering::Relaxed);
2545    let semantic_files = perf.semantic_files.swap(0, Ordering::Relaxed);
2546    let semantic_chunks = perf.semantic_chunks.swap(0, Ordering::Relaxed);
2547    let semantic_ms = perf.semantic_ms.swap(0, Ordering::Relaxed);
2548    let callgraph_invalidations = perf.callgraph_invalidations.swap(0, Ordering::Relaxed);
2549    let file_lines_dropped = perf.file_lines_dropped.swap(0, Ordering::Relaxed);
2550    let tier2 = perf
2551        .tier2
2552        .lock()
2553        .map(|mut tier2| std::mem::take(&mut *tier2))
2554        .unwrap_or_default();
2555    let tool_calls = perf
2556        .tool_calls
2557        .lock()
2558        .map(|samples| summarize_tool_calls(&samples))
2559        .unwrap_or_default();
2560
2561    let executor_busy = sample.is_some_and(|sample| {
2562        sample.interactive_running > 0
2563            || sample.maintenance_running > 0
2564            || sample.interactive_queued > 0
2565            || sample.maintenance_queued > 0
2566    });
2567    let active = watcher_ingested > 0
2568        || watcher_paths > 0
2569        || watcher_dropped > 0
2570        || semantic_collects > 0
2571        || callgraph_invalidations > 0
2572        || completed_interactive > 0
2573        || completed_maintenance > 0
2574        || new_tool_calls > 0
2575        || file_lines_dropped > 0
2576        || !tier2.is_empty()
2577        || executor_busy;
2578    if !active {
2579        return;
2580    }
2581
2582    let tier2_summary = if tier2.is_empty() {
2583        "none".to_string()
2584    } else {
2585        tier2
2586            .into_iter()
2587            .map(|(category, (count, ms))| format!("{category}:{count}/{ms}ms"))
2588            .collect::<Vec<_>>()
2589            .join(",")
2590    };
2591    let sample = sample.unwrap_or_default();
2592    crate::slog_info!(
2593        "perf tick: watcher={{ingested:{},paths:{},dropped:{}}} drains={} tier2=[{}] semantic={{collects:{},files:{},chunks:{},ms:{}}} callgraph_invalidations={} executor_completed={{interactive:{},maintenance:{}}} oldest_queued_ms={{interactive:{},maintenance:{}}} {} file_log_dropped={}",
2594        watcher_ingested,
2595        watcher_paths,
2596        watcher_dropped,
2597        drain_slices,
2598        tier2_summary,
2599        semantic_collects,
2600        semantic_files,
2601        semantic_chunks,
2602        semantic_ms,
2603        callgraph_invalidations,
2604        completed_interactive,
2605        completed_maintenance,
2606        format_optional_ms(sample.interactive_oldest_ms),
2607        format_optional_ms(sample.maintenance_oldest_ms),
2608        format_tool_call_summary(new_tool_calls, tool_calls),
2609        file_lines_dropped,
2610    );
2611}
2612
2613fn duration_millis_f64(duration: Duration) -> f64 {
2614    duration.as_secs_f64() * 1_000.0
2615}
2616
2617fn duration_millis_u64(duration: Duration) -> u64 {
2618    duration.as_millis().min(u64::MAX as u128) as u64
2619}
2620
2621fn summarize_tool_calls(samples: &VecDeque<ToolCallPerfSample>) -> ToolCallPerfSummary {
2622    if samples.is_empty() {
2623        return ToolCallPerfSummary::default();
2624    }
2625    let mut totals = samples
2626        .iter()
2627        .map(|sample| sample.total_ms)
2628        .collect::<Vec<_>>();
2629    let mut queues = samples
2630        .iter()
2631        .map(|sample| sample.queue_ms)
2632        .collect::<Vec<_>>();
2633    totals.sort_unstable();
2634    queues.sort_unstable();
2635    let median_index = (samples.len() - 1) / 2;
2636    ToolCallPerfSummary {
2637        window: samples.len(),
2638        p50_total_ms: totals[median_index],
2639        max_total_ms: totals[totals.len() - 1],
2640        p50_queue_ms: queues[median_index],
2641        max_queue_ms: queues[queues.len() - 1],
2642    }
2643}
2644
2645fn format_tool_call_summary(new_tool_calls: u64, summary: ToolCallPerfSummary) -> String {
2646    format!(
2647        "toolcall={{new:{new_tool_calls},window:{},p50_total_ms:{},max_total_ms:{},p50_queue_ms:{},max_queue_ms:{}}}",
2648        summary.window,
2649        summary.p50_total_ms,
2650        summary.max_total_ms,
2651        summary.p50_queue_ms,
2652        summary.max_queue_ms,
2653    )
2654}
2655
2656fn format_optional_ms(value: Option<u64>) -> String {
2657    value
2658        .map(|value| value.to_string())
2659        .unwrap_or_else(|| "none".to_string())
2660}
2661
2662fn perf_sample_due() -> bool {
2663    static ORIGIN: LazyLock<Instant> = LazyLock::new(Instant::now);
2664    let now_ns = ORIGIN.elapsed().as_nanos().min(u64::MAX as u128) as u64;
2665    let mut deadline = PERF.next_sample_ns.load(Ordering::Relaxed);
2666    loop {
2667        if now_ns < deadline {
2668            return false;
2669        }
2670        let next = now_ns.saturating_add(PERF_SAMPLE_INTERVAL.as_nanos() as u64);
2671        match PERF.next_sample_ns.compare_exchange_weak(
2672            deadline,
2673            next,
2674            Ordering::Relaxed,
2675            Ordering::Relaxed,
2676        ) {
2677            Ok(_) => return true,
2678            Err(observed) => deadline = observed,
2679        }
2680    }
2681}
2682
2683fn perf_tick_interval() -> Duration {
2684    static INTERVAL: OnceLock<Duration> = OnceLock::new();
2685    *INTERVAL.get_or_init(|| {
2686        std::env::var("AFT_PERF_TICK_INTERVAL_MS")
2687            .ok()
2688            .and_then(|value| value.parse::<u64>().ok())
2689            .filter(|value| *value > 0)
2690            .map(Duration::from_millis)
2691            .unwrap_or(DEFAULT_PERF_TICK_INTERVAL)
2692    })
2693}
2694
2695#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2696pub enum RescanReason {
2697    BufferOverflow,
2698    KernelDropped,
2699    UserDropped,
2700    Unknown,
2701}
2702
2703impl RescanReason {
2704    pub fn as_str(self) -> &'static str {
2705        match self {
2706            Self::BufferOverflow => "buffer_overflow",
2707            Self::KernelDropped => "kernel_dropped",
2708            Self::UserDropped => "user_dropped",
2709            Self::Unknown => "unknown",
2710        }
2711    }
2712}
2713
2714impl RescanReason {
2715    pub fn from_event_info(info: Option<&str>) -> Self {
2716        match info {
2717            Some("rescan: buffer overflow") => Self::BufferOverflow,
2718            Some("rescan: kernel dropped") => Self::KernelDropped,
2719            Some("rescan: user dropped") => Self::UserDropped,
2720            _ => Self::Unknown,
2721        }
2722    }
2723}
2724
2725#[cfg(any(test, feature = "test-support"))]
2726#[cfg_attr(not(test), allow(dead_code, unused_imports))]
2727pub mod tests {
2728
2729    use super::*;
2730
2731    #[cfg(test)]
2732    use filetime::set_file_mtime;
2733    #[cfg(test)]
2734    use filetime::FileTime;
2735    use tempfile::TempDir;
2736    #[test]
2737    fn watchdog_append_bypasses_held_logger_control_and_follows_rotation() {
2738        let dir = tempfile::tempdir().unwrap();
2739        let path = dir.path().join("watchdog.log");
2740        let control = super::FILE_CONTROL.lock().unwrap();
2741        super::write_watchdog_line(
2742            &path,
2743            "stall watchdog: stall detected marker=subc_frame_loop",
2744        )
2745        .unwrap();
2746        let rotated = dir.path().join("watchdog.log.1");
2747        std::fs::rename(&path, &rotated).unwrap();
2748        super::write_watchdog_line(&path, "stall watchdog: exit deferred because paging").unwrap();
2749        super::write_watchdog_line(
2750            &path,
2751            "stall watchdog: exiting Authorization: Bearer terminal-secret-value",
2752        )
2753        .unwrap();
2754        drop(control);
2755        let old = std::fs::read_to_string(rotated).unwrap();
2756        let current = std::fs::read_to_string(path).unwrap();
2757        assert!(old.contains("stall detected"));
2758        assert!(!old.contains("exit deferred"));
2759        assert_eq!(current.lines().count(), 2);
2760        assert!(current.contains("exit deferred because paging"));
2761        assert!(current.contains("stall watchdog: exiting"));
2762        assert!(!current.contains("terminal-secret-value"));
2763        assert!(current.contains(crate::log_redact::SECRET_PLACEHOLDER));
2764    }
2765
2766    #[test]
2767    fn gh_shim_preinit_warning_is_durable_and_file_only() {
2768        let dir = tempfile::tempdir().unwrap();
2769        let path = dir.path().join("logs").join("aft-shim.log");
2770        super::write_preinit_warning_to(&path, "gh speech snapshot invalid: first").unwrap();
2771        super::write_preinit_warning_to(&path, "gh speech snapshot invalid: second").unwrap();
2772        let text = std::fs::read_to_string(path).unwrap();
2773        let lines: Vec<_> = text.lines().collect();
2774        assert_eq!(lines.len(), 2);
2775        assert!(lines[0].ends_with(" [aft] WARN gh speech snapshot invalid: first"));
2776        assert!(lines[1].ends_with(" [aft] WARN gh speech snapshot invalid: second"));
2777    }
2778
2779    #[test]
2780    fn terminal_sync_redacts_both_sinks() {
2781        let directory = tempfile::tempdir().unwrap();
2782        let path = directory.path().join("terminal.log");
2783        let sink = super::RotatingFile::unopened(path.clone(), 1024, 1, 1);
2784        let mut stderr = Vec::new();
2785        super::write_terminal_line(
2786            &sink,
2787            &mut stderr,
2788            "Authorization: Bearer terminal-secret-value",
2789        )
2790        .unwrap();
2791        let file = std::fs::read(&path).unwrap();
2792        assert_eq!(file, stderr);
2793        let line = String::from_utf8(file).unwrap();
2794        assert!(!line.contains("terminal-secret-value"), "{line}");
2795        assert!(
2796            line.contains(crate::log_redact::SECRET_PLACEHOLDER),
2797            "{line}"
2798        );
2799    }
2800
2801    fn isolated_subc_stderr(test_name: &str, body: impl FnOnce()) {
2802        // libtest's exact names omit the crate prefix from module_path!().
2803        let test_name = test_name.split_once("::").unwrap().1;
2804        const PROBE: &str = "AFT_TEST_LOGGING_STDERR_CHILD";
2805        if std::env::var(PROBE).ok().as_deref() == Some(test_name) {
2806            super::init_subc();
2807            body();
2808            return;
2809        }
2810        let output = std::process::Command::new(std::env::current_exe().unwrap())
2811            .args(["--exact", test_name, "--nocapture", "--color=never"])
2812            .env(PROBE, test_name)
2813            .env("RUST_LOG", "off")
2814            .output()
2815            .unwrap();
2816        assert!(
2817            output.status.success()
2818                && String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed"),
2819            "stderr child failed: stdout={:?} stderr={:?}",
2820            String::from_utf8_lossy(&output.stdout),
2821            String::from_utf8_lossy(&output.stderr)
2822        );
2823    }
2824
2825    fn hold_stderr() -> (mpsc::Sender<()>, thread::JoinHandle<()>) {
2826        let (held_tx, held_rx) = mpsc::channel();
2827        let (release_tx, release_rx) = mpsc::channel();
2828        let holder = thread::spawn(move || {
2829            let stderr = io::stderr();
2830            let _held = stderr.lock();
2831            held_tx.send(()).unwrap();
2832            let _ = release_rx.recv_timeout(Duration::from_secs(5));
2833        });
2834        held_rx.recv_timeout(Duration::from_secs(5)).unwrap();
2835        (release_tx, holder)
2836    }
2837
2838    #[test]
2839    fn subc_file_writer_warning_does_not_wait_for_stderr() {
2840        isolated_subc_stderr(
2841            concat!(
2842                module_path!(),
2843                "::subc_file_writer_warning_does_not_wait_for_stderr"
2844            ),
2845            || {
2846                struct ReconfigureFault(Arc<Mutex<Vec<u8>>>);
2847                impl FileLogSink for ReconfigureFault {
2848                    fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
2849                        for line in lines {
2850                            self.0.lock().unwrap().extend_from_slice(line);
2851                        }
2852                        Ok(())
2853                    }
2854                    fn reopen(&mut self) -> io::Result<()> {
2855                        Ok(())
2856                    }
2857                    fn discard_buffer(&mut self) {}
2858                    fn reconfigure(&mut self, _: &Path) -> io::Result<SweepSummary> {
2859                        Err(io::Error::other("injected reconfigure failure"))
2860                    }
2861                }
2862                let output = Arc::new(Mutex::new(Vec::new()));
2863                let sink = Arc::new(Mutex::new(Some(ReconfigureFault(Arc::clone(&output)))));
2864                let (tx, rx) = mpsc::sync_channel(4);
2865                let (release, holder) = hold_stderr();
2866                let worker = thread::spawn(move || {
2867                    run_file_writer(
2868                        sink,
2869                        rx,
2870                        Arc::new(LogWriteHealth::default()),
2871                        Duration::ZERO,
2872                    )
2873                });
2874                tx.send(LogMessage::Reconfigure(PathBuf::from("injected-log-root")))
2875                    .unwrap();
2876                tx.send(LogMessage::Write(b"after warning\n".to_vec()))
2877                    .unwrap();
2878                let (done, completed) = mpsc::sync_channel(1);
2879                tx.send(LogMessage::Flush(done)).unwrap();
2880                let progressed = completed.recv_timeout(Duration::from_secs(1));
2881                let _ = release.send(());
2882                holder.join().unwrap();
2883                drop(tx);
2884                worker.join().unwrap();
2885                assert_eq!(
2886                    progressed.ok(),
2887                    Some(true),
2888                    "file writer warning waited on stderr"
2889                );
2890                assert_eq!(&*output.lock().unwrap(), b"after warning\n");
2891            },
2892        );
2893    }
2894
2895    #[test]
2896    fn subc_terminal_mirror_does_not_wait_for_stderr() {
2897        isolated_subc_stderr(
2898            concat!(
2899                module_path!(),
2900                "::subc_terminal_mirror_does_not_wait_for_stderr"
2901            ),
2902            || {
2903                let directory = tempfile::tempdir().unwrap();
2904                let tx = FILE_CONTROL.lock().unwrap().tx.clone().unwrap();
2905                tx.send(LogMessage::Reconfigure(directory.path().to_path_buf()))
2906                    .unwrap();
2907                assert!(writer_barrier(&tx));
2908                let (release, holder) = hold_stderr();
2909                let (done, completed) = mpsc::channel();
2910                let caller = thread::spawn(move || {
2911                    let _ = done.send(write_terminal_log_sync("held-terminal-stderr-probe"));
2912                });
2913                // stderr stays held until after this wait, so a write that
2914                // waited on it would time out here; the budget is generous
2915                // because a loaded Windows runner can take over a second to
2916                // persist the line.
2917                let result = completed.recv_timeout(Duration::from_secs(30));
2918                let _ = release.send(());
2919                holder.join().unwrap();
2920                caller.join().unwrap();
2921                assert!(
2922                    matches!(result, Ok(Ok(()))),
2923                    "terminal stderr blocked persistence: {result:?}"
2924                );
2925                let file = directory
2926                    .path()
2927                    .join("logs")
2928                    .join(format!("aft-{}.log", std::process::id()));
2929                assert!(fs::read_to_string(file)
2930                    .unwrap()
2931                    .contains("held-terminal-stderr-probe"));
2932            },
2933        );
2934    }
2935
2936    #[test]
2937    fn tee_and_process_diagnostics_cannot_bypass_transport_stderr_policy() {
2938        let source = include_str!("logging.rs");
2939        let tee = source
2940            .split_once("impl Write for TeeWriter {")
2941            .unwrap()
2942            .1
2943            .split_once("fn enqueue_file_line(")
2944            .unwrap()
2945            .0;
2946        assert!(tee.contains("self.stderr.write_all"));
2947        assert!(tee.contains("self.stderr.flush"));
2948        assert!(!tee.contains("io::stderr"));
2949        let diagnostics = source
2950            .split_once("fn write_stderr_once(")
2951            .unwrap()
2952            .1
2953            .split_once("pub fn flush_durable_log(")
2954            .unwrap()
2955            .0;
2956        assert!(diagnostics.contains("StderrOutput::for_process()"));
2957        assert!(!diagnostics.contains("io::stderr"));
2958        let terminal = source
2959            .split_once("pub fn write_terminal_log_sync(")
2960            .unwrap()
2961            .1
2962            .split_once("fn write_terminal_line(")
2963            .unwrap()
2964            .0;
2965        assert!(terminal.contains("StderrOutput::for_process()"));
2966        assert!(!terminal.contains("io::stderr"));
2967    }
2968
2969    #[test]
2970    fn blocked_stderr_does_not_stop_redacted_file_logging_or_health() {
2971        struct Gate {
2972            entered: Option<mpsc::Sender<()>>,
2973            release: mpsc::Receiver<()>,
2974            bytes: Arc<Mutex<Vec<u8>>>,
2975        }
2976        impl Write for Gate {
2977            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2978                if let Some(entered) = self.entered.take() {
2979                    entered.send(()).unwrap();
2980                    let _ = self.release.recv_timeout(Duration::from_secs(5));
2981                }
2982                self.bytes.lock().unwrap().extend_from_slice(bytes);
2983                Ok(bytes.len())
2984            }
2985            fn flush(&mut self) -> io::Result<()> {
2986                Ok(())
2987            }
2988        }
2989        let dir = tempfile::tempdir().unwrap();
2990        let path = dir.path().join("mirror-independent.log");
2991        let sink = RotatingFile::open(path.clone(), 1024 * 1024, 1, 1).unwrap();
2992        let (file_tx, file_rx) = mpsc::sync_channel(8);
2993        let file_worker = thread::spawn(move || {
2994            run_file_writer(
2995                Arc::new(Mutex::new(Some(sink))),
2996                file_rx,
2997                Arc::new(LogWriteHealth::default()),
2998                Duration::ZERO,
2999            )
3000        });
3001        let health = Arc::new(stderr_mirror::MirrorHealth::default());
3002        let bytes = Arc::new(Mutex::new(Vec::new()));
3003        let (entered_tx, entered_rx) = mpsc::channel();
3004        let (release_tx, release_rx) = mpsc::channel();
3005        let (mirror, stderr_worker) = stderr_mirror::Mirror::spawn(
3006            Gate {
3007                entered: Some(entered_tx),
3008                release: release_rx,
3009                bytes: Arc::clone(&bytes),
3010            },
3011            1,
3012            Arc::clone(&health),
3013        )
3014        .unwrap();
3015        let mut tee = TeeWriter {
3016            file_tx: Some(file_tx.clone()),
3017            stderr: StderrOutput::Subc(mirror),
3018        };
3019        tee.write_all(b"Authorization: Bearer mirror-secret-value\n")
3020            .unwrap();
3021        entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
3022        let start = Instant::now();
3023        tee.write_all(b"Authorization: Bearer second-secret-value\n")
3024            .unwrap();
3025        tee.write_all(b"third\n").unwrap();
3026        tee.flush().unwrap();
3027        let snapshot = health.snapshot();
3028        let elapsed = start.elapsed();
3029        let file_progressed = writer_barrier(&file_tx);
3030        let file = fs::read(&path).unwrap();
3031        let _ = release_tx.send(());
3032        drop(tee);
3033        drop(file_tx);
3034        stderr_worker.join().unwrap();
3035        file_worker.join().unwrap();
3036        assert!(elapsed < Duration::from_secs(1));
3037        assert!(file_progressed, "file writer waited on stderr");
3038        assert_eq!(snapshot["dropped_lines_total"], 1);
3039        assert_eq!(snapshot["dropped_flushes_total"], 1);
3040        let file = String::from_utf8(file).unwrap();
3041        let mirrored = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
3042        for output in [&file, &mirrored] {
3043            assert!(!output.contains("mirror-secret-value"), "{output}");
3044            assert!(!output.contains("second-secret-value"), "{output}");
3045            assert!(
3046                output.contains(crate::log_redact::SECRET_PLACEHOLDER),
3047                "{output}"
3048            );
3049        }
3050        assert!(file.ends_with("third\n"));
3051        assert!(!mirrored.contains("third"));
3052    }
3053
3054    #[derive(Clone, Copy, PartialEq, Eq)]
3055    enum SinkFault {
3056        None,
3057        Write,
3058        Flush,
3059        Open,
3060    }
3061
3062    struct SinkProbe {
3063        fault: SinkFault,
3064        output: Vec<u8>,
3065        opens: usize,
3066        writes: usize,
3067        flushes: usize,
3068    }
3069
3070    struct FaultWriter {
3071        probe: Arc<Mutex<SinkProbe>>,
3072        pending: Vec<u8>,
3073    }
3074
3075    impl Write for FaultWriter {
3076        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
3077            let mut probe = self.probe.lock().unwrap();
3078            probe.writes += 1;
3079            if probe.fault == SinkFault::Write {
3080                return Err(io::Error::other("No space left on device (injected write)"));
3081            }
3082            self.pending.extend_from_slice(bytes);
3083            Ok(bytes.len())
3084        }
3085
3086        fn flush(&mut self) -> io::Result<()> {
3087            let mut probe = self.probe.lock().unwrap();
3088            probe.flushes += 1;
3089            if probe.fault == SinkFault::Flush {
3090                return Err(io::Error::other("No space left on device (injected flush)"));
3091            }
3092            probe.output.append(&mut self.pending);
3093            Ok(())
3094        }
3095    }
3096
3097    struct FaultSink {
3098        probe: Arc<Mutex<SinkProbe>>,
3099        writer: Option<BufWriter<FaultWriter>>,
3100        write_gate: Option<(SyncSender<()>, mpsc::Receiver<()>)>,
3101    }
3102
3103    impl FaultSink {
3104        fn new(fault: SinkFault) -> Self {
3105            let probe = Arc::new(Mutex::new(SinkProbe {
3106                fault,
3107                output: Vec::new(),
3108                opens: 0,
3109                writes: 0,
3110                flushes: 0,
3111            }));
3112            Self {
3113                writer: Some(BufWriter::new(FaultWriter {
3114                    probe: Arc::clone(&probe),
3115                    pending: Vec::new(),
3116                })),
3117                probe,
3118                write_gate: None,
3119            }
3120        }
3121    }
3122
3123    impl FileLogSink for FaultSink {
3124        fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
3125            if let Some((entered, proceed)) = self.write_gate.take() {
3126                entered.send(()).unwrap();
3127                proceed.recv().unwrap();
3128            }
3129            let writer = self.writer.as_mut().expect("sink must reopen before retry");
3130            for line in lines {
3131                writer.write_all(line)?;
3132            }
3133            writer.flush()
3134        }
3135
3136        fn reopen(&mut self) -> io::Result<()> {
3137            self.discard_buffer();
3138            let mut probe = self.probe.lock().unwrap();
3139            probe.opens += 1;
3140            if probe.fault == SinkFault::Open {
3141                return Err(io::Error::other("bad handle (injected reopen)"));
3142            }
3143            self.writer = Some(BufWriter::new(FaultWriter {
3144                probe: Arc::clone(&self.probe),
3145                pending: Vec::new(),
3146            }));
3147            Ok(())
3148        }
3149
3150        fn discard_buffer(&mut self) {
3151            if let Some(writer) = self.writer.take() {
3152                let _ = writer.into_parts();
3153            }
3154        }
3155
3156        fn reconfigure(&mut self, _root: &Path) -> io::Result<SweepSummary> {
3157            unreachable!("this test never reconfigures storage")
3158        }
3159    }
3160
3161    fn writer_barrier(tx: &SyncSender<LogMessage>) -> bool {
3162        let (done, reply) = mpsc::sync_channel(1);
3163        tx.send(LogMessage::Flush(done))
3164            .expect("writer still running");
3165        reply
3166            .recv_timeout(Duration::from_secs(5))
3167            .expect("writer must survive a failed log write and answer flush requests")
3168    }
3169
3170    #[test]
3171    fn file_writer_recovers_after_write_and_flush_errors() {
3172        for fault in [SinkFault::Write, SinkFault::Flush] {
3173            let sink = FaultSink::new(fault);
3174            let probe = Arc::clone(&sink.probe);
3175            let shared = Arc::new(Mutex::new(Some(sink)));
3176            let health = Arc::new(LogWriteHealth::default());
3177            let (tx, rx) = mpsc::sync_channel(8);
3178            let worker_health = Arc::clone(&health);
3179            let worker = thread::spawn(move || {
3180                run_file_writer(shared, rx, worker_health, Duration::ZERO);
3181            });
3182
3183            tx.send(LogMessage::Write(b"lost one\nlost two\n".to_vec()))
3184                .unwrap();
3185            assert!(
3186                !writer_barrier(&tx),
3187                "failed writes cannot confirm durability"
3188            );
3189            let failed = health.snapshot();
3190            assert_eq!(failed["dropped_lines_total"], 2);
3191            assert!(failed["last_write_error"]
3192                .as_str()
3193                .unwrap()
3194                .contains("No space left on device"));
3195            let since = failed["failing_since"].as_str().unwrap();
3196
3197            // Opening the replacement handle can fail as well. It must not
3198            // terminate the worker or erase the original outage's start time.
3199            probe.lock().unwrap().fault = SinkFault::Open;
3200            tx.send(LogMessage::Write(b"lost three\n".to_vec()))
3201                .unwrap();
3202            assert!(!writer_barrier(&tx));
3203            assert_eq!(health.snapshot()["dropped_lines_total"], 3);
3204            assert_eq!(health.snapshot()["failing_since"], since);
3205
3206            probe.lock().unwrap().fault = SinkFault::None;
3207            tx.send(LogMessage::Write(b"recovered\n".to_vec())).unwrap();
3208            assert!(writer_barrier(&tx));
3209            tx.send(LogMessage::Write(b"still logging\n".to_vec()))
3210                .unwrap();
3211            assert!(writer_barrier(&tx));
3212            drop(tx);
3213            worker.join().unwrap();
3214
3215            let probe = probe.lock().unwrap();
3216            let output = String::from_utf8(probe.output.clone()).unwrap();
3217            let lines: Vec<_> = output.lines().collect();
3218            assert_eq!(lines.len(), 3, "no replay of lost buffers: {output}");
3219            assert!(
3220                lines[0].contains(&format!("log writes failed from {since} to ")),
3221                "{output}"
3222            );
3223            assert!(lines[0].contains("3 lines dropped"), "{output}");
3224            assert!(
3225                lines[0].contains("bad handle (injected reopen)"),
3226                "{output}"
3227            );
3228            assert_eq!(lines[1], "recovered");
3229            assert_eq!(lines[2], "still logging");
3230            assert_eq!(probe.opens, 2);
3231            let recovered = health.snapshot();
3232            assert_eq!(recovered["dropped_lines_total"], 3);
3233            assert!(recovered["failing_since"].is_null());
3234            assert_eq!(
3235                recovered["last_write_error"],
3236                "bad handle (injected reopen)"
3237            );
3238        }
3239    }
3240
3241    #[test]
3242    fn log_write_retries_back_off_without_sleeping_or_replaying_lost_lines() {
3243        let mut sink = FaultSink::new(SinkFault::Write);
3244        let health = Arc::new(LogWriteHealth::default());
3245        let mut recovery = LogWriteRecovery::new(Arc::clone(&health), LOG_WRITE_RETRY_MIN);
3246        let now = Instant::now();
3247        assert!(!recovery.write_batch(&mut sink, &line("lost one"), now));
3248        let writes = sink.probe.lock().unwrap().writes;
3249        assert!(!recovery.write_batch(
3250            &mut sink,
3251            &line("lost two"),
3252            now + Duration::from_millis(999)
3253        ));
3254        assert_eq!(sink.probe.lock().unwrap().writes, writes);
3255        assert_eq!(sink.probe.lock().unwrap().opens, 0);
3256
3257        sink.probe.lock().unwrap().fault = SinkFault::Open;
3258        assert!(!recovery.write_batch(
3259            &mut sink,
3260            &line("lost three"),
3261            now + Duration::from_secs(1)
3262        ));
3263        assert_eq!(sink.probe.lock().unwrap().opens, 1);
3264        assert!(!recovery.write_batch(
3265            &mut sink,
3266            &line("lost four"),
3267            now + Duration::from_millis(2999)
3268        ));
3269        assert_eq!(
3270            sink.probe.lock().unwrap().opens,
3271            1,
3272            "reopen failures also back off"
3273        );
3274
3275        sink.probe.lock().unwrap().fault = SinkFault::None;
3276        assert!(recovery.write_batch(&mut sink, &line("recovered"), now + Duration::from_secs(3)));
3277        let output = String::from_utf8(sink.probe.lock().unwrap().output.clone()).unwrap();
3278        assert!(
3279            output.lines().next().unwrap().contains("4 lines dropped"),
3280            "{output}"
3281        );
3282        assert!(output.ends_with("\nrecovered\n"), "{output}");
3283        assert_eq!(health.snapshot()["dropped_lines_total"], 4);
3284        assert_eq!(recovery.retry_delay, LOG_WRITE_RETRY_MIN);
3285
3286        // Repeated failures must reach a ceiling, not a busy retry loop or an
3287        // unbounded delay that effectively disables the log again.
3288        sink.probe.lock().unwrap().fault = SinkFault::Write;
3289        let mut next = now + Duration::from_secs(4);
3290        for _ in 0..10 {
3291            assert!(!recovery.write_batch(&mut sink, &line("lost again"), next));
3292            next = recovery.outage.as_ref().unwrap().retry_at;
3293        }
3294        assert_eq!(recovery.retry_delay, LOG_WRITE_RETRY_MAX);
3295        assert_eq!(
3296            next.duration_since(now + Duration::from_secs(4)),
3297            Duration::from_secs(181)
3298        );
3299    }
3300
3301    #[test]
3302    fn log_callers_and_health_do_not_wait_for_a_stalled_sink_or_full_queue() {
3303        let mut sink = FaultSink::new(SinkFault::Write);
3304        let (entered, entering) = mpsc::sync_channel(1);
3305        let (proceed, proceeding) = mpsc::sync_channel(1);
3306        sink.write_gate = Some((entered, proceeding));
3307        let shared = Arc::new(Mutex::new(Some(sink)));
3308        let health = Arc::new(LogWriteHealth::default());
3309        let (tx, rx) = mpsc::sync_channel(1);
3310        let worker_health = Arc::clone(&health);
3311        let worker =
3312            thread::spawn(move || run_file_writer(shared, rx, worker_health, Duration::ZERO));
3313        tx.send(LogMessage::Write(b"in flight\n".to_vec())).unwrap();
3314        entering
3315            .recv_timeout(Duration::from_secs(5))
3316            .expect("worker entered sink I/O");
3317
3318        let caller_health = Arc::clone(&health);
3319        let caller_tx = tx.clone();
3320        let (finished, finishing) = mpsc::sync_channel(1);
3321        let caller = thread::spawn(move || {
3322            let mut tx = Some(caller_tx);
3323            enqueue_file_line(&mut tx, b"queued\n", &caller_health);
3324            enqueue_file_line(&mut tx, b"queue full one\n", &caller_health);
3325            enqueue_file_line(&mut tx, b"queue full two\n", &caller_health);
3326            finished.send(caller_health.snapshot()).unwrap();
3327        });
3328        let while_stalled = finishing
3329            .recv_timeout(Duration::from_secs(5))
3330            .expect("log caller and health must finish while sink I/O is still stalled");
3331        assert_eq!(while_stalled["dropped_lines_total"], 2);
3332        proceed.send(()).unwrap();
3333        caller.join().unwrap();
3334        assert!(!writer_barrier(&tx));
3335        drop(tx);
3336        worker.join().unwrap();
3337        assert_eq!(health.snapshot()["dropped_lines_total"], 4);
3338    }
3339
3340    #[test]
3341    // Unix only: the fault is staged by renaming the log directory while the
3342    // sink holds a file open in it, which Windows refuses (Access is denied).
3343    // The injected-sink tests cover the same recovery path on every platform.
3344    #[cfg(unix)]
3345    fn file_log_reopens_after_rotation_loses_its_handle() {
3346        let temp = TempDir::new().unwrap();
3347        let logs = temp.path().join("logs");
3348        create_private_log_dir(&logs).unwrap();
3349        let path = logs.join("aft-777.log");
3350        let mut sink = RotatingFile::open(path.clone(), 100, 1, 1).unwrap();
3351        sink.write_batch(&line("before outage")).unwrap();
3352        let health = Arc::new(LogWriteHealth::default());
3353        let mut recovery = LogWriteRecovery::new(Arc::clone(&health), Duration::ZERO);
3354
3355        // A regular file at the directory path makes rotation fail after it
3356        // takes the active handle, with no reliance on disk usage or modes.
3357        let moved = temp.path().join("moved-logs");
3358        fs::rename(&logs, &moved).unwrap();
3359        fs::write(&logs, b"not a directory").unwrap();
3360        assert!(!recovery.write_batch(&mut sink, &line(&"x".repeat(101)), Instant::now()));
3361        assert!(sink.writer.is_none());
3362        fs::remove_file(&logs).unwrap();
3363        fs::rename(&moved, &logs).unwrap();
3364        // Do not rotate again: examine the original file's append ordering.
3365        sink.threshold = LOG_FILE_BYTES;
3366        assert!(recovery.write_batch(&mut sink, &line("after outage"), Instant::now()));
3367        let output = fs::read_to_string(path).unwrap();
3368        let lines: Vec<_> = output.lines().collect();
3369        assert_eq!(lines.len(), 3, "{output}");
3370        assert_eq!(lines[0], "before outage");
3371        assert!(lines[1].contains("1 lines dropped"), "{output}");
3372        assert_eq!(lines[2], "after outage");
3373        assert_eq!(health.snapshot()["dropped_lines_total"], 1);
3374    }
3375
3376    #[test]
3377    fn file_log_recovers_when_initial_open_failed() {
3378        let temp = TempDir::new().unwrap();
3379        let logs = temp.path().join("logs");
3380        fs::write(&logs, b"not a directory").unwrap();
3381        let path = logs.join("aft-777.log");
3382        let health = Arc::new(LogWriteHealth::default());
3383        let (mut sink, summary) = initial_file_sink(&logs, &path, Arc::clone(&health));
3384        assert!(summary.is_none());
3385        assert!(sink.writer.is_none());
3386        assert!(health.snapshot()["last_write_error"].is_string());
3387        let mut recovery = LogWriteRecovery::new(Arc::clone(&health), Duration::ZERO);
3388        assert!(!recovery.write_batch(&mut sink, &line("lost startup line"), Instant::now()));
3389        fs::remove_file(&logs).unwrap();
3390        assert!(recovery.write_batch(&mut sink, &line("startup recovered"), Instant::now()));
3391        let output = fs::read_to_string(path).unwrap();
3392        assert!(
3393            output.lines().next().unwrap().contains("1 lines dropped"),
3394            "{output}"
3395        );
3396        assert!(output.ends_with("\nstartup recovered\n"), "{output}");
3397        assert!(health.snapshot()["failing_since"].is_null());
3398    }
3399
3400    #[test]
3401    fn panic_hook_child_probe() {
3402        if std::env::var_os("AFT_TEST_PANIC_LOG_CHILD").is_none() {
3403            return;
3404        }
3405        let path = crate::storage_path::storage_dir(None)
3406            .join("logs")
3407            .join(format!("aft-{}.log", std::process::id()));
3408        let previous = std::panic::take_hook();
3409        std::panic::set_hook(Box::new(move |info| {
3410            let persisted =
3411                fs::read_to_string(&path).is_ok_and(|text| text.contains("forced backtrace:"));
3412            eprintln!("panic diagnostic persisted before previous hook: {persisted}");
3413            previous(info);
3414        }));
3415        init();
3416        let backtrace_env = std::env::var_os("RUST_BACKTRACE");
3417        let panic = std::panic::catch_unwind(|| panic!("durable panic diagnostic probe"));
3418        assert!(panic.is_err());
3419        assert_eq!(std::env::var_os("RUST_BACKTRACE"), backtrace_env);
3420        // No writer flush or destructor: exercise persistence before an abrupt
3421        // daemon exit, not merely a diagnostic still queued in memory.
3422        std::process::exit(0);
3423    }
3424
3425    #[test]
3426    fn panic_hook_preserves_default_backtrace_behavior_and_persists() {
3427        for backtrace in [None, Some("0"), Some("1"), Some("full")] {
3428            let storage = TempDir::new().unwrap();
3429            let mut child = std::process::Command::new(std::env::current_exe().unwrap());
3430            child
3431                .args([
3432                    "--exact",
3433                    "logging::tests::panic_hook_child_probe",
3434                    "--nocapture",
3435                ])
3436                .env("AFT_TEST_PANIC_LOG_CHILD", "1")
3437                .env("AFT_STORAGE_DIR", storage.path())
3438                .env("RUST_LOG", "off")
3439                .env_remove("RUST_BACKTRACE");
3440            if let Some(value) = backtrace {
3441                child.env("RUST_BACKTRACE", value);
3442            }
3443            let output = child.output().unwrap();
3444            let stderr = String::from_utf8_lossy(&output.stderr);
3445            assert!(output.status.success(), "child failed: {stderr}");
3446            let paths = fs::read_dir(storage.path().join("logs")).unwrap();
3447            let log = paths
3448                .map(|entry| fs::read_to_string(entry.unwrap().path()).unwrap())
3449                .collect::<String>();
3450            assert!(log.contains("durable panic diagnostic probe"), "{log}");
3451            assert!(log.contains("forced backtrace:"), "{log}");
3452            assert!(log.contains("panic_hook_child_probe"), "{log}");
3453            assert!(stderr.contains("panic diagnostic persisted before previous hook: true"));
3454            assert!(stderr.contains("durable panic diagnostic probe"));
3455            assert_eq!(
3456                stderr.contains("stack backtrace:"),
3457                matches!(backtrace, Some("1" | "full")),
3458                "RUST_BACKTRACE={backtrace:?}: {stderr}"
3459            );
3460            if backtrace == Some("full") {
3461                assert!(
3462                    stderr.contains("0x"),
3463                    "default full backtrace was lost: {stderr}"
3464                );
3465            }
3466        }
3467    }
3468
3469    #[test]
3470    fn panic_diagnostic_text_is_bounded_at_utf8_boundaries() {
3471        let enormous = "é🚀".repeat(PANIC_BACKTRACE_BYTES);
3472        for budget in [PANIC_MESSAGE_BYTES, PANIC_BACKTRACE_BYTES] {
3473            let text = bounded_panic_text(format_args!("{enormous}"), budget);
3474            assert!(text.len() <= budget);
3475            assert!(text.ends_with(PANIC_TRUNCATION));
3476            assert!(text.starts_with("é🚀"));
3477        }
3478        assert_eq!(
3479            bounded_panic_text(format_args!("small"), PANIC_MESSAGE_BYTES),
3480            "small"
3481        );
3482    }
3483
3484    pub fn line(value: &str) -> Vec<Vec<u8>> {
3485        vec![format!("{value}\n").into_bytes()]
3486    }
3487
3488    fn render_log_line(level: log::Level, target: &str, message: &str) -> String {
3489        let mut out = Vec::new();
3490        write_log_line(
3491            &mut out,
3492            "2026-09-26T10:00:00Z",
3493            level,
3494            target,
3495            &format_args!("{message}"),
3496        )
3497        .unwrap();
3498        String::from_utf8(out).unwrap()
3499    }
3500
3501    #[test]
3502    fn log_lines_carry_their_level_after_the_tag() {
3503        assert_eq!(
3504            render_log_line(log::Level::Warn, "aft::subc", "slow tool_call name=read"),
3505            "2026-09-26T10:00:00Z [aft] WARN slow tool_call name=read\n"
3506        );
3507        assert_eq!(
3508            render_log_line(log::Level::Error, "aft::lsp::client", "server crashed"),
3509            "2026-09-26T10:00:00Z [aft-lsp] ERROR server crashed\n"
3510        );
3511        assert_eq!(
3512            render_log_line(log::Level::Info, "aft", "started"),
3513            "2026-09-26T10:00:00Z [aft] INFO started\n"
3514        );
3515        assert_eq!(
3516            render_log_line(log::Level::Debug, "aft_lsp", "x"),
3517            "2026-09-26T10:00:00Z [aft-lsp] DEBUG x\n"
3518        );
3519    }
3520
3521    #[test]
3522    fn split_session_log_targets_preserve_legacy_filters() {
3523        let filter = env_logger::Builder::new()
3524            .parse_filters("info,aft::db=debug")
3525            .build();
3526        for (target, canonical) in [
3527            ("aft_base::cache_location", "aft::cache_location"),
3528            ("aft_db::db::write_ledger", "aft::db::write_ledger"),
3529            ("aft_parse::parser", "aft::parser"),
3530            ("aft::subc", "aft::subc"),
3531            ("aft_db_probe::db", "aft_db_probe::db"),
3532        ] {
3533            assert_eq!(canonical_slog_target(target), canonical);
3534        }
3535        let matches = |target| {
3536            log::Log::enabled(
3537                &filter,
3538                &log::Metadata::builder()
3539                    .target(target)
3540                    .level(log::Level::Debug)
3541                    .build(),
3542            )
3543        };
3544        assert!(!matches("aft_db::db::write_ledger"));
3545        assert!(matches(
3546            canonical_slog_target("aft_db::db::write_ledger").as_ref()
3547        ));
3548    }
3549
3550    fn slow_phases() -> ToolCallPhaseDurations {
3551        ToolCallPhaseDurations {
3552            cpu: crate::tool_progress::ToolCallPhaseCpu::default(),
3553            queue: Duration::ZERO,
3554            setup: Duration::ZERO,
3555            translate: Duration::ZERO,
3556            execute: Duration::from_millis(120),
3557            format: Duration::ZERO,
3558            finalize: Duration::ZERO,
3559            egress_enqueue: Duration::ZERO,
3560            egress_queue: Duration::ZERO,
3561            egress_prepare: Duration::ZERO,
3562            egress_write: Duration::ZERO,
3563            egress: Duration::ZERO,
3564            frame_bytes: 10,
3565            writer_queue_depth: 0,
3566            writer_active_at_enqueue: false,
3567            writer_queue_was_full: false,
3568            writer_reserve_timeouts: 0,
3569            total: SLOW_TOOL_CALL_THRESHOLD + Duration::from_millis(70),
3570            waiting_on: WaitingOn::None,
3571            waiting_on_build_id: None,
3572            wait_ms: 0,
3573            intentional_wait: false,
3574            arg_shape: None,
3575            edit_phases: None,
3576        }
3577    }
3578
3579    fn slow_call_levels(name: &str, caller: ToolCallCaller) -> Vec<log::Level> {
3580        SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow_mut().clear());
3581        note_tool_call_trace(
3582            name,
3583            "test-session",
3584            Path::new("/repo"),
3585            7,
3586            1,
3587            slow_phases(),
3588            caller,
3589        );
3590        SLOW_TOOL_CALL_CAPTURE.with(|captured| {
3591            captured
3592                .borrow_mut()
3593                .drain(..)
3594                .inspect(|(_, message)| {
3595                    assert!(message.starts_with(&format!("slow tool_call name={name} ")))
3596                })
3597                .map(|(level, _)| level)
3598                .collect()
3599        })
3600    }
3601
3602    #[test]
3603    fn slow_phase_time_renders_wall_and_cpu_in_one_field() {
3604        assert_eq!(
3605            slow_phase_time(
3606                Duration::from_micros(39_123),
3607                Some(Duration::from_micros(4))
3608            ),
3609            "39.123ms/cpu=0.004ms"
3610        );
3611        assert_eq!(
3612            slow_phase_time(Duration::from_millis(50), None),
3613            "50.000ms/cpu=?"
3614        );
3615    }
3616
3617    #[test]
3618    fn slow_plumbing_call_logs_at_debug_while_slow_agent_call_warns() {
3619        assert_eq!(
3620            slow_call_levels("bash_drain_completions", ToolCallCaller::Plumbing),
3621            vec![log::Level::Debug]
3622        );
3623        assert_eq!(
3624            slow_call_levels("bash_status", ToolCallCaller::Plumbing),
3625            vec![log::Level::Debug]
3626        );
3627        assert_eq!(
3628            slow_call_levels("bash_status", ToolCallCaller::Agent),
3629            vec![log::Level::Warn]
3630        );
3631        assert_eq!(
3632            slow_call_levels("read", ToolCallCaller::Agent),
3633            vec![log::Level::Warn]
3634        );
3635    }
3636
3637    #[test]
3638    fn slow_intentional_wait_excludes_execution_but_warns_for_overhead() {
3639        let mut phases = slow_phases();
3640        phases.intentional_wait = true;
3641        phases.execute = Duration::from_secs(120);
3642        phases.total = phases.execute + SLOW_TOOL_CALL_THRESHOLD;
3643        let _ = take_slow_tool_call_logs_for_test();
3644        note_tool_call_trace(
3645            "bash_watch",
3646            "waiting-session",
3647            Path::new("/repo"),
3648            7,
3649            1,
3650            phases.clone(),
3651            ToolCallCaller::Agent,
3652        );
3653        assert!(take_slow_tool_call_logs_for_test().is_empty());
3654
3655        phases.queue = SLOW_TOOL_CALL_THRESHOLD + Duration::from_millis(1);
3656        phases.total = phases.execute + phases.queue;
3657        note_tool_call_trace(
3658            "bash_watch",
3659            "waiting-session",
3660            Path::new("/repo"),
3661            7,
3662            2,
3663            phases.clone(),
3664            ToolCallCaller::Agent,
3665        );
3666        let lines = SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.take());
3667        assert_eq!(lines.len(), 1);
3668        assert_eq!(lines[0].0, log::Level::Warn);
3669
3670        phases.intentional_wait = false;
3671        phases.queue = Duration::ZERO;
3672        phases.total = phases.execute;
3673        note_tool_call_trace(
3674            "bash",
3675            "waiting-session",
3676            Path::new("/repo"),
3677            7,
3678            3,
3679            phases,
3680            ToolCallCaller::Agent,
3681        );
3682        let lines = SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.take());
3683        assert_eq!(lines.len(), 1);
3684        assert_eq!(lines[0].0, log::Level::Warn);
3685    }
3686
3687    #[test]
3688    fn fast_call_logs_no_slow_line() {
3689        let mut phases = slow_phases();
3690        phases.total = SLOW_TOOL_CALL_THRESHOLD;
3691        SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow_mut().clear());
3692        note_tool_call_trace(
3693            "read",
3694            "test-session",
3695            Path::new("/repo"),
3696            7,
3697            1,
3698            phases,
3699            ToolCallCaller::Agent,
3700        );
3701        assert!(SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow().is_empty()));
3702    }
3703
3704    #[test]
3705    fn subc_tool_catalog_fast_answer_does_not_emit_slow_call_line() {
3706        let mut phases = slow_phases();
3707        phases.total = SLOW_TOOL_CALL_THRESHOLD;
3708        let _ = take_slow_tool_call_logs_for_test();
3709        note_tool_call_trace(
3710            "tool.catalog",
3711            "catalog-fast",
3712            Path::new("/repo"),
3713            7,
3714            1,
3715            phases,
3716            ToolCallCaller::Agent,
3717        );
3718        assert!(take_slow_tool_call_logs_for_test().is_empty());
3719    }
3720
3721    #[test]
3722    fn epoch_timestamp_renders_known_dates() {
3723        // Epoch start, a modern date, a post-2038 date (u64 range), and the
3724        // 2100 non-leap century boundary that naive leap logic gets wrong.
3725        assert_eq!(format_epoch_secs(0), "1970-01-01T00:00:00Z");
3726        assert_eq!(format_epoch_secs(1_704_067_200), "2024-01-01T00:00:00Z");
3727        assert_eq!(format_epoch_secs(1_709_251_199), "2024-02-29T23:59:59Z");
3728        assert_eq!(format_epoch_secs(4_102_444_800), "2100-01-01T00:00:00Z");
3729        assert_eq!(format_epoch_secs(4_107_542_399), "2100-02-28T23:59:59Z");
3730    }
3731
3732    #[test]
3733    fn token_written_through_the_sink_is_masked_on_disk() {
3734        let temp = TempDir::new().unwrap();
3735        let path = temp.path().join("aft-777.log");
3736        let sink = RotatingFile::open(path.clone(), LOG_FILE_BYTES, 1, 1).unwrap();
3737        let (tx, rx) = mpsc::sync_channel(8);
3738        let sink = Arc::new(Mutex::new(Some(sink)));
3739        let writer = thread::spawn(move || {
3740            run_file_writer(
3741                sink,
3742                rx,
3743                Arc::new(LogWriteHealth::default()),
3744                LOG_WRITE_RETRY_MIN,
3745            )
3746        });
3747        let mut tee = TeeWriter::new(Some(tx));
3748        let token = "ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8";
3749        tee.write_all(
3750            format!("[aft] fetch https://bob:pw123@host.example/x?access_token=zz9 {token}\n")
3751                .as_bytes(),
3752        )
3753        .unwrap();
3754        drop(tee);
3755        writer.join().unwrap();
3756
3757        let on_disk = fs::read_to_string(&path).unwrap();
3758        assert_eq!(
3759            on_disk,
3760            "[aft] fetch https://***@host.example/x?access_token=<REDACTED_SECRET> <REDACTED_SECRET>\n"
3761        );
3762        assert!(!on_disk.contains(token));
3763        assert!(!on_disk.contains("pw123"));
3764    }
3765
3766    #[cfg(unix)]
3767    fn mode_of(path: &Path) -> u32 {
3768        use std::os::unix::fs::PermissionsExt;
3769        fs::metadata(path).unwrap().permissions().mode() & 0o777
3770    }
3771
3772    #[cfg(unix)]
3773    #[test]
3774    fn fresh_log_dir_and_file_are_owner_only() {
3775        let temp = TempDir::new().unwrap();
3776        let logs_dir = temp.path().join("storage").join("logs");
3777        let path = logs_dir.join("aft-4242.log");
3778        let (mut sink, _) = prepare_file_sink(&logs_dir, &path).unwrap();
3779        sink.write_batch(&line("hello")).unwrap();
3780
3781        assert_eq!(mode_of(&logs_dir), 0o700);
3782        assert_eq!(mode_of(&path), 0o600);
3783        // A rotated-in generation is created owner-only too.
3784        sink.rotate().unwrap();
3785        assert_eq!(mode_of(&path), 0o600);
3786        assert_eq!(mode_of(&rotated_path(&path, 1)), 0o600);
3787    }
3788
3789    #[cfg(unix)]
3790    #[test]
3791    fn existing_world_readable_log_dir_and_files_are_tightened() {
3792        use std::os::unix::fs::PermissionsExt;
3793        let temp = TempDir::new().unwrap();
3794        let logs_dir = temp.path().join("logs");
3795        fs::create_dir(&logs_dir).unwrap();
3796        fs::set_permissions(&logs_dir, fs::Permissions::from_mode(0o755)).unwrap();
3797        let path = logs_dir.join("aft-4242.log");
3798        for file in [path.clone(), rotated_path(&path, 1)] {
3799            fs::write(&file, "old\n").unwrap();
3800            fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
3801        }
3802
3803        let _ = prepare_file_sink(&logs_dir, &path).unwrap();
3804
3805        assert_eq!(mode_of(&logs_dir), 0o700);
3806        assert_eq!(mode_of(&path), 0o600);
3807        assert_eq!(mode_of(&rotated_path(&path, 1)), 0o600);
3808        assert_eq!(fs::read_to_string(&path).unwrap(), "old\n");
3809    }
3810
3811    #[test]
3812    fn rotation_rolls_once_and_replaces_the_single_backup_generation() {
3813        let temp = TempDir::new().unwrap();
3814        let path = temp.path().join("aft-123.log");
3815        fs::write(rotated_path(&path, 1), "stale backup\n").unwrap();
3816        let mut sink = RotatingFile::open(path.clone(), 10, 1, 1).unwrap();
3817        sink.write_batch(&line("aaaa")).unwrap();
3818        sink.write_batch(&line("bbbb")).unwrap();
3819        sink.write_batch(&line("cccc")).unwrap();
3820        sink.write_batch(&line("dddd")).unwrap();
3821        sink.write_batch(&line("eeee")).unwrap();
3822
3823        assert_eq!(fs::read_to_string(&path).unwrap(), "eeee\n");
3824        assert_eq!(
3825            fs::read_to_string(rotated_path(&path, 1)).unwrap(),
3826            "cccc\ndddd\n"
3827        );
3828        assert!(!rotated_path(&path, 2).exists());
3829    }
3830
3831    #[test]
3832    fn dead_pid_sweep_respects_age_liveness_and_explicit_plugin_exclusion() {
3833        let temp = TempDir::new().unwrap();
3834        let dead = temp.path().join("aft-4294967294.log");
3835        let dead_rotated = temp.path().join("aft-4294967294.log.1");
3836        let fresh_dead = temp.path().join("aft-4294967293.log");
3837        let own = temp.path().join(format!("aft-{}.log", std::process::id()));
3838        let live_rotated = rotated_path(&own, 1);
3839        let plugin = temp.path().join("aft-plugin.log");
3840        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
3841        for path in [&dead, &dead_rotated, &own, &live_rotated, &plugin] {
3842            fs::write(path, "log").unwrap();
3843            set_file_mtime(path, FileTime::from_unix_time(1, 0)).unwrap();
3844        }
3845        fs::write(&fresh_dead, "fresh").unwrap();
3846        set_file_mtime(
3847            &fresh_dead,
3848            FileTime::from_unix_time(
3849                (now - DEAD_PROCESS_LOG_MAX_AGE + Duration::from_secs(1))
3850                    .duration_since(SystemTime::UNIX_EPOCH)
3851                    .unwrap()
3852                    .as_secs() as i64,
3853                0,
3854            ),
3855        )
3856        .unwrap();
3857
3858        let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, u64::MAX).unwrap();
3859
3860        assert_eq!(summary.removed_files, 2);
3861        assert!(!dead.exists());
3862        assert!(!dead_rotated.exists());
3863        assert!(fresh_dead.exists());
3864        assert!(own.exists());
3865        assert!(live_rotated.exists());
3866        assert!(plugin.exists());
3867    }
3868
3869    /// A live process's own start time always precedes its writes, so its file
3870    /// with a current mtime stays; the same live number on a file last written
3871    /// before that process started is a recycled PID and is reaped.
3872    #[cfg(any(target_os = "linux", target_os = "macos"))]
3873    #[test]
3874    fn recycled_pid_log_is_reaped_while_the_live_owner_is_kept() {
3875        let temp = TempDir::new().unwrap();
3876        let live_pid = unsafe { libc::getppid() } as u32;
3877        assert!(is_process_alive(live_pid));
3878        let recycled = temp.path().join(format!("aft-{live_pid}.log"));
3879        fs::write(&recycled, "written long before this process existed").unwrap();
3880        set_file_mtime(&recycled, FileTime::from_unix_time(1, 0)).unwrap();
3881
3882        let summary = sweep_logs(
3883            temp.path(),
3884            SystemTime::now(),
3885            DEAD_PROCESS_LOG_MAX_AGE,
3886            u64::MAX,
3887        )
3888        .unwrap();
3889        assert_eq!(summary.removed_files, 1);
3890        assert_eq!(summary.recycled_pids, 1);
3891        assert!(!recycled.exists());
3892
3893        let owned = temp.path().join(format!("aft-{live_pid}.log"));
3894        fs::write(&owned, "written by the live owner").unwrap();
3895        let summary = sweep_logs(
3896            temp.path(),
3897            SystemTime::now() + DEAD_PROCESS_LOG_MAX_AGE * 2,
3898            DEAD_PROCESS_LOG_MAX_AGE,
3899            0,
3900        )
3901        .unwrap();
3902        assert_eq!(summary.removed_files, 0);
3903        assert!(owned.exists());
3904    }
3905
3906    /// After a reboot the kernel hands low numbers to system daemons owned by
3907    /// other users. PID 1 is always such a process, and the first cut of the
3908    /// recycled-PID check could not read its start time on macOS, so the file
3909    /// stayed pinned as if the daemon had written it. The verdict must not
3910    /// depend on the new owner's uid.
3911    #[cfg(any(target_os = "linux", target_os = "macos"))]
3912    #[test]
3913    fn recycled_pid_now_owned_by_another_user_is_reaped() {
3914        let temp = TempDir::new().unwrap();
3915        assert!(is_process_alive(1));
3916        assert!(
3917            crate::process_identity::process_start_time_ms(1).is_some(),
3918            "pid 1's start time must be readable from an unprivileged process"
3919        );
3920        let recycled = temp.path().join("aft-1.log");
3921        fs::write(&recycled, "written before the current pid 1 booted").unwrap();
3922        set_file_mtime(&recycled, FileTime::from_unix_time(1, 0)).unwrap();
3923
3924        let summary = sweep_logs(
3925            temp.path(),
3926            SystemTime::now(),
3927            DEAD_PROCESS_LOG_MAX_AGE,
3928            u64::MAX,
3929        )
3930        .unwrap();
3931        assert_eq!(summary.removed_files, 1);
3932        assert_eq!(summary.recycled_pids, 1);
3933        assert!(!recycled.exists());
3934    }
3935
3936    #[test]
3937    fn budget_backstop_deletes_oldest_dead_files_but_not_live_files() {
3938        let temp = TempDir::new().unwrap();
3939        let oldest = temp.path().join("aft-4294967294.log");
3940        let newest = temp.path().join("aft-4294967293.log");
3941        let live = temp.path().join(format!("aft-{}.log", std::process::id()));
3942        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
3943        fs::write(&oldest, "oldest").unwrap();
3944        fs::write(&newest, "newest").unwrap();
3945        fs::write(&live, "live-live").unwrap();
3946        set_file_mtime(&oldest, FileTime::from_unix_time(1, 0)).unwrap();
3947        set_file_mtime(&newest, FileTime::from_unix_time(2, 0)).unwrap();
3948        set_file_mtime(&live, FileTime::from_unix_time(1, 0)).unwrap();
3949
3950        let summary = sweep_logs(
3951            temp.path(),
3952            now,
3953            Duration::from_secs(365 * 24 * 60 * 60),
3954            15,
3955        )
3956        .unwrap();
3957
3958        assert_eq!(summary.removed_files, 1);
3959        assert!(!oldest.exists());
3960        assert!(newest.exists());
3961        assert!(live.exists());
3962    }
3963
3964    #[test]
3965    fn budget_backstop_keeps_the_newest_dead_log_inside_its_forensic_window() {
3966        // 2026-09-18: a successor's startup sweep deleted the log of the
3967        // process that had just died, because the directory was over budget
3968        // and that log was the only eligible candidate. The newest dead log
3969        // younger than the age reap is the record of the last exit and stays.
3970        let temp = TempDir::new().unwrap();
3971        let older = temp.path().join("aft-4294967294.log");
3972        let predecessor = temp.path().join("aft-4294967293.log");
3973        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
3974        fs::write(&older, "older-older-older").unwrap();
3975        fs::write(&predecessor, "predecessor-predecessor").unwrap();
3976        set_file_mtime(&older, FileTime::from_unix_time(1, 0)).unwrap();
3977        // Modified moments before `now`: dead, but inside the 24 h window.
3978        set_file_mtime(
3979            &predecessor,
3980            FileTime::from_unix_time(10 * 24 * 60 * 60 - 30, 0),
3981        )
3982        .unwrap();
3983
3984        let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, 4).unwrap();
3985
3986        assert!(
3987            !older.exists(),
3988            "the older dead log is still budget-reapable"
3989        );
3990        assert!(predecessor.exists(), "the newest dead log is protected");
3991        assert_eq!(summary.removed_files, 1);
3992        assert_eq!(
3993            summary.over_budget_bytes,
3994            "predecessor-predecessor".len() as u64 - 4,
3995            "the shortfall is reported instead of destroying the record"
3996        );
3997
3998        // Once it is older than the age reap it is an ordinary dead log again.
3999        set_file_mtime(&predecessor, FileTime::from_unix_time(1, 0)).unwrap();
4000        let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, 4).unwrap();
4001        assert!(!predecessor.exists());
4002        assert_eq!(summary.over_budget_bytes, 0);
4003    }
4004
4005    #[test]
4006    fn relic_plugin_rotations_are_reaped_before_process_logs_are_weighed() {
4007        let temp = TempDir::new().unwrap();
4008        let active = temp.path().join("aft-plugin.log");
4009        let backup = temp.path().join("aft-plugin.log.1");
4010        let relic_two = temp.path().join("aft-plugin.log.2");
4011        let relic_five = temp.path().join("aft-plugin.log.5");
4012        let test_relic = temp.path().join("aft-plugin-test.log.3");
4013        let predecessor = temp.path().join("aft-4294967293.log");
4014        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
4015        for (path, content) in [
4016            (&active, "active"),
4017            (&backup, "backup"),
4018            (&relic_two, "relic-two-relic-two"),
4019            (&relic_five, "relic-five-relic-five"),
4020            (&test_relic, "test-relic-test-relic"),
4021            (&predecessor, "predecessor"),
4022        ] {
4023            fs::write(path, content).unwrap();
4024            set_file_mtime(path, FileTime::from_unix_time(10 * 24 * 60 * 60 - 30, 0)).unwrap();
4025        }
4026
4027        // Budget fits the owned files plus the predecessor only once the
4028        // relics are gone; the predecessor must not be the thing that pays.
4029        let budget = ("active".len() + "backup".len() + "predecessor".len()) as u64;
4030        let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, budget).unwrap();
4031
4032        assert!(!relic_two.exists());
4033        assert!(!relic_five.exists());
4034        assert!(!test_relic.exists());
4035        assert!(active.exists(), "the plugin's live file is never touched");
4036        assert!(
4037            backup.exists(),
4038            "the plugin's one owned backup is never touched"
4039        );
4040        assert!(predecessor.exists());
4041        assert_eq!(summary.removed_files, 3);
4042        assert_eq!(summary.over_budget_bytes, 0);
4043    }
4044
4045    #[test]
4046    fn tool_call_summary_uses_bounded_window_median_and_maxima() {
4047        let samples = VecDeque::from([
4048            ToolCallPerfSample {
4049                total_ms: 9,
4050                queue_ms: 5,
4051            },
4052            ToolCallPerfSample {
4053                total_ms: 3,
4054                queue_ms: 1,
4055            },
4056            ToolCallPerfSample {
4057                total_ms: 7,
4058                queue_ms: 2,
4059            },
4060            ToolCallPerfSample {
4061                total_ms: 5,
4062                queue_ms: 4,
4063            },
4064        ]);
4065
4066        let summary = summarize_tool_calls(&samples);
4067
4068        assert_eq!(summary.window, 4);
4069        assert_eq!(summary.p50_total_ms, 5);
4070        assert_eq!(summary.max_total_ms, 9);
4071        assert_eq!(summary.p50_queue_ms, 2);
4072        assert_eq!(summary.max_queue_ms, 5);
4073    }
4074
4075    #[test]
4076    fn perf_tick_skips_empty_drains_but_keeps_real_work_and_drain_counts() {
4077        for activity in ["drain", "watcher", "semantic"] {
4078            let perf = PerfMetrics::default();
4079            perf.reporter.lock().unwrap().last_report = Instant::now() - perf_tick_interval();
4080            perf.drain_slices.store(1, Ordering::Relaxed);
4081            if activity == "watcher" {
4082                perf.watcher_ingested.store(2, Ordering::Relaxed);
4083                perf.watcher_paths.store(1, Ordering::Relaxed);
4084            } else if activity == "semantic" {
4085                perf.semantic_collects.store(1, Ordering::Relaxed);
4086                perf.semantic_files.store(2, Ordering::Relaxed);
4087                perf.semantic_chunks.store(3, Ordering::Relaxed);
4088                perf.semantic_ms.store(4, Ordering::Relaxed);
4089            }
4090            let (_, lines) = capture_log_lines(|| report_perf_tick(&perf, None, (0, 0)));
4091            if activity == "drain" {
4092                assert!(lines.is_empty(), "{lines:?}");
4093            } else {
4094                assert_eq!(lines.len(), 1, "{lines:?}");
4095                assert!(lines[0].starts_with("INFO perf tick:"), "{lines:?}");
4096                assert!(lines[0].contains(" drains=1 "), "{lines:?}");
4097                let expected = if activity == "watcher" {
4098                    "watcher={ingested:2,paths:1,dropped:0}"
4099                } else {
4100                    "semantic={collects:1,files:2,chunks:3,ms:4}"
4101                };
4102                assert!(lines[0].contains(expected), "{lines:?}");
4103            }
4104            assert_eq!(perf.drain_slices.load(Ordering::Relaxed), 0);
4105        }
4106    }
4107
4108    #[test]
4109    fn tool_call_tick_labels_interval_count_and_rolling_window() {
4110        let samples = VecDeque::from([ToolCallPerfSample {
4111            total_ms: 3_000,
4112            queue_ms: 2_900,
4113        }]);
4114        let summary = summarize_tool_calls(&samples);
4115
4116        assert_eq!(
4117            format_tool_call_summary(1, summary),
4118            "toolcall={new:1,window:1,p50_total_ms:3000,max_total_ms:3000,p50_queue_ms:2900,max_queue_ms:2900}"
4119        );
4120        assert_eq!(
4121            format_tool_call_summary(0, summary),
4122            "toolcall={new:0,window:1,p50_total_ms:3000,max_total_ms:3000,p50_queue_ms:2900,max_queue_ms:2900}"
4123        );
4124    }
4125
4126    fn index_event_matches_grammar(line: &str) -> bool {
4127        let Some(rest) = line.strip_prefix("index_event ") else {
4128            return false;
4129        };
4130        if rest.is_empty() {
4131            return false;
4132        }
4133        rest.split(' ').all(|token| {
4134            let Some((key, value)) = token.split_once('=') else {
4135                return false;
4136            };
4137            !key.is_empty()
4138                && key.chars().all(|c| c.is_ascii_lowercase() || c == '_')
4139                && !value.is_empty()
4140                && !value.contains(' ')
4141                && !value.contains('=')
4142        })
4143    }
4144
4145    fn index_event_fields(line: &str) -> BTreeMap<String, String> {
4146        let mut fields = BTreeMap::new();
4147        for token in line.split_whitespace().skip(1) {
4148            let Some((key, value)) = token.split_once('=') else {
4149                continue;
4150            };
4151            fields.insert(key.to_string(), value.to_string());
4152        }
4153        fields
4154    }
4155
4156    fn assert_index_event_grammar(lines: &[String]) {
4157        for line in lines {
4158            assert!(
4159                index_event_matches_grammar(line),
4160                "index_event line failed grammar: {line}"
4161            );
4162        }
4163    }
4164
4165    pub fn event_matches(line: &str, plane: &str, root: &str, key: &str) -> bool {
4166        let fields = index_event_fields(line);
4167        fields.get("plane").map(String::as_str) == Some(plane)
4168            && fields.get("root").map(String::as_str) == Some(root)
4169            && fields.get("key").map(String::as_str) == Some(key)
4170    }
4171
4172    pub fn assert_lifecycle_sequence(
4173        lines: &[String],
4174        plane: &str,
4175        root: &str,
4176        key: &str,
4177        require_progress: bool,
4178    ) {
4179        let events: Vec<_> = lines
4180            .iter()
4181            .filter(|line| event_matches(line, plane, root, key))
4182            .cloned()
4183            .collect();
4184        assert_index_event_grammar(&events);
4185        let kinds: Vec<_> = events
4186            .iter()
4187            .filter_map(|line| index_event_fields(line).get("kind").cloned())
4188            .filter(|kind| {
4189                matches!(
4190                    kind.as_str(),
4191                    "build_started" | "build_progress" | "build_ready"
4192                )
4193            })
4194            .collect();
4195        assert!(
4196            kinds.first().is_some_and(|kind| kind == "build_started"),
4197            "expected build_started first, got {kinds:?} from {events:?}"
4198        );
4199        if require_progress {
4200            assert!(
4201                kinds.iter().any(|kind| kind == "build_progress"),
4202                "expected build_progress in {kinds:?} from {events:?}"
4203            );
4204        }
4205        assert!(
4206            kinds.last().is_some_and(|kind| kind == "build_ready"),
4207            "expected build_ready last, got {kinds:?} from {events:?}"
4208        );
4209        let build_ids: Vec<_> = events
4210            .iter()
4211            .filter_map(|line| index_event_fields(line).get("build_id").cloned())
4212            .collect();
4213        assert!(!build_ids.is_empty());
4214        assert!(
4215            build_ids.iter().all(|id| id == &build_ids[0]),
4216            "build_id drifted across events: {build_ids:?}"
4217        );
4218        for line in &events {
4219            let fields = index_event_fields(line);
4220            assert_eq!(fields.get("root").map(String::as_str), Some(root), "{line}");
4221            assert_eq!(fields.get("key").map(String::as_str), Some(key), "{line}");
4222        }
4223    }
4224
4225    pub fn tiny_project(
4226        name: &str,
4227        file_name: &str,
4228        contents: &str,
4229    ) -> (tempfile::TempDir, PathBuf) {
4230        let temp = tempfile::tempdir().expect("tempdir");
4231        let root = temp.path().join(name);
4232        std::fs::create_dir_all(&root).expect("create project");
4233        std::fs::write(root.join(file_name), contents).expect("write fixture");
4234        let root = std::fs::canonicalize(&root).unwrap_or(root);
4235        (temp, root)
4236    }
4237
4238    #[test]
4239    fn watcher_rescan_event_reports_reason_cost_rss_and_interval_count() {
4240        let (_, lines) = capture_index_events(|| {
4241            log_watcher_rescan(
4242                Path::new("/tmp/watcher root"),
4243                RescanReason::KernelDropped,
4244                42,
4245                Some(-4096),
4246                137,
4247            );
4248        });
4249        assert_index_event_grammar(&lines);
4250        assert_eq!(lines.len(), 1);
4251        let fields = index_event_fields(&lines[0]);
4252        assert_eq!(
4253            fields.get("kind").map(String::as_str),
4254            Some("watcher_rescan")
4255        );
4256        assert_eq!(fields.get("plane").map(String::as_str), Some("watcher"));
4257        assert_eq!(
4258            fields.get("root").map(String::as_str),
4259            Some("/tmp/watcher_root")
4260        );
4261        assert_eq!(
4262            fields.get("reason").map(String::as_str),
4263            Some("kernel_dropped")
4264        );
4265        assert_eq!(fields.get("cost_ms").map(String::as_str), Some("42"));
4266        assert_eq!(
4267            fields.get("rss_delta_bytes").map(String::as_str),
4268            Some("-4096")
4269        );
4270        assert_eq!(
4271            fields.get("raw_events_since_last").map(String::as_str),
4272            Some("137")
4273        );
4274    }
4275
4276    #[test]
4277    fn index_event_grammar_rejects_spaces_and_equals_in_values() {
4278        let (result, lines) = capture_index_events(|| {
4279            log_index_event(
4280                IndexEvent::new(
4281                    IndexEventKind::BuildStarted,
4282                    IndexPlane::Search,
4283                    "b-1-1",
4284                    "/tmp/root",
4285                    "abc123",
4286                )
4287                .field("stage", "streaming"),
4288            );
4289        });
4290        let _ = result;
4291        assert_index_event_grammar(&lines);
4292        // The capture slot is process-wide: a parallel lib test that builds an
4293        // index can emit into the same window. Only this test's own event
4294        // (unique build_id) is the subject here.
4295        let own: Vec<&String> = lines
4296            .iter()
4297            .filter(|line| {
4298                index_event_fields(line).get("build_id").map(String::as_str) == Some("b-1-1")
4299            })
4300            .collect();
4301        assert_eq!(own.len(), 1, "{lines:?}");
4302    }
4303
4304    #[test]
4305    fn index_event_keeps_required_fields_for_long_root() {
4306        let root = format!("/{}", "a".repeat(399));
4307        let (_, lines) = capture_index_events(|| {
4308            log_index_event(IndexEvent::new(
4309                IndexEventKind::BuildStarted,
4310                IndexPlane::Search,
4311                "b-9-9",
4312                &root,
4313                "keepkey",
4314            ));
4315        });
4316        assert_eq!(lines.len(), 1, "{lines:?}");
4317        let fields = index_event_fields(&lines[0]);
4318        assert_eq!(fields.get("build_id").map(String::as_str), Some("b-9-9"));
4319        assert_eq!(fields.get("key").map(String::as_str), Some("keepkey"));
4320        assert!(fields.get("root").is_some(), "{lines:?}");
4321        assert_index_event_grammar(&lines);
4322    }
4323
4324    #[test]
4325    fn index_event_long_root_keeps_measurements_within_cap() {
4326        let suffix = "/typescript-eslint/worker";
4327        let root = format!("/{}{suffix}", "a".repeat(300 - 1 - suffix.len()));
4328        assert_eq!(root.len(), 300);
4329        let event = IndexEvent::new(
4330            IndexEventKind::FirstQuery,
4331            IndexPlane::Semantic,
4332            "b-12345-123",
4333            &root,
4334            "workspace",
4335        )
4336        .field("tool", "semantic_search")
4337        .field("queue_ms", 12)
4338        .field("service_ms", 34)
4339        .field("status", "ok")
4340        .field("elapsed_ms", 5678)
4341        .field("ready_to_first_query_ms", 9012)
4342        .field("completed", 345)
4343        .field("total", 678);
4344        let line = format_index_event_line(&event);
4345        assert!(line.len() <= INDEX_EVENT_MAX_BYTES, "{line}");
4346        assert!(index_event_matches_grammar(&line), "{line}");
4347        let fields = index_event_fields(&line);
4348        for (key, value) in [
4349            ("elapsed_ms", "5678"),
4350            ("ready_to_first_query_ms", "9012"),
4351            ("completed", "345"),
4352            ("total", "678"),
4353            ("queue_ms", "12"),
4354            ("service_ms", "34"),
4355        ] {
4356            assert_eq!(fields.get(key).map(String::as_str), Some(value), "{line}");
4357        }
4358        assert!(fields["root"].ends_with(suffix), "{line}");
4359        assert_eq!(
4360            line,
4361            include_str!("../../../scripts/telemetry/fixtures/index-event-long-root.txt").trim()
4362        );
4363    }
4364
4365    #[test]
4366    fn index_event_measurements_take_priority_over_long_descriptions() {
4367        let event = IndexEvent::new(
4368            IndexEventKind::FirstQuery,
4369            IndexPlane::Search,
4370            "b-1-1",
4371            "/work/repo",
4372            "0123456789abcdef",
4373        )
4374        .field("tool", "x".repeat(190))
4375        .field("status", "x".repeat(300))
4376        .field("ready_to_first_query_ms", 42);
4377        let line = format_index_event_line(&event);
4378        assert!(line.len() <= INDEX_EVENT_MAX_BYTES, "{line}");
4379        assert_eq!(index_event_fields(&line)["ready_to_first_query_ms"], "42");
4380    }
4381
4382    #[test]
4383    fn shortened_index_roots_are_distinct_and_bounded() {
4384        let root = format!("/{}/typescript-eslint/worker", "a".repeat(300));
4385        let other = root.replacen('a', "b", 1);
4386        let shortened = left_truncate_root(&root, 50);
4387        assert!(shortened.starts_with(".../"));
4388        assert!(shortened.ends_with("/typescript-eslint/worker"));
4389        assert_ne!(shortened, left_truncate_root(&other, 50));
4390        for budget in 0..50 {
4391            assert!(left_truncate_root(&root, budget).len() <= budget);
4392        }
4393    }
4394
4395    #[test]
4396    fn first_query_fires_once_per_build_id() {
4397        let root = PathBuf::from("/tmp/first-query-root");
4398        let key = "firstquerykey";
4399        let build_id = "b-1-99";
4400        let (_, lines) = capture_index_events(|| {
4401            log_index_event(IndexEvent::new(
4402                IndexEventKind::BuildReady,
4403                IndexPlane::Search,
4404                build_id,
4405                &root,
4406                key,
4407            ));
4408            assert!(claim_first_query(
4409                IndexPlane::Search,
4410                &root,
4411                "grep",
4412                1,
4413                2,
4414                "ok"
4415            ));
4416            assert!(!claim_first_query(
4417                IndexPlane::Search,
4418                &root,
4419                "grep",
4420                1,
4421                2,
4422                "ok"
4423            ));
4424        });
4425        let first_query: Vec<_> = lines
4426            .iter()
4427            .filter(|line| line.contains("kind=first_query"))
4428            .collect();
4429        assert_eq!(first_query.len(), 1, "{lines:?}");
4430        let fields = index_event_fields(first_query[0]);
4431        assert_eq!(fields.get("build_id").map(String::as_str), Some(build_id));
4432        assert_eq!(fields.get("tool").map(String::as_str), Some("grep"));
4433    }
4434}