use crate::executor::{Executor, ExecutorContext};
use crate::process_identity::is_process_alive;
use crate::tool_progress::{ToolCallPhaseDurations, WaitingOn};
use sha2::{Digest, Sha256};
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, VecDeque};
#[cfg(unix)]
use std::fs::OpenOptions;
use std::fs::{self, File};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant, SystemTime};
mod stderr_mirror;
static SUBC_LOGGING: AtomicBool = AtomicBool::new(false);
static STDERR_MIRROR: OnceLock<stderr_mirror::Mirror> = OnceLock::new();
static STDERR_MIRROR_HEALTH: LazyLock<Arc<stderr_mirror::MirrorHealth>> =
LazyLock::new(|| Arc::new(stderr_mirror::MirrorHealth::default()));
const LOG_FILE_BYTES: u64 = 32 * 1024 * 1024;
const LOG_GENERATIONS: usize = 1;
const ROTATION_CHECK_EVERY: u64 = 1;
const LOG_CHANNEL_CAPACITY: usize = 4096;
const LOG_WRITE_RETRY_MIN: Duration = Duration::from_secs(1);
const LOG_WRITE_RETRY_MAX: Duration = Duration::from_secs(30);
const DEAD_PROCESS_LOG_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
const LOG_DIRECTORY_BUDGET_BYTES: u64 = 200 * 1024 * 1024;
const LOG_SWEEP_INTERVAL: Duration = Duration::from_secs(60 * 60);
const DEFAULT_PERF_TICK_INTERVAL: Duration = Duration::from_secs(60);
const PERF_SAMPLE_INTERVAL: Duration = Duration::from_millis(250);
#[rustfmt::skip]
test_support_visibility! {
pub(crate) const SLOW_TOOL_CALL_THRESHOLD: Duration = Duration::from_millis(50);
}
const TOOL_CALL_SAMPLE_CAPACITY: usize = 256;
const INDEX_EVENT_MAX_BYTES: usize = 300;
const PANIC_MESSAGE_BYTES: usize = 4 * 1024;
const PANIC_BACKTRACE_BYTES: usize = 24 * 1024;
const PANIC_TRUNCATION: &str = "\n[panic diagnostic truncated]";
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum IndexPlane {
Callgraph,
Search,
Semantic,
Tier2,
}
impl IndexPlane {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Callgraph => "callgraph",
Self::Search => "search",
Self::Semantic => "semantic",
Self::Tier2 => "tier2",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IndexEventKind {
BuildStarted,
BuildProgress,
BuildReady,
BuildSuperseded,
#[allow(dead_code)]
BuildCancelled,
BuildFailed,
FirstQuery,
}
impl IndexEventKind {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::BuildStarted => "build_started",
Self::BuildProgress => "build_progress",
Self::BuildReady => "build_ready",
Self::BuildSuperseded => "build_superseded",
Self::BuildCancelled => "build_cancelled",
Self::BuildFailed => "build_failed",
Self::FirstQuery => "first_query",
}
}
fn is_terminal(self) -> bool {
matches!(
self,
Self::BuildReady | Self::BuildSuperseded | Self::BuildCancelled | Self::BuildFailed
)
}
}
#[derive(Clone, Debug)]
pub struct IndexEvent {
pub kind: IndexEventKind,
pub plane: IndexPlane,
pub build_id: String,
pub root: PathBuf,
pub key: String,
extra: Vec<(&'static str, String)>,
}
impl IndexEvent {
pub(crate) fn new(
kind: IndexEventKind,
plane: IndexPlane,
build_id: impl Into<String>,
root: impl AsRef<Path>,
key: impl Into<String>,
) -> Self {
Self {
kind,
plane,
build_id: build_id.into(),
root: root.as_ref().to_path_buf(),
key: key.into(),
extra: Vec::new(),
}
}
pub fn from_scope(kind: IndexEventKind, scope: &IndexBuildScope) -> Self {
Self::new(
kind,
scope.plane,
scope.build_id.clone(),
&scope.root,
scope.key.clone(),
)
}
pub fn field(mut self, key: &'static str, value: impl ToString) -> Self {
self.extra.push((key, value.to_string()));
self
}
}
#[derive(Clone, Debug)]
pub struct IndexBuildScope {
pub plane: IndexPlane,
pub build_id: String,
pub root: PathBuf,
pub key: String,
pub started_at: Instant,
}
impl IndexBuildScope {
pub fn new(plane: IndexPlane, root: impl AsRef<Path>, key: impl Into<String>) -> Self {
Self {
plane,
build_id: mint_index_build_id(),
root: root.as_ref().to_path_buf(),
key: key.into(),
started_at: Instant::now(),
}
}
pub fn elapsed_ms(&self) -> u64 {
self.started_at.elapsed().as_millis().min(u64::MAX as u128) as u64
}
}
struct InFlightBuild {
build_id: String,
}
struct UnclaimedReady {
build_id: String,
key: String,
ready_at: Instant,
}
#[derive(Default)]
struct IndexLifecycle {
in_flight: Mutex<HashMap<(String, IndexPlane), InFlightBuild>>,
unclaimed: Mutex<HashMap<(String, IndexPlane), UnclaimedReady>>,
}
#[derive(Default)]
struct IndexBuildStartSignals {
sequence: u64,
last_by_root_plane: HashMap<(String, IndexPlane), u64>,
in_flight_by_root_plane: HashMap<(String, IndexPlane), u64>,
waiters: HashMap<(String, IndexPlane), Vec<(u64, crossbeam_channel::Sender<()>)>>,
}
struct ToolCallWaitState {
waiting_on: WaitingOn,
waiting_on_build_id: Option<String>,
wait_ms: u64,
queue_ms: u64,
}
impl Default for ToolCallWaitState {
fn default() -> Self {
Self {
waiting_on: WaitingOn::None,
waiting_on_build_id: None,
wait_ms: 0,
queue_ms: 0,
}
}
}
static INDEX_BUILD_COUNTER: AtomicU64 = AtomicU64::new(1);
static INDEX_LIFECYCLE: LazyLock<IndexLifecycle> = LazyLock::new(IndexLifecycle::default);
static INDEX_BUILD_START_SIGNALS: LazyLock<Mutex<IndexBuildStartSignals>> =
LazyLock::new(|| Mutex::new(IndexBuildStartSignals::default()));
thread_local! {
static CURRENT_INDEX_BUILD: RefCell<Option<IndexBuildScope>> = const { RefCell::new(None) };
static TOOL_CALL_WAIT: RefCell<ToolCallWaitState> = const {
RefCell::new(ToolCallWaitState {
waiting_on: WaitingOn::None,
waiting_on_build_id: None,
wait_ms: 0,
queue_ms: 0,
})
};
}
#[cfg(any(test, feature = "test-support"))]
static INDEX_EVENT_CAPTURE: LazyLock<Mutex<Option<Vec<String>>>> =
LazyLock::new(|| Mutex::new(None));
#[cfg(any(test, feature = "test-support"))]
static INDEX_EVENT_CAPTURE_LOCK: Mutex<()> = Mutex::new(());
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static LOG_LINE_CAPTURE: RefCell<Option<Arc<Mutex<Vec<String>>>>> = const { RefCell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn capture_log_lines<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
let capture = Arc::new(Mutex::new(Vec::new()));
let result = capture_log_lines_into(capture.clone(), f);
let lines = capture.lock().unwrap().clone();
(result, lines)
}
#[cfg(any(test, feature = "test-support"))]
pub fn capture_log_lines_into<R>(capture: Arc<Mutex<Vec<String>>>, f: impl FnOnce() -> R) -> R {
let _ = env_logger::builder().is_test(true).try_init();
let previous = LOG_LINE_CAPTURE.with(|slot| slot.replace(Some(capture)));
let result = f();
LOG_LINE_CAPTURE.with(|slot| slot.replace(previous));
result
}
#[cfg(any(test, feature = "test-support"))]
fn capture_log_line(level: log::Level, line: &str) {
LOG_LINE_CAPTURE.with(|slot| {
if let Some(lines) = slot.borrow().as_ref() {
lines.lock().unwrap().push(format!("{level} {line}"));
}
});
}
#[doc(hidden)]
#[cfg(any(test, feature = "test-support"))]
#[inline]
pub fn capture_active() -> bool {
LOG_LINE_CAPTURE.with(|slot| slot.borrow().is_some())
}
#[doc(hidden)]
#[cfg(not(any(test, feature = "test-support")))]
#[inline]
pub fn capture_active() -> bool {
false
}
fn canonical_slog_target(target: &str) -> std::borrow::Cow<'_, str> {
match target.split_once("::") {
Some(("aft_base" | "aft_db" | "aft_parse", module)) => format!("aft::{module}").into(),
_ => target.into(),
}
}
#[doc(hidden)]
#[inline]
pub fn slog_info_enabled(target: &'static str) -> bool {
log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Info)
|| capture_active()
}
#[doc(hidden)]
#[inline]
pub fn slog_warn_enabled(target: &'static str) -> bool {
log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Warn)
|| capture_active()
}
#[doc(hidden)]
#[inline]
pub fn slog_error_enabled(target: &'static str) -> bool {
log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Error)
|| capture_active()
}
#[doc(hidden)]
#[inline]
pub fn slog_debug_enabled(target: &'static str) -> bool {
log::log_enabled!(target: canonical_slog_target(target).as_ref(), log::Level::Debug)
|| capture_active()
}
#[doc(hidden)]
pub fn emit_slog_info(target: &'static str, message: String) {
emit_slog(target, log::Level::Info, message);
}
#[doc(hidden)]
pub fn emit_slog_warn(target: &'static str, message: String) {
emit_slog(target, log::Level::Warn, message);
}
#[doc(hidden)]
pub fn emit_slog_error(target: &'static str, message: String) {
emit_slog(target, log::Level::Error, message);
}
#[doc(hidden)]
pub fn emit_slog_debug(target: &'static str, message: String) {
emit_slog(target, log::Level::Debug, message);
}
fn emit_slog(target: &'static str, level: log::Level, message: String) {
#[cfg(any(test, feature = "test-support"))]
capture_log_line(level, &message);
log::log!(target: canonical_slog_target(target).as_ref(), level, "{message}");
}
pub(crate) fn mint_index_build_id() -> String {
let n = INDEX_BUILD_COUNTER.fetch_add(1, Ordering::Relaxed);
format!("b-{}-{n}", std::process::id())
}
pub struct IndexBuildGuard {
previous: Option<IndexBuildScope>,
}
impl Drop for IndexBuildGuard {
fn drop(&mut self) {
CURRENT_INDEX_BUILD.with(|slot| {
*slot.borrow_mut() = self.previous.take();
});
}
}
pub fn install_index_build(scope: IndexBuildScope) -> IndexBuildGuard {
let previous = CURRENT_INDEX_BUILD.with(|slot| slot.replace(Some(scope)));
IndexBuildGuard { previous }
}
pub struct IndexBuildFailureGuard {
armed: bool,
}
impl IndexBuildFailureGuard {
pub fn new() -> Self {
Self { armed: true }
}
pub fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for IndexBuildFailureGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
let Some(scope) = current_index_build() else {
return;
};
if in_flight_build_id(scope.plane, &scope.root).as_deref() != Some(scope.build_id.as_str())
{
return;
}
log_current_index_event(
IndexEventKind::BuildFailed,
&[("reason", "error".to_string())],
);
}
}
pub fn current_index_build() -> Option<IndexBuildScope> {
CURRENT_INDEX_BUILD.with(|slot| slot.borrow().clone())
}
pub fn normalize_index_root(root: &Path) -> String {
root.to_string_lossy().replace('\\', "/")
}
fn sanitize_index_value(value: &str) -> String {
let mut out = String::with_capacity(value.len().max(1));
for ch in value.chars() {
match ch {
' ' | '\t' | '\n' | '\r' | '=' => out.push('_'),
'\\' => out.push('/'),
c if c.is_ascii_graphic() || c == '/' => out.push(c),
_ => out.push('_'),
}
}
if out.is_empty() {
out.push('-');
}
out
}
fn push_index_field(line: &mut String, key: &str, value: &str, max_bytes: usize) {
let sanitized = sanitize_index_value(value);
let addition = format!(" {key}={sanitized}");
if line.len() + addition.len() > max_bytes {
return;
}
line.push_str(&addition);
}
fn left_truncate_root(root: &str, max_bytes: usize) -> String {
if root.len() <= max_bytes {
return root.to_string();
}
let hash = format!("{:x}", Sha256::digest(root.as_bytes()));
let marker = format!(".../{}", &hash[..8]);
if max_bytes <= marker.len() {
return marker[..max_bytes].to_string();
}
let root = root.trim_end_matches('/');
let suffix_start = root.rmatch_indices('/').nth(1).map_or(0, |(i, _)| i + 1);
let keep = max_bytes.saturating_sub(marker.len() + 1);
let mut start = suffix_start.max(root.len().saturating_sub(keep));
while start < root.len() && !root.is_char_boundary(start) {
start += 1;
}
if start == root.len() {
marker
} else {
format!("{marker}/{}", &root[start..])
}
}
fn format_index_event_line(event: &IndexEvent) -> String {
let kind = sanitize_index_value(event.kind.as_str());
let plane = sanitize_index_value(event.plane.as_str());
let build_id = sanitize_index_value(&event.build_id);
let key = sanitize_index_value(&event.key);
let mut root = sanitize_index_value(&normalize_index_root(&event.root));
let prefix = format!("index_event kind={kind} plane={plane} build_id={build_id} root=");
let key_field = format!(" key={key}");
let extra_budget = INDEX_EVENT_MAX_BYTES
.saturating_sub(prefix.len() + key_field.len())
.saturating_sub(root.len().min(".../00000000".len()));
let mut extra_fields = String::new();
for numeric in [true, false] {
for (key, value) in &event.extra {
if value.parse::<u64>().is_ok() == numeric {
push_index_field(&mut extra_fields, key, value, extra_budget);
}
}
}
let root_budget = INDEX_EVENT_MAX_BYTES
.saturating_sub(prefix.len())
.saturating_sub(key_field.len())
.saturating_sub(extra_fields.len());
if root.len() > root_budget {
root = left_truncate_root(&root, root_budget);
}
format!("{prefix}{root}{key_field}{extra_fields}")
}
fn root_plane_key(root: &Path, plane: IndexPlane) -> (String, IndexPlane) {
(normalize_index_root(root), plane)
}
fn remember_in_flight(event: &IndexEvent) {
let key = root_plane_key(&event.root, event.plane);
if event.kind == IndexEventKind::BuildStarted {
if let Ok(mut signals) = INDEX_BUILD_START_SIGNALS.lock() {
signals.sequence = signals.sequence.wrapping_add(1);
let sequence = signals.sequence;
signals.last_by_root_plane.insert(key.clone(), sequence);
signals
.in_flight_by_root_plane
.insert(key.clone(), sequence);
if let Some(waiters) = signals.waiters.remove(&key) {
for (baseline, sender) in waiters {
if sequence > baseline {
let _ = sender.send(());
}
}
}
}
if let Ok(mut in_flight) = INDEX_LIFECYCLE.in_flight.lock() {
in_flight.insert(
key,
InFlightBuild {
build_id: event.build_id.clone(),
},
);
}
return;
}
if event.kind.is_terminal() {
if let Ok(mut in_flight) = INDEX_LIFECYCLE.in_flight.lock() {
in_flight.remove(&key);
}
if let Ok(mut signals) = INDEX_BUILD_START_SIGNALS.lock() {
signals.in_flight_by_root_plane.remove(&key);
}
release_index_build_start_waiters(event.plane, &event.root);
}
if event.kind == IndexEventKind::BuildReady {
if let Ok(mut unclaimed) = INDEX_LIFECYCLE.unclaimed.lock() {
unclaimed.insert(
key,
UnclaimedReady {
build_id: event.build_id.clone(),
key: event.key.clone(),
ready_at: Instant::now(),
},
);
}
}
}
fn emit_index_event_line(line: String) {
#[cfg(any(test, feature = "test-support"))]
if let Ok(mut slot) = INDEX_EVENT_CAPTURE.lock() {
if let Some(events) = slot.as_mut() {
events.push(line.clone());
}
}
crate::slog_info!("{}", line);
}
pub fn log_index_event(event: IndexEvent) {
remember_in_flight(&event);
emit_index_event_line(format_index_event_line(&event));
}
pub fn log_watcher_rescan(
root: &Path,
reason: RescanReason,
cost_ms: u64,
rss_delta_bytes: Option<i64>,
raw_events_since_last: u64,
) {
let reason = sanitize_index_value(reason.as_str());
let rss_delta = rss_delta_bytes
.map(|delta| delta.to_string())
.unwrap_or_else(|| "unavailable".to_string());
let prefix = "index_event kind=watcher_rescan plane=watcher root=";
let suffix = format!(
" reason={reason} cost_ms={cost_ms} rss_delta_bytes={rss_delta} raw_events_since_last={raw_events_since_last}"
);
let mut root = sanitize_index_value(&normalize_index_root(root));
let root_budget = INDEX_EVENT_MAX_BYTES
.saturating_sub(prefix.len())
.saturating_sub(suffix.len());
if root.len() > root_budget {
root = left_truncate_root(&root, root_budget);
}
emit_index_event_line(format!("{prefix}{root}{suffix}"));
}
pub(crate) fn log_current_index_event(kind: IndexEventKind, extra: &[(&'static str, String)]) {
let Some(scope) = current_index_build() else {
return;
};
let mut event = IndexEvent::from_scope(kind, &scope);
for (key, value) in extra {
event.extra.push((key, value.clone()));
}
log_index_event(event);
}
pub fn release_index_build_start_waiters(plane: IndexPlane, root: &Path) {
let waiters = INDEX_BUILD_START_SIGNALS
.lock()
.ok()
.and_then(|mut signals| signals.waiters.remove(&root_plane_key(root, plane)))
.unwrap_or_default();
for (_, sender) in waiters {
let _ = sender.send(());
}
}
pub(crate) fn in_flight_build_id(plane: IndexPlane, root: &Path) -> Option<String> {
INDEX_LIFECYCLE
.in_flight
.lock()
.ok()?
.get(&root_plane_key(root, plane))
.map(|build| build.build_id.clone())
}
pub(crate) fn claim_first_query(
plane: IndexPlane,
root: &Path,
tool: &str,
queue_ms: u64,
service_ms: u64,
status: &str,
) -> bool {
let slot = {
let Ok(mut unclaimed) = INDEX_LIFECYCLE.unclaimed.lock() else {
return false;
};
unclaimed.remove(&root_plane_key(root, plane))
};
let Some(slot) = slot else {
return false;
};
let ready_to_first_query_ms = slot.ready_at.elapsed().as_millis().min(u64::MAX as u128) as u64;
log_index_event(
IndexEvent::new(
IndexEventKind::FirstQuery,
plane,
slot.build_id,
root,
slot.key,
)
.field("tool", tool)
.field("queue_ms", queue_ms)
.field("service_ms", service_ms)
.field("status", status)
.field("ready_to_first_query_ms", ready_to_first_query_ms),
);
true
}
pub fn note_index_query(plane: IndexPlane, root: &Path, tool: &str, service_ms: u64, status: &str) {
match status {
"building" | "rebuilding" => {
let build_id = in_flight_build_id(plane, root);
note_tool_call_wait(WaitingOn::Build, build_id.as_deref(), 0);
}
_ => {
let queue_ms = TOOL_CALL_WAIT.with(|slot| slot.borrow().queue_ms);
claim_first_query(plane, root, tool, queue_ms, service_ms, status);
}
}
}
pub fn reset_tool_call_wait() {
TOOL_CALL_WAIT.with(|slot| *slot.borrow_mut() = ToolCallWaitState::default());
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn note_tool_call_wait(waiting_on: WaitingOn, build_id: Option<&str>, wait_ms: u64) {
TOOL_CALL_WAIT.with(|slot| {
let mut state = slot.borrow_mut();
state.waiting_on = waiting_on;
state.waiting_on_build_id = build_id.map(str::to_string);
state.wait_ms = state.wait_ms.saturating_add(wait_ms);
});
}
}
pub fn note_tool_call_queue_ms(queue_ms: u64) {
TOOL_CALL_WAIT.with(|slot| slot.borrow_mut().queue_ms = queue_ms);
}
pub fn take_tool_call_wait() -> (WaitingOn, Option<String>, u64) {
TOOL_CALL_WAIT.with(|slot| {
let state = std::mem::take(&mut *slot.borrow_mut());
(state.waiting_on, state.waiting_on_build_id, state.wait_ms)
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EditPhase {
Backup,
Write,
Format,
Syntax,
Validate,
Diff,
Lsp,
}
impl EditPhase {
const ALL: [EditPhase; 7] = [
EditPhase::Backup,
EditPhase::Write,
EditPhase::Format,
EditPhase::Syntax,
EditPhase::Validate,
EditPhase::Diff,
EditPhase::Lsp,
];
fn as_str(self) -> &'static str {
match self {
EditPhase::Backup => "backup",
EditPhase::Write => "write",
EditPhase::Format => "format",
EditPhase::Syntax => "syntax",
EditPhase::Validate => "validate",
EditPhase::Diff => "diff",
EditPhase::Lsp => "lsp",
}
}
fn index(self) -> usize {
self as usize
}
}
struct EditPhaseTimes {
elapsed: [Duration; 7],
depth: [u8; 7],
touched: bool,
}
thread_local! {
static EDIT_PHASES: RefCell<EditPhaseTimes> = const {
RefCell::new(EditPhaseTimes {
elapsed: [Duration::ZERO; 7],
depth: [0; 7],
touched: false,
})
};
}
pub struct EditPhaseTimer {
phase: EditPhase,
started: Instant,
}
pub fn time_edit_phase(phase: EditPhase) -> EditPhaseTimer {
EDIT_PHASES.with(|slot| {
let mut times = slot.borrow_mut();
times.depth[phase.index()] = times.depth[phase.index()].saturating_add(1);
});
EditPhaseTimer {
phase,
started: Instant::now(),
}
}
impl Drop for EditPhaseTimer {
fn drop(&mut self) {
let elapsed = self.started.elapsed();
EDIT_PHASES.with(|slot| {
let mut times = slot.borrow_mut();
let index = self.phase.index();
times.depth[index] = times.depth[index].saturating_sub(1);
if times.depth[index] == 0 {
times.elapsed[index] += elapsed;
times.touched = true;
}
});
}
}
pub fn reset_edit_phase_times() {
EDIT_PHASES.with(|slot| {
let mut times = slot.borrow_mut();
times.elapsed = [Duration::ZERO; 7];
times.touched = false;
});
}
pub fn take_edit_phase_times() -> Option<String> {
EDIT_PHASES.with(|slot| {
let mut times = slot.borrow_mut();
if !times.touched {
return None;
}
let rendered = EditPhase::ALL
.iter()
.map(|phase| {
format!(
"{}:{}",
phase.as_str(),
duration_millis_u64(times.elapsed[phase.index()])
)
})
.collect::<Vec<_>>()
.join(",");
times.elapsed = [Duration::ZERO; 7];
times.touched = false;
Some(rendered)
})
}
#[cfg(any(test, feature = "test-support"))]
pub fn capture_index_events<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
let _serial = INDEX_EVENT_CAPTURE_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Ok(mut slot) = INDEX_EVENT_CAPTURE.lock() {
*slot = Some(Vec::new());
}
let result = f();
let events = INDEX_EVENT_CAPTURE
.lock()
.ok()
.and_then(|mut slot| slot.take())
.unwrap_or_default();
(result, events)
}
pub fn init() {
init_with_stderr_mode(false);
}
pub fn init_subc() {
init_with_stderr_mode(true);
}
fn init_with_stderr_mode(subc: bool) {
SUBC_LOGGING.store(subc, Ordering::Relaxed);
if subc {
STDERR_MIRROR.get_or_init(|| {
stderr_mirror::Mirror::spawn(
io::stderr(),
stderr_mirror::QUEUE_CAPACITY,
Arc::clone(&STDERR_MIRROR_HEALTH),
)
.map(|(mirror, _worker)| mirror)
.unwrap_or_else(|_| stderr_mirror::Mirror::disabled(Arc::clone(&STDERR_MIRROR_HEALTH)))
});
}
let storage_root = crate::storage_path::storage_dir(None);
let logs_dir = storage_root.join("logs");
let file_name = format!("aft-{}.log", std::process::id());
let file_path = logs_dir.join(file_name);
let (sink, startup_sweep) =
initial_file_sink(&logs_dir, &file_path, Arc::clone(&LOG_WRITE_HEALTH));
let (tx, rx) = mpsc::sync_channel(LOG_CHANNEL_CAPACITY);
let sink = Arc::new(Mutex::new(Some(sink)));
let worker_sink = Arc::clone(&sink);
let file_tx = thread::Builder::new()
.name("aft-log-writer".to_string())
.spawn(move || {
run_file_writer(
worker_sink,
rx,
Arc::clone(&LOG_WRITE_HEALTH),
LOG_WRITE_RETRY_MIN,
)
})
.map(|_| {
if let Ok(mut control) = FILE_CONTROL.lock() {
control.tx = Some(tx.clone());
control.sink = Some(sink);
control.storage_root = Some(storage_root.clone());
}
Some(tx)
})
.unwrap_or_else(|error| {
write_stderr_once(&format!(
"[aft] WARN durable log disabled: cannot start writer thread: {error}\n"
));
None
});
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.target(env_logger::Target::Pipe(Box::new(TeeWriter::new(file_tx))))
.format(|buf, record| {
write_log_line(
buf,
&format_utc_timestamp(),
record.level(),
record.target(),
record.args(),
)
})
.init();
install_panic_hook(file_path);
if let Some(summary) = startup_sweep {
log_sweep_summary(summary);
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn subc_stderr_tee_for_test() -> impl Write + Send {
TeeWriter::new(None)
}
fn install_panic_hook(initial_path: PathBuf) {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let message = bounded_panic_text(format_args!("{info}"), PANIC_MESSAGE_BYTES);
let trace = std::backtrace::Backtrace::force_capture();
let trace = bounded_panic_text(format_args!("{trace}"), PANIC_BACKTRACE_BYTES);
let report = crate::log_redact::aft_redact_bytes(
format!(
"{} [aft] ERROR panic {message}\nforced backtrace:\n{trace}\n",
format_utc_timestamp()
)
.as_bytes(),
)
.into_owned();
let path = FILE_CONTROL
.try_lock()
.ok()
.and_then(|control| control.storage_root.clone())
.map(|root| {
root.join("logs")
.join(format!("aft-{}.log", std::process::id()))
})
.unwrap_or_else(|| initial_path.clone());
let persisted = open_private_log_file(&path, false).and_then(|mut file| {
file.write_all(&report)?;
aft_store::sync::sync_all_in_panic(&file, &path)
});
if persisted.is_err() {
let _ = io::stderr().write_all(&report);
}
previous(info);
}));
}
pub fn daemon_log_path() -> PathBuf {
let root = FILE_CONTROL
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.storage_root
.clone()
.unwrap_or_else(|| crate::storage_path::storage_dir(None));
root.join("logs")
.join(format!("aft-{}.log", std::process::id()))
}
pub fn write_watchdog_line(path: &Path, message: &str) -> io::Result<()> {
let mut line = Vec::new();
write_log_line(
&mut line,
&format_utc_timestamp(),
log::Level::Warn,
"aft::subc::stall_watchdog",
&format_args!("{message}"),
)?;
open_private_log_file(path, false)?.write_all(&crate::log_redact::aft_redact_bytes(&line))
}
pub fn write_preinit_warning(message: &str) -> io::Result<()> {
write_preinit_warning_to(&daemon_log_path(), message)
}
fn write_preinit_warning_to(path: &Path, message: &str) -> io::Result<()> {
if let Some(parent) = path.parent() {
create_private_log_dir(parent)?;
}
let mut line = Vec::new();
write_log_line(
&mut line,
&format_utc_timestamp(),
log::Level::Warn,
"aft::gh_shim_speech",
&format_args!("{message}"),
)?;
let mut file = open_private_log_file(path, false)?;
file.write_all(&crate::log_redact::aft_redact_bytes(&line))?;
aft_store::sync::sync_all(&file, path)
}
fn bounded_panic_text(args: std::fmt::Arguments<'_>, max_bytes: usize) -> String {
use std::fmt::Write;
let mut text = PanicText {
text: String::new(),
budget: max_bytes.saturating_sub(PANIC_TRUNCATION.len()),
truncated: false,
};
let _ = text.write_fmt(args);
if text.truncated {
text.text.push_str(PANIC_TRUNCATION);
}
text.text
}
struct PanicText {
text: String,
budget: usize,
truncated: bool,
}
impl std::fmt::Write for PanicText {
fn write_str(&mut self, value: &str) -> std::fmt::Result {
let remaining = self.budget.saturating_sub(self.text.len());
let mut end = value.len().min(remaining);
while !value.is_char_boundary(end) {
end -= 1;
}
self.text.push_str(&value[..end]);
self.truncated |= end != value.len();
Ok(())
}
}
fn write_log_line<W: Write + ?Sized>(
out: &mut W,
timestamp: &str,
level: log::Level,
target: &str,
message: &std::fmt::Arguments<'_>,
) -> io::Result<()> {
let prefix = if target.starts_with("aft::lsp") || target.starts_with("aft_lsp") {
"[aft-lsp]"
} else {
"[aft]"
};
writeln!(out, "{timestamp} {prefix} {level} {message}")
}
fn format_utc_timestamp() -> String {
let since_epoch = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default();
let seconds = format_epoch_secs(since_epoch.as_secs());
format!(
"{}.{:03}Z",
seconds.trim_end_matches('Z'),
since_epoch.subsec_millis()
)
}
fn format_epoch_secs(secs: u64) -> String {
let (days, rem) = (secs / 86_400, secs % 86_400);
let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}
fn prepare_file_sink(
logs_dir: &Path,
file_path: &Path,
) -> io::Result<(RotatingFile, SweepSummary)> {
create_private_log_dir(logs_dir)?;
let summary = sweep_logs(
logs_dir,
SystemTime::now(),
DEAD_PROCESS_LOG_MAX_AGE,
LOG_DIRECTORY_BUDGET_BYTES,
)?;
mark_log_sweep_ran();
let sink = RotatingFile::open(
file_path.to_path_buf(),
LOG_FILE_BYTES,
LOG_GENERATIONS,
ROTATION_CHECK_EVERY,
)?;
Ok((sink, summary))
}
fn initial_file_sink(
logs_dir: &Path,
file_path: &Path,
health: Arc<LogWriteHealth>,
) -> (RotatingFile, Option<SweepSummary>) {
match prepare_file_sink(logs_dir, file_path) {
Ok((sink, summary)) => (sink, Some(summary)),
Err(error) => {
LogWriteRecovery::new(health, LOG_WRITE_RETRY_MIN).failed(&error, 0, Instant::now());
write_stderr_once(&format!(
"[aft] WARN durable log will retry opening {}: {error}\n",
file_path.display()
));
(
RotatingFile::unopened(
file_path.to_path_buf(),
LOG_FILE_BYTES,
LOG_GENERATIONS,
ROTATION_CHECK_EVERY,
),
None,
)
}
}
}
enum LogMessage {
Write(Vec<u8>),
Reconfigure(PathBuf),
Flush(SyncSender<bool>),
}
type SharedFileSink<S = RotatingFile> = Arc<Mutex<Option<S>>>;
trait FileLogSink: Send {
fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()>;
fn reopen(&mut self) -> io::Result<()>;
fn discard_buffer(&mut self);
fn reconfigure(&mut self, storage_root: &Path) -> io::Result<SweepSummary>;
}
#[derive(Default)]
struct LogWriteHealth {
dropped_lines_total: AtomicU64,
last_write_error: Mutex<Option<String>>,
failing_since: Mutex<Option<String>>,
}
static LOG_WRITE_HEALTH: LazyLock<Arc<LogWriteHealth>> =
LazyLock::new(|| Arc::new(LogWriteHealth::default()));
pub fn durable_log_health() -> serde_json::Value {
let mut health = LOG_WRITE_HEALTH.snapshot();
let mut mirror = STDERR_MIRROR_HEALTH.snapshot();
mirror["best_effort"] = SUBC_LOGGING.load(Ordering::Relaxed).into();
health["stderr_mirror"] = mirror;
health
}
impl LogWriteHealth {
fn snapshot(&self) -> serde_json::Value {
serde_json::json!({
"dropped_lines_total": self.dropped_lines_total.load(Ordering::Relaxed),
"last_write_error": self.last_write_error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(),
"failing_since": self.failing_since.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(),
})
}
fn drop_lines(&self, count: u64) {
self.dropped_lines_total.fetch_add(count, Ordering::Relaxed);
PERF.file_lines_dropped.fetch_add(count, Ordering::Relaxed);
}
}
fn log_line_count(bytes: &[u8]) -> u64 {
bytes.iter().filter(|&&byte| byte == b'\n').count().max(1) as u64
}
struct LogWriteOutage {
since: String,
first_error: String,
last_error: String,
dropped_lines: u64,
retry_at: Instant,
}
struct LogWriteRecovery {
health: Arc<LogWriteHealth>,
outage: Option<LogWriteOutage>,
retry_min: Duration,
retry_delay: Duration,
}
impl LogWriteRecovery {
fn new(health: Arc<LogWriteHealth>, retry_min: Duration) -> Self {
let since = health
.failing_since
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let error = health
.last_write_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let outage = since.zip(error).map(|(since, error)| LogWriteOutage {
since,
first_error: error.clone(),
last_error: error,
dropped_lines: 0,
retry_at: Instant::now(),
});
Self {
health,
outage,
retry_min,
retry_delay: retry_min,
}
}
fn failed(&mut self, error: &io::Error, dropped_lines: u64, now: Instant) {
let error = crate::log_redact::aft_redactor(&error.to_string()).into_owned();
let outage = self.outage.get_or_insert_with(|| {
let since = format_utc_timestamp();
*self
.health
.failing_since
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(since.clone());
LogWriteOutage {
since,
first_error: error.clone(),
last_error: error.clone(),
dropped_lines: 0,
retry_at: now,
}
});
outage.last_error = error.clone();
outage.dropped_lines = outage.dropped_lines.saturating_add(dropped_lines);
outage.retry_at = now + self.retry_delay;
self.retry_delay = self.retry_delay.saturating_mul(2).min(LOG_WRITE_RETRY_MAX);
*self
.health
.last_write_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(error);
self.health.drop_lines(dropped_lines);
}
fn write_batch(
&mut self,
sink: &mut impl FileLogSink,
lines: &[Vec<u8>],
now: Instant,
) -> bool {
if lines.is_empty() {
return true;
}
let dropped_lines = lines.iter().map(|line| log_line_count(line)).sum();
if let Some(outage) = self.outage.as_mut() {
if now < outage.retry_at {
outage.dropped_lines = outage.dropped_lines.saturating_add(dropped_lines);
self.health.drop_lines(dropped_lines);
return false;
}
let recovered_at = format_utc_timestamp();
let errors = if outage.first_error == outage.last_error {
outage.first_error.clone()
} else {
format!("{}; last error: {}", outage.first_error, outage.last_error)
};
let marker = format!(
"{recovered_at} [aft] WARN log writes failed from {} to {recovered_at} ({errors}); {} lines dropped\n",
outage.since, outage.dropped_lines
);
if let Err(error) = sink
.reopen()
.and_then(|()| sink.write_batch(&[marker.into_bytes()]))
{
sink.discard_buffer();
self.failed(&error, dropped_lines, now);
return false;
}
self.outage = None;
self.retry_delay = self.retry_min;
*self
.health
.failing_since
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
if let Err(error) = sink.write_batch(lines) {
sink.discard_buffer();
self.failed(&error, dropped_lines, now);
return false;
}
true
}
}
#[derive(Default)]
struct FileControl {
tx: Option<SyncSender<LogMessage>>,
storage_root: Option<PathBuf>,
sink: Option<SharedFileSink>,
}
static FILE_CONTROL: LazyLock<Mutex<FileControl>> =
LazyLock::new(|| Mutex::new(FileControl::default()));
struct TeeWriter {
file_tx: Option<SyncSender<LogMessage>>,
stderr: StderrOutput,
}
impl TeeWriter {
fn new(file_tx: Option<SyncSender<LogMessage>>) -> Self {
Self {
file_tx,
stderr: StderrOutput::for_process(),
}
}
}
enum StderrOutput {
Standalone,
Subc(stderr_mirror::Mirror),
}
impl StderrOutput {
fn for_process() -> Self {
if SUBC_LOGGING.load(Ordering::Relaxed) {
Self::Subc(STDERR_MIRROR.get().cloned().unwrap_or_else(|| {
stderr_mirror::Mirror::disabled(Arc::clone(&STDERR_MIRROR_HEALTH))
}))
} else {
Self::Standalone
}
}
}
impl Write for StderrOutput {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self {
Self::Standalone => {
let _ = io::stderr().write_all(bytes);
}
Self::Subc(mirror) => mirror.record(bytes),
}
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
match self {
Self::Standalone => {
let _ = io::stderr().flush();
}
Self::Subc(mirror) => mirror.flush(),
}
Ok(())
}
}
impl Write for TeeWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let line = crate::log_redact::aft_redact_bytes(buf);
enqueue_file_line(&mut self.file_tx, &line, &LOG_WRITE_HEALTH);
let _ = self.stderr.write_all(&line);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
let _ = self.stderr.flush();
Ok(())
}
}
fn enqueue_file_line(
file_tx: &mut Option<SyncSender<LogMessage>>,
line: &[u8],
health: &LogWriteHealth,
) {
if let Some(tx) = file_tx.as_ref() {
match tx.try_send(LogMessage::Write(line.to_vec())) {
Ok(()) => {}
Err(TrySendError::Full(_)) => health.drop_lines(log_line_count(line)),
Err(TrySendError::Disconnected(_)) => {
health.drop_lines(log_line_count(line));
*file_tx = None;
}
}
}
}
fn run_file_writer<S: FileLogSink>(
shared_sink: SharedFileSink<S>,
rx: mpsc::Receiver<LogMessage>,
health: Arc<LogWriteHealth>,
retry_min: Duration,
) {
let mut recovery = LogWriteRecovery::new(health, retry_min);
let mut durable = true;
#[cfg(debug_assertions)]
let test_delay = std::env::var("AFT_TEST_LOG_WRITER_DELAY_MS")
.ok()
.and_then(|value| value.parse::<u64>().ok())
.map(std::time::Duration::from_millis);
#[cfg(debug_assertions)]
let test_flush_hold = std::env::var("AFT_TEST_LOG_FLUSH_HOLD_MS")
.ok()
.and_then(|value| value.parse::<u64>().ok())
.map(std::time::Duration::from_millis);
while let Ok(message) = rx.recv() {
#[cfg(debug_assertions)]
if let Some(delay) = test_delay {
thread::sleep(delay);
}
let mut lines = Vec::new();
let mut reconfigure = None;
let mut flushed = None;
match message {
LogMessage::Write(line) => {
lines.push(line);
while lines.len() < 256 {
match rx.try_recv() {
Ok(LogMessage::Write(line)) => lines.push(line),
Ok(LogMessage::Reconfigure(storage_root)) => {
reconfigure = Some(storage_root);
break;
}
Ok(LogMessage::Flush(done)) => {
flushed = Some(done);
break;
}
Err(_) => break,
}
}
}
LogMessage::Reconfigure(storage_root) => reconfigure = Some(storage_root),
LogMessage::Flush(done) => flushed = Some(done),
}
let mut slot = shared_sink
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(sink) = slot.as_mut() else { break };
durable &= recovery.write_batch(sink, &lines, Instant::now());
if let Some(done) = flushed {
let confirmed = durable;
durable = true;
#[cfg(debug_assertions)]
if let Some(hold) = test_flush_hold {
drop(slot);
thread::sleep(hold);
let _ = done.try_send(confirmed);
continue;
}
let _ = done.try_send(confirmed);
}
if let Some(storage_root) = reconfigure {
let logs_dir = storage_root.join("logs");
let path = logs_dir.join(format!("aft-{}.log", std::process::id()));
match sink.reconfigure(&storage_root) {
Ok(summary) => {
if let Some(outage) = recovery.outage.as_mut() {
outage.retry_at = Instant::now();
}
log_sweep_summary(summary);
}
Err(error) => write_stderr_once(&format!(
"[aft] WARN durable log could not switch to {}: {error}\n",
path.display()
)),
}
}
}
}
fn write_stderr_once(message: &str) {
write_stderr_diagnostic(message);
}
pub fn write_stderr_diagnostic(message: &str) {
let line = crate::log_redact::aft_redact_bytes(message.as_bytes());
let _ = StderrOutput::for_process().write_all(&line);
}
pub fn flush_durable_log(timeout: std::time::Duration) -> bool {
let tx = match FILE_CONTROL.lock() {
Ok(control) => control.tx.clone(),
Err(_) => None,
};
let Some(tx) = tx else {
return false;
};
let (done_tx, done_rx) = mpsc::sync_channel(1);
if tx.send(LogMessage::Flush(done_tx)).is_err() {
return false;
}
done_rx.recv_timeout(timeout).unwrap_or(false)
}
pub fn flush_stderr_on_exit(timeout: std::time::Duration) -> bool {
STDERR_MIRROR
.get()
.is_none_or(|mirror| mirror.drain_on_exit(timeout))
}
#[cfg(debug_assertions)]
pub fn hold_stderr_mirror_until_exit_fence() {
if let Some(mirror) = STDERR_MIRROR.get() {
mirror.hold_until_exit_fence();
}
}
pub fn write_terminal_log_sync(message: &str) -> io::Result<()> {
let shared = FILE_CONTROL
.lock()
.map_err(|_| io::Error::other("log control poisoned"))?
.sink
.clone()
.ok_or_else(|| io::Error::other("durable log disabled"))?;
let mut slot = shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut sink = slot
.take()
.ok_or_else(|| io::Error::other("log sink already stopped"))?;
if let Some(mut writer) = sink.writer.take() {
writer.flush()?;
}
write_terminal_line(&sink, &mut StderrOutput::for_process(), message)
}
fn write_terminal_line(
sink: &RotatingFile,
stderr: &mut impl Write,
message: &str,
) -> io::Result<()> {
let mut line = Vec::new();
write_log_line(
&mut line,
&format_utc_timestamp(),
log::Level::Info,
"aft",
&format_args!("{message}"),
)?;
let line = crate::log_redact::aft_redact_bytes(&line);
let _ = stderr.write_all(&line);
let mut file = open_private_log_file(&sink.path, false)?;
file.write_all(&line)?;
aft_store::sync::sync_all(&file, &sink.path)?;
sink.write_counter.credit_logical(line.len() as u64);
Ok(())
}
struct RotatingFile {
path: PathBuf,
writer: Option<BufWriter<File>>,
size: u64,
threshold: u64,
generations: usize,
check_every: u64,
writes_since_check: u64,
write_counter: crate::write_counters::Counter,
}
impl RotatingFile {
fn unopened(path: PathBuf, threshold: u64, generations: usize, check_every: u64) -> Self {
Self {
path,
writer: None,
size: 0,
threshold,
generations,
check_every: check_every.max(1),
writes_since_check: 0,
write_counter: crate::write_counters::process_root_counter(
crate::write_counters::Domain::Logs,
),
}
}
fn open(
path: PathBuf,
threshold: u64,
generations: usize,
check_every: u64,
) -> io::Result<Self> {
let file = open_private_log_file(&path, false)?;
#[cfg(unix)]
{
tighten_if_owned(&path, LOG_FILE_MODE);
for generation in 1..=generations {
tighten_if_owned(&rotated_path(&path, generation), LOG_FILE_MODE);
}
}
let size = file.metadata()?.len();
let mut sink = Self::unopened(path, threshold, generations, check_every);
sink.writer = Some(BufWriter::new(file));
sink.size = size;
if size > threshold {
sink.rotate()?;
}
Ok(sink)
}
fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
let batch_bytes = lines.iter().map(Vec::len).sum::<usize>() as u64;
self.writes_since_check = self.writes_since_check.saturating_add(lines.len() as u64);
if self.writes_since_check >= self.check_every
&& self.size > 0
&& self.size.saturating_add(batch_bytes) > self.threshold
{
self.rotate()?;
}
let writer = self
.writer
.as_mut()
.ok_or_else(|| io::Error::other("log writer unavailable"))?;
for line in lines {
writer.write_all(line)?;
}
writer.flush()?;
self.write_counter.credit_logical(batch_bytes);
self.size = self.size.saturating_add(batch_bytes);
if self.writes_since_check >= self.check_every {
self.writes_since_check = 0;
}
Ok(())
}
fn rotate(&mut self) -> io::Result<()> {
if let Some(mut writer) = self.writer.take() {
if let Err(error) = writer.flush() {
let _ = writer.into_parts();
return Err(error);
}
}
if self.generations > 0 {
let oldest = rotated_path(&self.path, self.generations);
remove_file_if_present(&oldest)?;
for generation in (1..self.generations).rev() {
let from = rotated_path(&self.path, generation);
let to = rotated_path(&self.path, generation + 1);
rename_if_present(&from, &to)?;
}
rename_if_present(&self.path, &rotated_path(&self.path, 1))?;
} else {
remove_file_if_present(&self.path)?;
}
let file = open_private_log_file(&self.path, true)?;
self.writer = Some(BufWriter::new(file));
self.size = 0;
self.writes_since_check = 0;
Ok(())
}
}
impl FileLogSink for RotatingFile {
fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
RotatingFile::write_batch(self, lines)
}
fn reopen(&mut self) -> io::Result<()> {
self.discard_buffer();
create_private_log_dir(
self.path
.parent()
.ok_or_else(|| io::Error::other("log path has no parent"))?,
)?;
let file = open_private_log_file(&self.path, false)?;
self.size = file.metadata()?.len();
self.writer = Some(BufWriter::new(file));
self.writes_since_check = 0;
Ok(())
}
fn discard_buffer(&mut self) {
if let Some(writer) = self.writer.take() {
let _ = writer.into_parts();
}
}
fn reconfigure(&mut self, storage_root: &Path) -> io::Result<SweepSummary> {
let logs_dir = storage_root.join("logs");
let path = logs_dir.join(format!("aft-{}.log", std::process::id()));
let (sink, summary) = prepare_file_sink(&logs_dir, &path)?;
self.discard_buffer();
*self = sink;
Ok(summary)
}
}
fn rotated_path(base: &Path, generation: usize) -> PathBuf {
let mut path = base.as_os_str().to_os_string();
path.push(format!(".{generation}"));
PathBuf::from(path)
}
#[cfg(unix)]
const LOG_FILE_MODE: u32 = crate::private_storage::FILE_MODE;
fn create_private_log_dir(dir: &Path) -> io::Result<()> {
crate::private_storage::open_dir(dir.parent().unwrap_or(dir), dir)
}
fn open_private_log_file(path: &Path, truncate: bool) -> io::Result<File> {
let mut options = crate::private_storage::options();
options.create(true);
if truncate {
options.write(true).truncate(true);
} else {
options.append(true);
}
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(LOG_FILE_MODE);
}
options.open(path)
}
#[cfg(unix)]
fn tighten_if_owned(path: &Path, mode: u32) {
use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
if path
.parent()
.into_iter()
.chain(path.parent().and_then(Path::parent))
.any(|dir| fs::symlink_metadata(dir).is_ok_and(|metadata| metadata.is_symlink()))
{
return;
}
let Ok(file) = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
else {
return;
};
let Ok(metadata) = file.metadata() else {
return;
};
let euid = unsafe { libc::geteuid() };
if metadata.uid() != euid || metadata.mode() & 0o777 & !mode == 0 {
return;
}
let _ = file.set_permissions(fs::Permissions::from_mode(mode));
}
fn remove_file_if_present(path: &Path) -> io::Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
fn rename_if_present(from: &Path, to: &Path) -> io::Result<()> {
match fs::rename(from, to) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct SweepSummary {
removed_files: usize,
bytes_freed: u64,
recycled_pids: usize,
over_budget_bytes: u64,
}
struct ProcessLogFile {
path: PathBuf,
modified: Option<SystemTime>,
bytes: u64,
dead: bool,
old_enough: bool,
removed: bool,
}
fn relic_plugin_rotation(name: &str) -> bool {
let Some(rest) = name.strip_prefix("aft-plugin") else {
return false;
};
let Some((_, generation)) = rest.rsplit_once(".log.") else {
return false;
};
generation
.parse::<u32>()
.is_ok_and(|generation| generation >= 2)
}
fn log_sweep_summary(summary: SweepSummary) {
crate::slog_info!(
"log retention sweep: removed_files={} bytes_freed={} recycled_pids={}",
summary.removed_files,
summary.bytes_freed,
summary.recycled_pids
);
if summary.over_budget_bytes > 0 {
crate::slog_warn!(
"log directory over budget by {} bytes after sweep: the newest dead process log is kept as the record of that process's exit",
summary.over_budget_bytes
);
}
}
fn sweep_logs(
dir: &Path,
now: SystemTime,
max_age: Duration,
budget_bytes: u64,
) -> io::Result<SweepSummary> {
let mut total_bytes = 0_u64;
let mut process_logs = Vec::new();
let mut relic_rotations = Vec::new();
let mut live_pids = BTreeMap::new();
let mut recycled_count = 0_usize;
let own_pid = std::process::id();
for entry in fs::read_dir(dir)? {
let entry = match entry {
Ok(entry) => entry,
Err(_) => continue,
};
let metadata = match entry.metadata() {
Ok(metadata) if metadata.is_file() => metadata,
Ok(_) | Err(_) => continue,
};
let bytes = metadata.len();
total_bytes = total_bytes.saturating_add(bytes);
let name = entry.file_name();
let name = name.to_string_lossy();
if relic_plugin_rotation(&name) {
relic_rotations.push((entry.path(), bytes));
continue;
}
let pid = match name.as_ref() {
"aft-plugin.log" => continue,
_ => process_log_pid(&name),
};
let Some(pid) = pid else {
continue;
};
let modified = metadata.modified().ok();
let old_enough = modified
.and_then(|modified| now.duration_since(modified).ok())
.is_some_and(|age| age >= max_age);
let alive = *live_pids.entry(pid).or_insert_with(|| {
if !is_process_alive(pid) {
return false;
}
let recycled = pid_started_after_last_write(pid, modified);
if recycled {
recycled_count += 1;
}
!recycled
});
process_logs.push(ProcessLogFile {
path: entry.path(),
modified,
bytes,
dead: pid != own_pid && !alive,
old_enough,
removed: false,
});
}
let mut summary = SweepSummary {
recycled_pids: recycled_count,
..SweepSummary::default()
};
for file in &mut process_logs {
if file.dead && file.old_enough && remove_sweep_candidate(&file.path) {
file.removed = true;
total_bytes = total_bytes.saturating_sub(file.bytes);
summary.removed_files += 1;
summary.bytes_freed = summary.bytes_freed.saturating_add(file.bytes);
}
}
for (path, bytes) in &relic_rotations {
if remove_sweep_candidate(path) {
total_bytes = total_bytes.saturating_sub(*bytes);
summary.removed_files += 1;
summary.bytes_freed = summary.bytes_freed.saturating_add(*bytes);
}
}
process_logs.sort_by_key(|file| file.modified);
let protected = process_logs
.iter()
.rposition(|file| file.dead && !file.removed && !file.old_enough);
for (index, file) in process_logs
.iter_mut()
.enumerate()
.filter(|(_, file)| file.dead && !file.removed)
{
if total_bytes <= budget_bytes {
break;
}
if Some(index) == protected {
continue;
}
if remove_sweep_candidate(&file.path) {
file.removed = true;
total_bytes = total_bytes.saturating_sub(file.bytes);
summary.removed_files += 1;
summary.bytes_freed = summary.bytes_freed.saturating_add(file.bytes);
}
}
summary.over_budget_bytes = total_bytes.saturating_sub(budget_bytes);
Ok(summary)
}
const PID_REUSE_TOLERANCE_MS: u64 = 2_000;
fn pid_started_after_last_write(pid: u32, modified: Option<SystemTime>) -> bool {
let Some(modified_ms) = modified
.and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|since_epoch| since_epoch.as_millis() as u64)
else {
return false;
};
crate::process_identity::process_start_time_ms(pid)
.is_some_and(|started_ms| started_ms > modified_ms.saturating_add(PID_REUSE_TOLERANCE_MS))
}
fn remove_sweep_candidate(path: &Path) -> bool {
fs::remove_file(path).is_ok()
}
fn process_log_pid(name: &str) -> Option<u32> {
let rest = name.strip_prefix("aft-")?;
let (pid, suffix) = rest.split_once(".log")?;
if !suffix.is_empty()
&& !(suffix.starts_with('.') && suffix[1..].chars().all(|ch| ch.is_ascii_digit()))
{
return None;
}
pid.parse().ok()
}
static LAST_LOG_SWEEP: LazyLock<Mutex<Option<Instant>>> = LazyLock::new(|| Mutex::new(None));
fn mark_log_sweep_ran() {
if let Ok(mut last_run) = LAST_LOG_SWEEP.lock() {
*last_run = Some(Instant::now());
}
}
pub fn maybe_sweep_logs() {
let now = Instant::now();
let should_run = LAST_LOG_SWEEP
.lock()
.map(|mut last_run| {
if last_run.is_some_and(|last| now.duration_since(last) < LOG_SWEEP_INTERVAL) {
false
} else {
*last_run = Some(now);
true
}
})
.unwrap_or(false);
if !should_run {
return;
}
let spawned = std::thread::Builder::new()
.name("aft-log-sweep".to_owned())
.spawn(sweep_logs_now);
if let Err(error) = spawned {
crate::slog_warn!("log retention sweep could not start: {}", error);
}
}
fn sweep_logs_now() {
let storage_root = FILE_CONTROL
.lock()
.ok()
.and_then(|control| control.storage_root.clone())
.unwrap_or_else(|| crate::storage_path::storage_dir(None));
let logs_dir = storage_root.join("logs");
match sweep_logs(
&logs_dir,
SystemTime::now(),
DEAD_PROCESS_LOG_MAX_AGE,
LOG_DIRECTORY_BUDGET_BYTES,
) {
Ok(summary) => log_sweep_summary(summary),
Err(error) => crate::slog_warn!(
"log retention sweep failed for {}: {}",
logs_dir.display(),
error
),
}
}
#[derive(Default)]
struct PerfMetrics {
watcher_ingested: AtomicU64,
watcher_paths: AtomicU64,
watcher_dropped: AtomicU64,
drain_slices: AtomicU64,
semantic_collects: AtomicU64,
semantic_files: AtomicU64,
semantic_chunks: AtomicU64,
semantic_ms: AtomicU64,
callgraph_invalidations: AtomicU64,
file_lines_dropped: AtomicU64,
tool_call_count: AtomicU64,
tool_calls: Mutex<VecDeque<ToolCallPerfSample>>,
tier2: Mutex<BTreeMap<String, (u64, u64)>>,
next_sample_ns: AtomicU64,
reporter: Mutex<PerfReporter>,
}
struct PerfReporter {
last_report: Instant,
last_completed_interactive: u64,
last_completed_maintenance: u64,
last_tool_call_count: u64,
}
impl Default for PerfReporter {
fn default() -> Self {
Self {
last_report: Instant::now(),
last_completed_interactive: 0,
last_completed_maintenance: 0,
last_tool_call_count: 0,
}
}
}
#[derive(Clone, Copy)]
struct ToolCallPerfSample {
total_ms: u64,
queue_ms: u64,
}
#[derive(Clone, Copy, Default)]
struct ToolCallPerfSummary {
window: usize,
p50_total_ms: u64,
max_total_ms: u64,
p50_queue_ms: u64,
max_queue_ms: u64,
}
#[derive(Clone, Copy, Default)]
struct ExecutorSample {
interactive_running: usize,
maintenance_running: usize,
interactive_queued: usize,
maintenance_queued: usize,
interactive_oldest_ms: Option<u64>,
maintenance_oldest_ms: Option<u64>,
}
static PERF: LazyLock<PerfMetrics> = LazyLock::new(PerfMetrics::default);
pub fn sync_storage_root(storage_root: PathBuf) {
let Ok(mut control) = FILE_CONTROL.lock() else {
return;
};
if control.storage_root.as_ref() == Some(&storage_root) {
return;
}
let Some(tx) = control.tx.as_ref() else {
return;
};
if tx
.try_send(LogMessage::Reconfigure(storage_root.clone()))
.is_ok()
{
control.storage_root = Some(storage_root);
}
}
pub fn note_watcher_events(count: usize) {
PERF.watcher_ingested
.fetch_add(count as u64, Ordering::Relaxed);
}
pub fn note_drain_paths(count: usize) {
PERF.watcher_paths
.fetch_add(count as u64, Ordering::Relaxed);
}
pub fn note_watcher_overflow() {
PERF.watcher_dropped.fetch_add(1, Ordering::Relaxed);
}
pub fn note_drain_slice() {
PERF.drain_slices.fetch_add(1, Ordering::Relaxed);
}
pub fn note_semantic_collect(chunks: usize, files: usize, elapsed_ms: u64) {
PERF.semantic_collects.fetch_add(1, Ordering::Relaxed);
PERF.semantic_chunks
.fetch_add(chunks as u64, Ordering::Relaxed);
PERF.semantic_files
.fetch_add(files as u64, Ordering::Relaxed);
PERF.semantic_ms.fetch_add(elapsed_ms, Ordering::Relaxed);
}
pub fn note_tier2_scan(category: String, elapsed_ms: u64) {
if let Ok(mut tier2) = PERF.tier2.lock() {
let entry = tier2.entry(category).or_default();
entry.0 = entry.0.saturating_add(1);
entry.1 = entry.1.saturating_add(elapsed_ms);
}
}
pub fn note_callgraph_invalidations(files: usize) {
PERF.callgraph_invalidations
.fetch_add(files as u64, Ordering::Relaxed);
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ToolCallCaller {
Agent,
Plumbing,
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static SLOW_TOOL_CALL_CAPTURE: RefCell<Vec<(log::Level, String)>> =
const { RefCell::new(Vec::new()) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn take_slow_tool_call_logs_for_test() -> Vec<String> {
SLOW_TOOL_CALL_CAPTURE.with(|captured| {
captured
.borrow_mut()
.drain(..)
.map(|(_, message)| message)
.collect()
})
}
fn slow_tool_call_level(caller: ToolCallCaller) -> log::Level {
match caller {
ToolCallCaller::Agent => log::Level::Warn,
ToolCallCaller::Plumbing => log::Level::Debug,
}
}
pub fn note_tool_call_trace(
name: &str,
session: &str,
root: &Path,
channel: u16,
corr: u64,
phases: ToolCallPhaseDurations,
caller: ToolCallCaller,
) {
let sample = ToolCallPerfSample {
total_ms: duration_millis_u64(phases.total),
queue_ms: duration_millis_u64(phases.queue),
};
if let Ok(mut samples) = PERF.tool_calls.lock() {
if samples.len() == TOOL_CALL_SAMPLE_CAPACITY {
samples.pop_front();
}
samples.push_back(sample);
PERF.tool_call_count.fetch_add(1, Ordering::Relaxed);
}
let waiting_on_build_id = phases.waiting_on_build_id.as_deref().unwrap_or("-");
crate::slog_debug!(
"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={}",
name,
session,
channel,
corr,
duration_millis_f64(phases.total),
duration_millis_f64(phases.queue),
duration_millis_f64(phases.setup),
duration_millis_f64(phases.translate),
duration_millis_f64(phases.execute),
duration_millis_f64(phases.format),
duration_millis_f64(phases.finalize),
duration_millis_f64(phases.egress),
duration_millis_f64(phases.egress_enqueue),
duration_millis_f64(phases.egress_queue),
duration_millis_f64(phases.egress_prepare),
duration_millis_f64(phases.egress_write),
phases.frame_bytes,
phases.writer_queue_depth,
phases.writer_active_at_enqueue,
phases.writer_queue_was_full,
phases.writer_reserve_timeouts,
phases.waiting_on.as_str(),
waiting_on_build_id,
phases.wait_ms,
root.display(),
);
let diagnostic_elapsed = if phases.intentional_wait {
phases.total.saturating_sub(phases.execute)
} else {
phases.total
};
if diagnostic_elapsed > SLOW_TOOL_CALL_THRESHOLD {
let level = slow_tool_call_level(caller);
let mut detail = String::new();
if let Some(shape) = phases.arg_shape.as_deref() {
detail.push(' ');
detail.push_str(shape);
}
if let Some(edit_phases) = phases.edit_phases.as_deref() {
detail.push_str(" edit_phases=");
detail.push_str(edit_phases);
}
let message = format!(
"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={}",
name,
session,
channel,
corr,
duration_millis_u64(phases.total),
slow_phase_time(phases.queue, None),
slow_phase_time(phases.setup, phases.cpu.setup),
slow_phase_time(phases.translate, phases.cpu.translate),
slow_phase_time(phases.execute, phases.cpu.execute),
slow_phase_time(phases.format, phases.cpu.format),
slow_phase_time(phases.finalize, phases.cpu.finalize),
slow_phase_time(phases.egress, None),
slow_phase_time(phases.egress_enqueue, None),
slow_phase_time(phases.egress_queue, None),
slow_phase_time(phases.egress_prepare, phases.cpu.egress_prepare),
slow_phase_time(phases.egress_write, None),
phases.frame_bytes,
phases.writer_queue_depth,
phases.writer_active_at_enqueue,
phases.writer_queue_was_full,
phases.writer_reserve_timeouts,
phases.waiting_on.as_str(),
waiting_on_build_id,
phases.wait_ms,
detail,
root.display(),
);
#[cfg(any(test, feature = "test-support"))]
SLOW_TOOL_CALL_CAPTURE
.with(|captured| captured.borrow_mut().push((level, message.clone())));
log::log!(level, "{}{}", crate::log_ctx::session_prefix(), message);
}
}
fn slow_phase_time(wall: Duration, cpu: Option<Duration>) -> String {
match cpu {
Some(cpu) => format!(
"{:.3}ms/cpu={:.3}ms",
duration_millis_f64(wall),
duration_millis_f64(cpu)
),
None => format!("{:.3}ms/cpu=?", duration_millis_f64(wall)),
}
}
pub fn perf_tick<C: ExecutorContext>(executor: Option<&Executor<C>>) {
if !perf_sample_due() {
return;
}
let sample = executor.and_then(|executor| {
executor
.try_dispatch_liveness_snapshot()
.map(|snapshot| ExecutorSample {
interactive_running: snapshot.running.interactive,
maintenance_running: snapshot.running.maintenance,
interactive_queued: snapshot.interactive.queued,
maintenance_queued: snapshot.maintenance.queued,
interactive_oldest_ms: snapshot.interactive.oldest_age_ms,
maintenance_oldest_ms: snapshot.maintenance.oldest_age_ms,
})
});
let completion_counts = executor.map_or((0, 0), Executor::<C>::completion_counts);
report_perf_tick(&PERF, sample, completion_counts);
}
fn report_perf_tick(
perf: &PerfMetrics,
sample: Option<ExecutorSample>,
completion_counts: (u64, u64),
) {
let tool_call_count = perf.tool_call_count.load(Ordering::Relaxed);
let (completed_interactive, completed_maintenance, new_tool_calls) = {
let Ok(mut reporter) = perf.reporter.lock() else {
return;
};
if reporter.last_report.elapsed() < perf_tick_interval() {
return;
}
reporter.last_report = Instant::now();
let completed = (
completion_counts
.0
.saturating_sub(reporter.last_completed_interactive),
completion_counts
.1
.saturating_sub(reporter.last_completed_maintenance),
tool_call_count.saturating_sub(reporter.last_tool_call_count),
);
reporter.last_completed_interactive = completion_counts.0;
reporter.last_completed_maintenance = completion_counts.1;
reporter.last_tool_call_count = tool_call_count;
completed
};
let watcher_ingested = perf.watcher_ingested.swap(0, Ordering::Relaxed);
let watcher_paths = perf.watcher_paths.swap(0, Ordering::Relaxed);
let watcher_dropped = perf.watcher_dropped.swap(0, Ordering::Relaxed);
let drain_slices = perf.drain_slices.swap(0, Ordering::Relaxed);
let semantic_collects = perf.semantic_collects.swap(0, Ordering::Relaxed);
let semantic_files = perf.semantic_files.swap(0, Ordering::Relaxed);
let semantic_chunks = perf.semantic_chunks.swap(0, Ordering::Relaxed);
let semantic_ms = perf.semantic_ms.swap(0, Ordering::Relaxed);
let callgraph_invalidations = perf.callgraph_invalidations.swap(0, Ordering::Relaxed);
let file_lines_dropped = perf.file_lines_dropped.swap(0, Ordering::Relaxed);
let tier2 = perf
.tier2
.lock()
.map(|mut tier2| std::mem::take(&mut *tier2))
.unwrap_or_default();
let tool_calls = perf
.tool_calls
.lock()
.map(|samples| summarize_tool_calls(&samples))
.unwrap_or_default();
let executor_busy = sample.is_some_and(|sample| {
sample.interactive_running > 0
|| sample.maintenance_running > 0
|| sample.interactive_queued > 0
|| sample.maintenance_queued > 0
});
let active = watcher_ingested > 0
|| watcher_paths > 0
|| watcher_dropped > 0
|| semantic_collects > 0
|| callgraph_invalidations > 0
|| completed_interactive > 0
|| completed_maintenance > 0
|| new_tool_calls > 0
|| file_lines_dropped > 0
|| !tier2.is_empty()
|| executor_busy;
if !active {
return;
}
let tier2_summary = if tier2.is_empty() {
"none".to_string()
} else {
tier2
.into_iter()
.map(|(category, (count, ms))| format!("{category}:{count}/{ms}ms"))
.collect::<Vec<_>>()
.join(",")
};
let sample = sample.unwrap_or_default();
crate::slog_info!(
"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={}",
watcher_ingested,
watcher_paths,
watcher_dropped,
drain_slices,
tier2_summary,
semantic_collects,
semantic_files,
semantic_chunks,
semantic_ms,
callgraph_invalidations,
completed_interactive,
completed_maintenance,
format_optional_ms(sample.interactive_oldest_ms),
format_optional_ms(sample.maintenance_oldest_ms),
format_tool_call_summary(new_tool_calls, tool_calls),
file_lines_dropped,
);
}
fn duration_millis_f64(duration: Duration) -> f64 {
duration.as_secs_f64() * 1_000.0
}
fn duration_millis_u64(duration: Duration) -> u64 {
duration.as_millis().min(u64::MAX as u128) as u64
}
fn summarize_tool_calls(samples: &VecDeque<ToolCallPerfSample>) -> ToolCallPerfSummary {
if samples.is_empty() {
return ToolCallPerfSummary::default();
}
let mut totals = samples
.iter()
.map(|sample| sample.total_ms)
.collect::<Vec<_>>();
let mut queues = samples
.iter()
.map(|sample| sample.queue_ms)
.collect::<Vec<_>>();
totals.sort_unstable();
queues.sort_unstable();
let median_index = (samples.len() - 1) / 2;
ToolCallPerfSummary {
window: samples.len(),
p50_total_ms: totals[median_index],
max_total_ms: totals[totals.len() - 1],
p50_queue_ms: queues[median_index],
max_queue_ms: queues[queues.len() - 1],
}
}
fn format_tool_call_summary(new_tool_calls: u64, summary: ToolCallPerfSummary) -> String {
format!(
"toolcall={{new:{new_tool_calls},window:{},p50_total_ms:{},max_total_ms:{},p50_queue_ms:{},max_queue_ms:{}}}",
summary.window,
summary.p50_total_ms,
summary.max_total_ms,
summary.p50_queue_ms,
summary.max_queue_ms,
)
}
fn format_optional_ms(value: Option<u64>) -> String {
value
.map(|value| value.to_string())
.unwrap_or_else(|| "none".to_string())
}
fn perf_sample_due() -> bool {
static ORIGIN: LazyLock<Instant> = LazyLock::new(Instant::now);
let now_ns = ORIGIN.elapsed().as_nanos().min(u64::MAX as u128) as u64;
let mut deadline = PERF.next_sample_ns.load(Ordering::Relaxed);
loop {
if now_ns < deadline {
return false;
}
let next = now_ns.saturating_add(PERF_SAMPLE_INTERVAL.as_nanos() as u64);
match PERF.next_sample_ns.compare_exchange_weak(
deadline,
next,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => return true,
Err(observed) => deadline = observed,
}
}
}
fn perf_tick_interval() -> Duration {
static INTERVAL: OnceLock<Duration> = OnceLock::new();
*INTERVAL.get_or_init(|| {
std::env::var("AFT_PERF_TICK_INTERVAL_MS")
.ok()
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| *value > 0)
.map(Duration::from_millis)
.unwrap_or(DEFAULT_PERF_TICK_INTERVAL)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RescanReason {
BufferOverflow,
KernelDropped,
UserDropped,
Unknown,
}
impl RescanReason {
pub fn as_str(self) -> &'static str {
match self {
Self::BufferOverflow => "buffer_overflow",
Self::KernelDropped => "kernel_dropped",
Self::UserDropped => "user_dropped",
Self::Unknown => "unknown",
}
}
}
impl RescanReason {
pub fn from_event_info(info: Option<&str>) -> Self {
match info {
Some("rescan: buffer overflow") => Self::BufferOverflow,
Some("rescan: kernel dropped") => Self::KernelDropped,
Some("rescan: user dropped") => Self::UserDropped,
_ => Self::Unknown,
}
}
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
use super::*;
#[cfg(test)]
use filetime::set_file_mtime;
#[cfg(test)]
use filetime::FileTime;
use tempfile::TempDir;
#[test]
fn watchdog_append_bypasses_held_logger_control_and_follows_rotation() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("watchdog.log");
let control = super::FILE_CONTROL.lock().unwrap();
super::write_watchdog_line(
&path,
"stall watchdog: stall detected marker=subc_frame_loop",
)
.unwrap();
let rotated = dir.path().join("watchdog.log.1");
std::fs::rename(&path, &rotated).unwrap();
super::write_watchdog_line(&path, "stall watchdog: exit deferred because paging").unwrap();
super::write_watchdog_line(
&path,
"stall watchdog: exiting Authorization: Bearer terminal-secret-value",
)
.unwrap();
drop(control);
let old = std::fs::read_to_string(rotated).unwrap();
let current = std::fs::read_to_string(path).unwrap();
assert!(old.contains("stall detected"));
assert!(!old.contains("exit deferred"));
assert_eq!(current.lines().count(), 2);
assert!(current.contains("exit deferred because paging"));
assert!(current.contains("stall watchdog: exiting"));
assert!(!current.contains("terminal-secret-value"));
assert!(current.contains(crate::log_redact::SECRET_PLACEHOLDER));
}
#[test]
fn gh_shim_preinit_warning_is_durable_and_file_only() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("logs").join("aft-shim.log");
super::write_preinit_warning_to(&path, "gh speech snapshot invalid: first").unwrap();
super::write_preinit_warning_to(&path, "gh speech snapshot invalid: second").unwrap();
let text = std::fs::read_to_string(path).unwrap();
let lines: Vec<_> = text.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[0].ends_with(" [aft] WARN gh speech snapshot invalid: first"));
assert!(lines[1].ends_with(" [aft] WARN gh speech snapshot invalid: second"));
}
#[test]
fn terminal_sync_redacts_both_sinks() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminal.log");
let sink = super::RotatingFile::unopened(path.clone(), 1024, 1, 1);
let mut stderr = Vec::new();
super::write_terminal_line(
&sink,
&mut stderr,
"Authorization: Bearer terminal-secret-value",
)
.unwrap();
let file = std::fs::read(&path).unwrap();
assert_eq!(file, stderr);
let line = String::from_utf8(file).unwrap();
assert!(!line.contains("terminal-secret-value"), "{line}");
assert!(
line.contains(crate::log_redact::SECRET_PLACEHOLDER),
"{line}"
);
}
fn isolated_subc_stderr(test_name: &str, body: impl FnOnce()) {
let test_name = test_name.split_once("::").unwrap().1;
const PROBE: &str = "AFT_TEST_LOGGING_STDERR_CHILD";
if std::env::var(PROBE).ok().as_deref() == Some(test_name) {
super::init_subc();
body();
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", test_name, "--nocapture", "--color=never"])
.env(PROBE, test_name)
.env("RUST_LOG", "off")
.output()
.unwrap();
assert!(
output.status.success()
&& String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed"),
"stderr child failed: stdout={:?} stderr={:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
fn hold_stderr() -> (mpsc::Sender<()>, thread::JoinHandle<()>) {
let (held_tx, held_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let holder = thread::spawn(move || {
let stderr = io::stderr();
let _held = stderr.lock();
held_tx.send(()).unwrap();
let _ = release_rx.recv_timeout(Duration::from_secs(5));
});
held_rx.recv_timeout(Duration::from_secs(5)).unwrap();
(release_tx, holder)
}
#[test]
fn subc_file_writer_warning_does_not_wait_for_stderr() {
isolated_subc_stderr(
concat!(
module_path!(),
"::subc_file_writer_warning_does_not_wait_for_stderr"
),
|| {
struct ReconfigureFault(Arc<Mutex<Vec<u8>>>);
impl FileLogSink for ReconfigureFault {
fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
for line in lines {
self.0.lock().unwrap().extend_from_slice(line);
}
Ok(())
}
fn reopen(&mut self) -> io::Result<()> {
Ok(())
}
fn discard_buffer(&mut self) {}
fn reconfigure(&mut self, _: &Path) -> io::Result<SweepSummary> {
Err(io::Error::other("injected reconfigure failure"))
}
}
let output = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::new(Mutex::new(Some(ReconfigureFault(Arc::clone(&output)))));
let (tx, rx) = mpsc::sync_channel(4);
let (release, holder) = hold_stderr();
let worker = thread::spawn(move || {
run_file_writer(
sink,
rx,
Arc::new(LogWriteHealth::default()),
Duration::ZERO,
)
});
tx.send(LogMessage::Reconfigure(PathBuf::from("injected-log-root")))
.unwrap();
tx.send(LogMessage::Write(b"after warning\n".to_vec()))
.unwrap();
let (done, completed) = mpsc::sync_channel(1);
tx.send(LogMessage::Flush(done)).unwrap();
let progressed = completed.recv_timeout(Duration::from_secs(1));
let _ = release.send(());
holder.join().unwrap();
drop(tx);
worker.join().unwrap();
assert_eq!(
progressed.ok(),
Some(true),
"file writer warning waited on stderr"
);
assert_eq!(&*output.lock().unwrap(), b"after warning\n");
},
);
}
#[test]
fn subc_terminal_mirror_does_not_wait_for_stderr() {
isolated_subc_stderr(
concat!(
module_path!(),
"::subc_terminal_mirror_does_not_wait_for_stderr"
),
|| {
let directory = tempfile::tempdir().unwrap();
let tx = FILE_CONTROL.lock().unwrap().tx.clone().unwrap();
tx.send(LogMessage::Reconfigure(directory.path().to_path_buf()))
.unwrap();
assert!(writer_barrier(&tx));
let (release, holder) = hold_stderr();
let (done, completed) = mpsc::channel();
let caller = thread::spawn(move || {
let _ = done.send(write_terminal_log_sync("held-terminal-stderr-probe"));
});
let result = completed.recv_timeout(Duration::from_secs(30));
let _ = release.send(());
holder.join().unwrap();
caller.join().unwrap();
assert!(
matches!(result, Ok(Ok(()))),
"terminal stderr blocked persistence: {result:?}"
);
let file = directory
.path()
.join("logs")
.join(format!("aft-{}.log", std::process::id()));
assert!(fs::read_to_string(file)
.unwrap()
.contains("held-terminal-stderr-probe"));
},
);
}
#[test]
fn tee_and_process_diagnostics_cannot_bypass_transport_stderr_policy() {
let source = include_str!("logging.rs");
let tee = source
.split_once("impl Write for TeeWriter {")
.unwrap()
.1
.split_once("fn enqueue_file_line(")
.unwrap()
.0;
assert!(tee.contains("self.stderr.write_all"));
assert!(tee.contains("self.stderr.flush"));
assert!(!tee.contains("io::stderr"));
let diagnostics = source
.split_once("fn write_stderr_once(")
.unwrap()
.1
.split_once("pub fn flush_durable_log(")
.unwrap()
.0;
assert!(diagnostics.contains("StderrOutput::for_process()"));
assert!(!diagnostics.contains("io::stderr"));
let terminal = source
.split_once("pub fn write_terminal_log_sync(")
.unwrap()
.1
.split_once("fn write_terminal_line(")
.unwrap()
.0;
assert!(terminal.contains("StderrOutput::for_process()"));
assert!(!terminal.contains("io::stderr"));
}
#[test]
fn blocked_stderr_does_not_stop_redacted_file_logging_or_health() {
struct Gate {
entered: Option<mpsc::Sender<()>>,
release: mpsc::Receiver<()>,
bytes: Arc<Mutex<Vec<u8>>>,
}
impl Write for Gate {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if let Some(entered) = self.entered.take() {
entered.send(()).unwrap();
let _ = self.release.recv_timeout(Duration::from_secs(5));
}
self.bytes.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("mirror-independent.log");
let sink = RotatingFile::open(path.clone(), 1024 * 1024, 1, 1).unwrap();
let (file_tx, file_rx) = mpsc::sync_channel(8);
let file_worker = thread::spawn(move || {
run_file_writer(
Arc::new(Mutex::new(Some(sink))),
file_rx,
Arc::new(LogWriteHealth::default()),
Duration::ZERO,
)
});
let health = Arc::new(stderr_mirror::MirrorHealth::default());
let bytes = Arc::new(Mutex::new(Vec::new()));
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let (mirror, stderr_worker) = stderr_mirror::Mirror::spawn(
Gate {
entered: Some(entered_tx),
release: release_rx,
bytes: Arc::clone(&bytes),
},
1,
Arc::clone(&health),
)
.unwrap();
let mut tee = TeeWriter {
file_tx: Some(file_tx.clone()),
stderr: StderrOutput::Subc(mirror),
};
tee.write_all(b"Authorization: Bearer mirror-secret-value\n")
.unwrap();
entered_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let start = Instant::now();
tee.write_all(b"Authorization: Bearer second-secret-value\n")
.unwrap();
tee.write_all(b"third\n").unwrap();
tee.flush().unwrap();
let snapshot = health.snapshot();
let elapsed = start.elapsed();
let file_progressed = writer_barrier(&file_tx);
let file = fs::read(&path).unwrap();
let _ = release_tx.send(());
drop(tee);
drop(file_tx);
stderr_worker.join().unwrap();
file_worker.join().unwrap();
assert!(elapsed < Duration::from_secs(1));
assert!(file_progressed, "file writer waited on stderr");
assert_eq!(snapshot["dropped_lines_total"], 1);
assert_eq!(snapshot["dropped_flushes_total"], 1);
let file = String::from_utf8(file).unwrap();
let mirrored = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
for output in [&file, &mirrored] {
assert!(!output.contains("mirror-secret-value"), "{output}");
assert!(!output.contains("second-secret-value"), "{output}");
assert!(
output.contains(crate::log_redact::SECRET_PLACEHOLDER),
"{output}"
);
}
assert!(file.ends_with("third\n"));
assert!(!mirrored.contains("third"));
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum SinkFault {
None,
Write,
Flush,
Open,
}
struct SinkProbe {
fault: SinkFault,
output: Vec<u8>,
opens: usize,
writes: usize,
flushes: usize,
}
struct FaultWriter {
probe: Arc<Mutex<SinkProbe>>,
pending: Vec<u8>,
}
impl Write for FaultWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
let mut probe = self.probe.lock().unwrap();
probe.writes += 1;
if probe.fault == SinkFault::Write {
return Err(io::Error::other("No space left on device (injected write)"));
}
self.pending.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
let mut probe = self.probe.lock().unwrap();
probe.flushes += 1;
if probe.fault == SinkFault::Flush {
return Err(io::Error::other("No space left on device (injected flush)"));
}
probe.output.append(&mut self.pending);
Ok(())
}
}
struct FaultSink {
probe: Arc<Mutex<SinkProbe>>,
writer: Option<BufWriter<FaultWriter>>,
write_gate: Option<(SyncSender<()>, mpsc::Receiver<()>)>,
}
impl FaultSink {
fn new(fault: SinkFault) -> Self {
let probe = Arc::new(Mutex::new(SinkProbe {
fault,
output: Vec::new(),
opens: 0,
writes: 0,
flushes: 0,
}));
Self {
writer: Some(BufWriter::new(FaultWriter {
probe: Arc::clone(&probe),
pending: Vec::new(),
})),
probe,
write_gate: None,
}
}
}
impl FileLogSink for FaultSink {
fn write_batch(&mut self, lines: &[Vec<u8>]) -> io::Result<()> {
if let Some((entered, proceed)) = self.write_gate.take() {
entered.send(()).unwrap();
proceed.recv().unwrap();
}
let writer = self.writer.as_mut().expect("sink must reopen before retry");
for line in lines {
writer.write_all(line)?;
}
writer.flush()
}
fn reopen(&mut self) -> io::Result<()> {
self.discard_buffer();
let mut probe = self.probe.lock().unwrap();
probe.opens += 1;
if probe.fault == SinkFault::Open {
return Err(io::Error::other("bad handle (injected reopen)"));
}
self.writer = Some(BufWriter::new(FaultWriter {
probe: Arc::clone(&self.probe),
pending: Vec::new(),
}));
Ok(())
}
fn discard_buffer(&mut self) {
if let Some(writer) = self.writer.take() {
let _ = writer.into_parts();
}
}
fn reconfigure(&mut self, _root: &Path) -> io::Result<SweepSummary> {
unreachable!("this test never reconfigures storage")
}
}
fn writer_barrier(tx: &SyncSender<LogMessage>) -> bool {
let (done, reply) = mpsc::sync_channel(1);
tx.send(LogMessage::Flush(done))
.expect("writer still running");
reply
.recv_timeout(Duration::from_secs(5))
.expect("writer must survive a failed log write and answer flush requests")
}
#[test]
fn file_writer_recovers_after_write_and_flush_errors() {
for fault in [SinkFault::Write, SinkFault::Flush] {
let sink = FaultSink::new(fault);
let probe = Arc::clone(&sink.probe);
let shared = Arc::new(Mutex::new(Some(sink)));
let health = Arc::new(LogWriteHealth::default());
let (tx, rx) = mpsc::sync_channel(8);
let worker_health = Arc::clone(&health);
let worker = thread::spawn(move || {
run_file_writer(shared, rx, worker_health, Duration::ZERO);
});
tx.send(LogMessage::Write(b"lost one\nlost two\n".to_vec()))
.unwrap();
assert!(
!writer_barrier(&tx),
"failed writes cannot confirm durability"
);
let failed = health.snapshot();
assert_eq!(failed["dropped_lines_total"], 2);
assert!(failed["last_write_error"]
.as_str()
.unwrap()
.contains("No space left on device"));
let since = failed["failing_since"].as_str().unwrap();
probe.lock().unwrap().fault = SinkFault::Open;
tx.send(LogMessage::Write(b"lost three\n".to_vec()))
.unwrap();
assert!(!writer_barrier(&tx));
assert_eq!(health.snapshot()["dropped_lines_total"], 3);
assert_eq!(health.snapshot()["failing_since"], since);
probe.lock().unwrap().fault = SinkFault::None;
tx.send(LogMessage::Write(b"recovered\n".to_vec())).unwrap();
assert!(writer_barrier(&tx));
tx.send(LogMessage::Write(b"still logging\n".to_vec()))
.unwrap();
assert!(writer_barrier(&tx));
drop(tx);
worker.join().unwrap();
let probe = probe.lock().unwrap();
let output = String::from_utf8(probe.output.clone()).unwrap();
let lines: Vec<_> = output.lines().collect();
assert_eq!(lines.len(), 3, "no replay of lost buffers: {output}");
assert!(
lines[0].contains(&format!("log writes failed from {since} to ")),
"{output}"
);
assert!(lines[0].contains("3 lines dropped"), "{output}");
assert!(
lines[0].contains("bad handle (injected reopen)"),
"{output}"
);
assert_eq!(lines[1], "recovered");
assert_eq!(lines[2], "still logging");
assert_eq!(probe.opens, 2);
let recovered = health.snapshot();
assert_eq!(recovered["dropped_lines_total"], 3);
assert!(recovered["failing_since"].is_null());
assert_eq!(
recovered["last_write_error"],
"bad handle (injected reopen)"
);
}
}
#[test]
fn log_write_retries_back_off_without_sleeping_or_replaying_lost_lines() {
let mut sink = FaultSink::new(SinkFault::Write);
let health = Arc::new(LogWriteHealth::default());
let mut recovery = LogWriteRecovery::new(Arc::clone(&health), LOG_WRITE_RETRY_MIN);
let now = Instant::now();
assert!(!recovery.write_batch(&mut sink, &line("lost one"), now));
let writes = sink.probe.lock().unwrap().writes;
assert!(!recovery.write_batch(
&mut sink,
&line("lost two"),
now + Duration::from_millis(999)
));
assert_eq!(sink.probe.lock().unwrap().writes, writes);
assert_eq!(sink.probe.lock().unwrap().opens, 0);
sink.probe.lock().unwrap().fault = SinkFault::Open;
assert!(!recovery.write_batch(
&mut sink,
&line("lost three"),
now + Duration::from_secs(1)
));
assert_eq!(sink.probe.lock().unwrap().opens, 1);
assert!(!recovery.write_batch(
&mut sink,
&line("lost four"),
now + Duration::from_millis(2999)
));
assert_eq!(
sink.probe.lock().unwrap().opens,
1,
"reopen failures also back off"
);
sink.probe.lock().unwrap().fault = SinkFault::None;
assert!(recovery.write_batch(&mut sink, &line("recovered"), now + Duration::from_secs(3)));
let output = String::from_utf8(sink.probe.lock().unwrap().output.clone()).unwrap();
assert!(
output.lines().next().unwrap().contains("4 lines dropped"),
"{output}"
);
assert!(output.ends_with("\nrecovered\n"), "{output}");
assert_eq!(health.snapshot()["dropped_lines_total"], 4);
assert_eq!(recovery.retry_delay, LOG_WRITE_RETRY_MIN);
sink.probe.lock().unwrap().fault = SinkFault::Write;
let mut next = now + Duration::from_secs(4);
for _ in 0..10 {
assert!(!recovery.write_batch(&mut sink, &line("lost again"), next));
next = recovery.outage.as_ref().unwrap().retry_at;
}
assert_eq!(recovery.retry_delay, LOG_WRITE_RETRY_MAX);
assert_eq!(
next.duration_since(now + Duration::from_secs(4)),
Duration::from_secs(181)
);
}
#[test]
fn log_callers_and_health_do_not_wait_for_a_stalled_sink_or_full_queue() {
let mut sink = FaultSink::new(SinkFault::Write);
let (entered, entering) = mpsc::sync_channel(1);
let (proceed, proceeding) = mpsc::sync_channel(1);
sink.write_gate = Some((entered, proceeding));
let shared = Arc::new(Mutex::new(Some(sink)));
let health = Arc::new(LogWriteHealth::default());
let (tx, rx) = mpsc::sync_channel(1);
let worker_health = Arc::clone(&health);
let worker =
thread::spawn(move || run_file_writer(shared, rx, worker_health, Duration::ZERO));
tx.send(LogMessage::Write(b"in flight\n".to_vec())).unwrap();
entering
.recv_timeout(Duration::from_secs(5))
.expect("worker entered sink I/O");
let caller_health = Arc::clone(&health);
let caller_tx = tx.clone();
let (finished, finishing) = mpsc::sync_channel(1);
let caller = thread::spawn(move || {
let mut tx = Some(caller_tx);
enqueue_file_line(&mut tx, b"queued\n", &caller_health);
enqueue_file_line(&mut tx, b"queue full one\n", &caller_health);
enqueue_file_line(&mut tx, b"queue full two\n", &caller_health);
finished.send(caller_health.snapshot()).unwrap();
});
let while_stalled = finishing
.recv_timeout(Duration::from_secs(5))
.expect("log caller and health must finish while sink I/O is still stalled");
assert_eq!(while_stalled["dropped_lines_total"], 2);
proceed.send(()).unwrap();
caller.join().unwrap();
assert!(!writer_barrier(&tx));
drop(tx);
worker.join().unwrap();
assert_eq!(health.snapshot()["dropped_lines_total"], 4);
}
#[test]
#[cfg(unix)]
fn file_log_reopens_after_rotation_loses_its_handle() {
let temp = TempDir::new().unwrap();
let logs = temp.path().join("logs");
create_private_log_dir(&logs).unwrap();
let path = logs.join("aft-777.log");
let mut sink = RotatingFile::open(path.clone(), 100, 1, 1).unwrap();
sink.write_batch(&line("before outage")).unwrap();
let health = Arc::new(LogWriteHealth::default());
let mut recovery = LogWriteRecovery::new(Arc::clone(&health), Duration::ZERO);
let moved = temp.path().join("moved-logs");
fs::rename(&logs, &moved).unwrap();
fs::write(&logs, b"not a directory").unwrap();
assert!(!recovery.write_batch(&mut sink, &line(&"x".repeat(101)), Instant::now()));
assert!(sink.writer.is_none());
fs::remove_file(&logs).unwrap();
fs::rename(&moved, &logs).unwrap();
sink.threshold = LOG_FILE_BYTES;
assert!(recovery.write_batch(&mut sink, &line("after outage"), Instant::now()));
let output = fs::read_to_string(path).unwrap();
let lines: Vec<_> = output.lines().collect();
assert_eq!(lines.len(), 3, "{output}");
assert_eq!(lines[0], "before outage");
assert!(lines[1].contains("1 lines dropped"), "{output}");
assert_eq!(lines[2], "after outage");
assert_eq!(health.snapshot()["dropped_lines_total"], 1);
}
#[test]
fn file_log_recovers_when_initial_open_failed() {
let temp = TempDir::new().unwrap();
let logs = temp.path().join("logs");
fs::write(&logs, b"not a directory").unwrap();
let path = logs.join("aft-777.log");
let health = Arc::new(LogWriteHealth::default());
let (mut sink, summary) = initial_file_sink(&logs, &path, Arc::clone(&health));
assert!(summary.is_none());
assert!(sink.writer.is_none());
assert!(health.snapshot()["last_write_error"].is_string());
let mut recovery = LogWriteRecovery::new(Arc::clone(&health), Duration::ZERO);
assert!(!recovery.write_batch(&mut sink, &line("lost startup line"), Instant::now()));
fs::remove_file(&logs).unwrap();
assert!(recovery.write_batch(&mut sink, &line("startup recovered"), Instant::now()));
let output = fs::read_to_string(path).unwrap();
assert!(
output.lines().next().unwrap().contains("1 lines dropped"),
"{output}"
);
assert!(output.ends_with("\nstartup recovered\n"), "{output}");
assert!(health.snapshot()["failing_since"].is_null());
}
#[test]
fn panic_hook_child_probe() {
if std::env::var_os("AFT_TEST_PANIC_LOG_CHILD").is_none() {
return;
}
let path = crate::storage_path::storage_dir(None)
.join("logs")
.join(format!("aft-{}.log", std::process::id()));
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let persisted =
fs::read_to_string(&path).is_ok_and(|text| text.contains("forced backtrace:"));
eprintln!("panic diagnostic persisted before previous hook: {persisted}");
previous(info);
}));
init();
let backtrace_env = std::env::var_os("RUST_BACKTRACE");
let panic = std::panic::catch_unwind(|| panic!("durable panic diagnostic probe"));
assert!(panic.is_err());
assert_eq!(std::env::var_os("RUST_BACKTRACE"), backtrace_env);
std::process::exit(0);
}
#[test]
fn panic_hook_preserves_default_backtrace_behavior_and_persists() {
for backtrace in [None, Some("0"), Some("1"), Some("full")] {
let storage = TempDir::new().unwrap();
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
child
.args([
"--exact",
"logging::tests::panic_hook_child_probe",
"--nocapture",
])
.env("AFT_TEST_PANIC_LOG_CHILD", "1")
.env("AFT_STORAGE_DIR", storage.path())
.env("RUST_LOG", "off")
.env_remove("RUST_BACKTRACE");
if let Some(value) = backtrace {
child.env("RUST_BACKTRACE", value);
}
let output = child.output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "child failed: {stderr}");
let paths = fs::read_dir(storage.path().join("logs")).unwrap();
let log = paths
.map(|entry| fs::read_to_string(entry.unwrap().path()).unwrap())
.collect::<String>();
assert!(log.contains("durable panic diagnostic probe"), "{log}");
assert!(log.contains("forced backtrace:"), "{log}");
assert!(log.contains("panic_hook_child_probe"), "{log}");
assert!(stderr.contains("panic diagnostic persisted before previous hook: true"));
assert!(stderr.contains("durable panic diagnostic probe"));
assert_eq!(
stderr.contains("stack backtrace:"),
matches!(backtrace, Some("1" | "full")),
"RUST_BACKTRACE={backtrace:?}: {stderr}"
);
if backtrace == Some("full") {
assert!(
stderr.contains("0x"),
"default full backtrace was lost: {stderr}"
);
}
}
}
#[test]
fn panic_diagnostic_text_is_bounded_at_utf8_boundaries() {
let enormous = "é🚀".repeat(PANIC_BACKTRACE_BYTES);
for budget in [PANIC_MESSAGE_BYTES, PANIC_BACKTRACE_BYTES] {
let text = bounded_panic_text(format_args!("{enormous}"), budget);
assert!(text.len() <= budget);
assert!(text.ends_with(PANIC_TRUNCATION));
assert!(text.starts_with("é🚀"));
}
assert_eq!(
bounded_panic_text(format_args!("small"), PANIC_MESSAGE_BYTES),
"small"
);
}
pub fn line(value: &str) -> Vec<Vec<u8>> {
vec![format!("{value}\n").into_bytes()]
}
fn render_log_line(level: log::Level, target: &str, message: &str) -> String {
let mut out = Vec::new();
write_log_line(
&mut out,
"2026-09-26T10:00:00Z",
level,
target,
&format_args!("{message}"),
)
.unwrap();
String::from_utf8(out).unwrap()
}
#[test]
fn log_lines_carry_their_level_after_the_tag() {
assert_eq!(
render_log_line(log::Level::Warn, "aft::subc", "slow tool_call name=read"),
"2026-09-26T10:00:00Z [aft] WARN slow tool_call name=read\n"
);
assert_eq!(
render_log_line(log::Level::Error, "aft::lsp::client", "server crashed"),
"2026-09-26T10:00:00Z [aft-lsp] ERROR server crashed\n"
);
assert_eq!(
render_log_line(log::Level::Info, "aft", "started"),
"2026-09-26T10:00:00Z [aft] INFO started\n"
);
assert_eq!(
render_log_line(log::Level::Debug, "aft_lsp", "x"),
"2026-09-26T10:00:00Z [aft-lsp] DEBUG x\n"
);
}
#[test]
fn split_session_log_targets_preserve_legacy_filters() {
let filter = env_logger::Builder::new()
.parse_filters("info,aft::db=debug")
.build();
for (target, canonical) in [
("aft_base::cache_location", "aft::cache_location"),
("aft_db::db::write_ledger", "aft::db::write_ledger"),
("aft_parse::parser", "aft::parser"),
("aft::subc", "aft::subc"),
("aft_db_probe::db", "aft_db_probe::db"),
] {
assert_eq!(canonical_slog_target(target), canonical);
}
let matches = |target| {
log::Log::enabled(
&filter,
&log::Metadata::builder()
.target(target)
.level(log::Level::Debug)
.build(),
)
};
assert!(!matches("aft_db::db::write_ledger"));
assert!(matches(
canonical_slog_target("aft_db::db::write_ledger").as_ref()
));
}
fn slow_phases() -> ToolCallPhaseDurations {
ToolCallPhaseDurations {
cpu: crate::tool_progress::ToolCallPhaseCpu::default(),
queue: Duration::ZERO,
setup: Duration::ZERO,
translate: Duration::ZERO,
execute: Duration::from_millis(120),
format: Duration::ZERO,
finalize: Duration::ZERO,
egress_enqueue: Duration::ZERO,
egress_queue: Duration::ZERO,
egress_prepare: Duration::ZERO,
egress_write: Duration::ZERO,
egress: Duration::ZERO,
frame_bytes: 10,
writer_queue_depth: 0,
writer_active_at_enqueue: false,
writer_queue_was_full: false,
writer_reserve_timeouts: 0,
total: SLOW_TOOL_CALL_THRESHOLD + Duration::from_millis(70),
waiting_on: WaitingOn::None,
waiting_on_build_id: None,
wait_ms: 0,
intentional_wait: false,
arg_shape: None,
edit_phases: None,
}
}
fn slow_call_levels(name: &str, caller: ToolCallCaller) -> Vec<log::Level> {
SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow_mut().clear());
note_tool_call_trace(
name,
"test-session",
Path::new("/repo"),
7,
1,
slow_phases(),
caller,
);
SLOW_TOOL_CALL_CAPTURE.with(|captured| {
captured
.borrow_mut()
.drain(..)
.inspect(|(_, message)| {
assert!(message.starts_with(&format!("slow tool_call name={name} ")))
})
.map(|(level, _)| level)
.collect()
})
}
#[test]
fn slow_phase_time_renders_wall_and_cpu_in_one_field() {
assert_eq!(
slow_phase_time(
Duration::from_micros(39_123),
Some(Duration::from_micros(4))
),
"39.123ms/cpu=0.004ms"
);
assert_eq!(
slow_phase_time(Duration::from_millis(50), None),
"50.000ms/cpu=?"
);
}
#[test]
fn slow_plumbing_call_logs_at_debug_while_slow_agent_call_warns() {
assert_eq!(
slow_call_levels("bash_drain_completions", ToolCallCaller::Plumbing),
vec![log::Level::Debug]
);
assert_eq!(
slow_call_levels("bash_status", ToolCallCaller::Plumbing),
vec![log::Level::Debug]
);
assert_eq!(
slow_call_levels("bash_status", ToolCallCaller::Agent),
vec![log::Level::Warn]
);
assert_eq!(
slow_call_levels("read", ToolCallCaller::Agent),
vec![log::Level::Warn]
);
}
#[test]
fn slow_intentional_wait_excludes_execution_but_warns_for_overhead() {
let mut phases = slow_phases();
phases.intentional_wait = true;
phases.execute = Duration::from_secs(120);
phases.total = phases.execute + SLOW_TOOL_CALL_THRESHOLD;
let _ = take_slow_tool_call_logs_for_test();
note_tool_call_trace(
"bash_watch",
"waiting-session",
Path::new("/repo"),
7,
1,
phases.clone(),
ToolCallCaller::Agent,
);
assert!(take_slow_tool_call_logs_for_test().is_empty());
phases.queue = SLOW_TOOL_CALL_THRESHOLD + Duration::from_millis(1);
phases.total = phases.execute + phases.queue;
note_tool_call_trace(
"bash_watch",
"waiting-session",
Path::new("/repo"),
7,
2,
phases.clone(),
ToolCallCaller::Agent,
);
let lines = SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.take());
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].0, log::Level::Warn);
phases.intentional_wait = false;
phases.queue = Duration::ZERO;
phases.total = phases.execute;
note_tool_call_trace(
"bash",
"waiting-session",
Path::new("/repo"),
7,
3,
phases,
ToolCallCaller::Agent,
);
let lines = SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.take());
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].0, log::Level::Warn);
}
#[test]
fn fast_call_logs_no_slow_line() {
let mut phases = slow_phases();
phases.total = SLOW_TOOL_CALL_THRESHOLD;
SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow_mut().clear());
note_tool_call_trace(
"read",
"test-session",
Path::new("/repo"),
7,
1,
phases,
ToolCallCaller::Agent,
);
assert!(SLOW_TOOL_CALL_CAPTURE.with(|captured| captured.borrow().is_empty()));
}
#[test]
fn subc_tool_catalog_fast_answer_does_not_emit_slow_call_line() {
let mut phases = slow_phases();
phases.total = SLOW_TOOL_CALL_THRESHOLD;
let _ = take_slow_tool_call_logs_for_test();
note_tool_call_trace(
"tool.catalog",
"catalog-fast",
Path::new("/repo"),
7,
1,
phases,
ToolCallCaller::Agent,
);
assert!(take_slow_tool_call_logs_for_test().is_empty());
}
#[test]
fn epoch_timestamp_renders_known_dates() {
assert_eq!(format_epoch_secs(0), "1970-01-01T00:00:00Z");
assert_eq!(format_epoch_secs(1_704_067_200), "2024-01-01T00:00:00Z");
assert_eq!(format_epoch_secs(1_709_251_199), "2024-02-29T23:59:59Z");
assert_eq!(format_epoch_secs(4_102_444_800), "2100-01-01T00:00:00Z");
assert_eq!(format_epoch_secs(4_107_542_399), "2100-02-28T23:59:59Z");
}
#[test]
fn token_written_through_the_sink_is_masked_on_disk() {
let temp = TempDir::new().unwrap();
let path = temp.path().join("aft-777.log");
let sink = RotatingFile::open(path.clone(), LOG_FILE_BYTES, 1, 1).unwrap();
let (tx, rx) = mpsc::sync_channel(8);
let sink = Arc::new(Mutex::new(Some(sink)));
let writer = thread::spawn(move || {
run_file_writer(
sink,
rx,
Arc::new(LogWriteHealth::default()),
LOG_WRITE_RETRY_MIN,
)
});
let mut tee = TeeWriter::new(Some(tx));
let token = "ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8";
tee.write_all(
format!("[aft] fetch https://bob:pw123@host.example/x?access_token=zz9 {token}\n")
.as_bytes(),
)
.unwrap();
drop(tee);
writer.join().unwrap();
let on_disk = fs::read_to_string(&path).unwrap();
assert_eq!(
on_disk,
"[aft] fetch https://***@host.example/x?access_token=<REDACTED_SECRET> <REDACTED_SECRET>\n"
);
assert!(!on_disk.contains(token));
assert!(!on_disk.contains("pw123"));
}
#[cfg(unix)]
fn mode_of(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[cfg(unix)]
#[test]
fn fresh_log_dir_and_file_are_owner_only() {
let temp = TempDir::new().unwrap();
let logs_dir = temp.path().join("storage").join("logs");
let path = logs_dir.join("aft-4242.log");
let (mut sink, _) = prepare_file_sink(&logs_dir, &path).unwrap();
sink.write_batch(&line("hello")).unwrap();
assert_eq!(mode_of(&logs_dir), 0o700);
assert_eq!(mode_of(&path), 0o600);
sink.rotate().unwrap();
assert_eq!(mode_of(&path), 0o600);
assert_eq!(mode_of(&rotated_path(&path, 1)), 0o600);
}
#[cfg(unix)]
#[test]
fn existing_world_readable_log_dir_and_files_are_tightened() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().unwrap();
let logs_dir = temp.path().join("logs");
fs::create_dir(&logs_dir).unwrap();
fs::set_permissions(&logs_dir, fs::Permissions::from_mode(0o755)).unwrap();
let path = logs_dir.join("aft-4242.log");
for file in [path.clone(), rotated_path(&path, 1)] {
fs::write(&file, "old\n").unwrap();
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
}
let _ = prepare_file_sink(&logs_dir, &path).unwrap();
assert_eq!(mode_of(&logs_dir), 0o700);
assert_eq!(mode_of(&path), 0o600);
assert_eq!(mode_of(&rotated_path(&path, 1)), 0o600);
assert_eq!(fs::read_to_string(&path).unwrap(), "old\n");
}
#[test]
fn rotation_rolls_once_and_replaces_the_single_backup_generation() {
let temp = TempDir::new().unwrap();
let path = temp.path().join("aft-123.log");
fs::write(rotated_path(&path, 1), "stale backup\n").unwrap();
let mut sink = RotatingFile::open(path.clone(), 10, 1, 1).unwrap();
sink.write_batch(&line("aaaa")).unwrap();
sink.write_batch(&line("bbbb")).unwrap();
sink.write_batch(&line("cccc")).unwrap();
sink.write_batch(&line("dddd")).unwrap();
sink.write_batch(&line("eeee")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "eeee\n");
assert_eq!(
fs::read_to_string(rotated_path(&path, 1)).unwrap(),
"cccc\ndddd\n"
);
assert!(!rotated_path(&path, 2).exists());
}
#[test]
fn dead_pid_sweep_respects_age_liveness_and_explicit_plugin_exclusion() {
let temp = TempDir::new().unwrap();
let dead = temp.path().join("aft-4294967294.log");
let dead_rotated = temp.path().join("aft-4294967294.log.1");
let fresh_dead = temp.path().join("aft-4294967293.log");
let own = temp.path().join(format!("aft-{}.log", std::process::id()));
let live_rotated = rotated_path(&own, 1);
let plugin = temp.path().join("aft-plugin.log");
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
for path in [&dead, &dead_rotated, &own, &live_rotated, &plugin] {
fs::write(path, "log").unwrap();
set_file_mtime(path, FileTime::from_unix_time(1, 0)).unwrap();
}
fs::write(&fresh_dead, "fresh").unwrap();
set_file_mtime(
&fresh_dead,
FileTime::from_unix_time(
(now - DEAD_PROCESS_LOG_MAX_AGE + Duration::from_secs(1))
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
0,
),
)
.unwrap();
let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, u64::MAX).unwrap();
assert_eq!(summary.removed_files, 2);
assert!(!dead.exists());
assert!(!dead_rotated.exists());
assert!(fresh_dead.exists());
assert!(own.exists());
assert!(live_rotated.exists());
assert!(plugin.exists());
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn recycled_pid_log_is_reaped_while_the_live_owner_is_kept() {
let temp = TempDir::new().unwrap();
let live_pid = unsafe { libc::getppid() } as u32;
assert!(is_process_alive(live_pid));
let recycled = temp.path().join(format!("aft-{live_pid}.log"));
fs::write(&recycled, "written long before this process existed").unwrap();
set_file_mtime(&recycled, FileTime::from_unix_time(1, 0)).unwrap();
let summary = sweep_logs(
temp.path(),
SystemTime::now(),
DEAD_PROCESS_LOG_MAX_AGE,
u64::MAX,
)
.unwrap();
assert_eq!(summary.removed_files, 1);
assert_eq!(summary.recycled_pids, 1);
assert!(!recycled.exists());
let owned = temp.path().join(format!("aft-{live_pid}.log"));
fs::write(&owned, "written by the live owner").unwrap();
let summary = sweep_logs(
temp.path(),
SystemTime::now() + DEAD_PROCESS_LOG_MAX_AGE * 2,
DEAD_PROCESS_LOG_MAX_AGE,
0,
)
.unwrap();
assert_eq!(summary.removed_files, 0);
assert!(owned.exists());
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn recycled_pid_now_owned_by_another_user_is_reaped() {
let temp = TempDir::new().unwrap();
assert!(is_process_alive(1));
assert!(
crate::process_identity::process_start_time_ms(1).is_some(),
"pid 1's start time must be readable from an unprivileged process"
);
let recycled = temp.path().join("aft-1.log");
fs::write(&recycled, "written before the current pid 1 booted").unwrap();
set_file_mtime(&recycled, FileTime::from_unix_time(1, 0)).unwrap();
let summary = sweep_logs(
temp.path(),
SystemTime::now(),
DEAD_PROCESS_LOG_MAX_AGE,
u64::MAX,
)
.unwrap();
assert_eq!(summary.removed_files, 1);
assert_eq!(summary.recycled_pids, 1);
assert!(!recycled.exists());
}
#[test]
fn budget_backstop_deletes_oldest_dead_files_but_not_live_files() {
let temp = TempDir::new().unwrap();
let oldest = temp.path().join("aft-4294967294.log");
let newest = temp.path().join("aft-4294967293.log");
let live = temp.path().join(format!("aft-{}.log", std::process::id()));
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
fs::write(&oldest, "oldest").unwrap();
fs::write(&newest, "newest").unwrap();
fs::write(&live, "live-live").unwrap();
set_file_mtime(&oldest, FileTime::from_unix_time(1, 0)).unwrap();
set_file_mtime(&newest, FileTime::from_unix_time(2, 0)).unwrap();
set_file_mtime(&live, FileTime::from_unix_time(1, 0)).unwrap();
let summary = sweep_logs(
temp.path(),
now,
Duration::from_secs(365 * 24 * 60 * 60),
15,
)
.unwrap();
assert_eq!(summary.removed_files, 1);
assert!(!oldest.exists());
assert!(newest.exists());
assert!(live.exists());
}
#[test]
fn budget_backstop_keeps_the_newest_dead_log_inside_its_forensic_window() {
let temp = TempDir::new().unwrap();
let older = temp.path().join("aft-4294967294.log");
let predecessor = temp.path().join("aft-4294967293.log");
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
fs::write(&older, "older-older-older").unwrap();
fs::write(&predecessor, "predecessor-predecessor").unwrap();
set_file_mtime(&older, FileTime::from_unix_time(1, 0)).unwrap();
set_file_mtime(
&predecessor,
FileTime::from_unix_time(10 * 24 * 60 * 60 - 30, 0),
)
.unwrap();
let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, 4).unwrap();
assert!(
!older.exists(),
"the older dead log is still budget-reapable"
);
assert!(predecessor.exists(), "the newest dead log is protected");
assert_eq!(summary.removed_files, 1);
assert_eq!(
summary.over_budget_bytes,
"predecessor-predecessor".len() as u64 - 4,
"the shortfall is reported instead of destroying the record"
);
set_file_mtime(&predecessor, FileTime::from_unix_time(1, 0)).unwrap();
let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, 4).unwrap();
assert!(!predecessor.exists());
assert_eq!(summary.over_budget_bytes, 0);
}
#[test]
fn relic_plugin_rotations_are_reaped_before_process_logs_are_weighed() {
let temp = TempDir::new().unwrap();
let active = temp.path().join("aft-plugin.log");
let backup = temp.path().join("aft-plugin.log.1");
let relic_two = temp.path().join("aft-plugin.log.2");
let relic_five = temp.path().join("aft-plugin.log.5");
let test_relic = temp.path().join("aft-plugin-test.log.3");
let predecessor = temp.path().join("aft-4294967293.log");
let now = SystemTime::UNIX_EPOCH + Duration::from_secs(10 * 24 * 60 * 60);
for (path, content) in [
(&active, "active"),
(&backup, "backup"),
(&relic_two, "relic-two-relic-two"),
(&relic_five, "relic-five-relic-five"),
(&test_relic, "test-relic-test-relic"),
(&predecessor, "predecessor"),
] {
fs::write(path, content).unwrap();
set_file_mtime(path, FileTime::from_unix_time(10 * 24 * 60 * 60 - 30, 0)).unwrap();
}
let budget = ("active".len() + "backup".len() + "predecessor".len()) as u64;
let summary = sweep_logs(temp.path(), now, DEAD_PROCESS_LOG_MAX_AGE, budget).unwrap();
assert!(!relic_two.exists());
assert!(!relic_five.exists());
assert!(!test_relic.exists());
assert!(active.exists(), "the plugin's live file is never touched");
assert!(
backup.exists(),
"the plugin's one owned backup is never touched"
);
assert!(predecessor.exists());
assert_eq!(summary.removed_files, 3);
assert_eq!(summary.over_budget_bytes, 0);
}
#[test]
fn tool_call_summary_uses_bounded_window_median_and_maxima() {
let samples = VecDeque::from([
ToolCallPerfSample {
total_ms: 9,
queue_ms: 5,
},
ToolCallPerfSample {
total_ms: 3,
queue_ms: 1,
},
ToolCallPerfSample {
total_ms: 7,
queue_ms: 2,
},
ToolCallPerfSample {
total_ms: 5,
queue_ms: 4,
},
]);
let summary = summarize_tool_calls(&samples);
assert_eq!(summary.window, 4);
assert_eq!(summary.p50_total_ms, 5);
assert_eq!(summary.max_total_ms, 9);
assert_eq!(summary.p50_queue_ms, 2);
assert_eq!(summary.max_queue_ms, 5);
}
#[test]
fn perf_tick_skips_empty_drains_but_keeps_real_work_and_drain_counts() {
for activity in ["drain", "watcher", "semantic"] {
let perf = PerfMetrics::default();
perf.reporter.lock().unwrap().last_report = Instant::now() - perf_tick_interval();
perf.drain_slices.store(1, Ordering::Relaxed);
if activity == "watcher" {
perf.watcher_ingested.store(2, Ordering::Relaxed);
perf.watcher_paths.store(1, Ordering::Relaxed);
} else if activity == "semantic" {
perf.semantic_collects.store(1, Ordering::Relaxed);
perf.semantic_files.store(2, Ordering::Relaxed);
perf.semantic_chunks.store(3, Ordering::Relaxed);
perf.semantic_ms.store(4, Ordering::Relaxed);
}
let (_, lines) = capture_log_lines(|| report_perf_tick(&perf, None, (0, 0)));
if activity == "drain" {
assert!(lines.is_empty(), "{lines:?}");
} else {
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].starts_with("INFO perf tick:"), "{lines:?}");
assert!(lines[0].contains(" drains=1 "), "{lines:?}");
let expected = if activity == "watcher" {
"watcher={ingested:2,paths:1,dropped:0}"
} else {
"semantic={collects:1,files:2,chunks:3,ms:4}"
};
assert!(lines[0].contains(expected), "{lines:?}");
}
assert_eq!(perf.drain_slices.load(Ordering::Relaxed), 0);
}
}
#[test]
fn tool_call_tick_labels_interval_count_and_rolling_window() {
let samples = VecDeque::from([ToolCallPerfSample {
total_ms: 3_000,
queue_ms: 2_900,
}]);
let summary = summarize_tool_calls(&samples);
assert_eq!(
format_tool_call_summary(1, summary),
"toolcall={new:1,window:1,p50_total_ms:3000,max_total_ms:3000,p50_queue_ms:2900,max_queue_ms:2900}"
);
assert_eq!(
format_tool_call_summary(0, summary),
"toolcall={new:0,window:1,p50_total_ms:3000,max_total_ms:3000,p50_queue_ms:2900,max_queue_ms:2900}"
);
}
fn index_event_matches_grammar(line: &str) -> bool {
let Some(rest) = line.strip_prefix("index_event ") else {
return false;
};
if rest.is_empty() {
return false;
}
rest.split(' ').all(|token| {
let Some((key, value)) = token.split_once('=') else {
return false;
};
!key.is_empty()
&& key.chars().all(|c| c.is_ascii_lowercase() || c == '_')
&& !value.is_empty()
&& !value.contains(' ')
&& !value.contains('=')
})
}
fn index_event_fields(line: &str) -> BTreeMap<String, String> {
let mut fields = BTreeMap::new();
for token in line.split_whitespace().skip(1) {
let Some((key, value)) = token.split_once('=') else {
continue;
};
fields.insert(key.to_string(), value.to_string());
}
fields
}
fn assert_index_event_grammar(lines: &[String]) {
for line in lines {
assert!(
index_event_matches_grammar(line),
"index_event line failed grammar: {line}"
);
}
}
pub fn event_matches(line: &str, plane: &str, root: &str, key: &str) -> bool {
let fields = index_event_fields(line);
fields.get("plane").map(String::as_str) == Some(plane)
&& fields.get("root").map(String::as_str) == Some(root)
&& fields.get("key").map(String::as_str) == Some(key)
}
pub fn assert_lifecycle_sequence(
lines: &[String],
plane: &str,
root: &str,
key: &str,
require_progress: bool,
) {
let events: Vec<_> = lines
.iter()
.filter(|line| event_matches(line, plane, root, key))
.cloned()
.collect();
assert_index_event_grammar(&events);
let kinds: Vec<_> = events
.iter()
.filter_map(|line| index_event_fields(line).get("kind").cloned())
.filter(|kind| {
matches!(
kind.as_str(),
"build_started" | "build_progress" | "build_ready"
)
})
.collect();
assert!(
kinds.first().is_some_and(|kind| kind == "build_started"),
"expected build_started first, got {kinds:?} from {events:?}"
);
if require_progress {
assert!(
kinds.iter().any(|kind| kind == "build_progress"),
"expected build_progress in {kinds:?} from {events:?}"
);
}
assert!(
kinds.last().is_some_and(|kind| kind == "build_ready"),
"expected build_ready last, got {kinds:?} from {events:?}"
);
let build_ids: Vec<_> = events
.iter()
.filter_map(|line| index_event_fields(line).get("build_id").cloned())
.collect();
assert!(!build_ids.is_empty());
assert!(
build_ids.iter().all(|id| id == &build_ids[0]),
"build_id drifted across events: {build_ids:?}"
);
for line in &events {
let fields = index_event_fields(line);
assert_eq!(fields.get("root").map(String::as_str), Some(root), "{line}");
assert_eq!(fields.get("key").map(String::as_str), Some(key), "{line}");
}
}
pub fn tiny_project(
name: &str,
file_name: &str,
contents: &str,
) -> (tempfile::TempDir, PathBuf) {
let temp = tempfile::tempdir().expect("tempdir");
let root = temp.path().join(name);
std::fs::create_dir_all(&root).expect("create project");
std::fs::write(root.join(file_name), contents).expect("write fixture");
let root = std::fs::canonicalize(&root).unwrap_or(root);
(temp, root)
}
#[test]
fn watcher_rescan_event_reports_reason_cost_rss_and_interval_count() {
let (_, lines) = capture_index_events(|| {
log_watcher_rescan(
Path::new("/tmp/watcher root"),
RescanReason::KernelDropped,
42,
Some(-4096),
137,
);
});
assert_index_event_grammar(&lines);
assert_eq!(lines.len(), 1);
let fields = index_event_fields(&lines[0]);
assert_eq!(
fields.get("kind").map(String::as_str),
Some("watcher_rescan")
);
assert_eq!(fields.get("plane").map(String::as_str), Some("watcher"));
assert_eq!(
fields.get("root").map(String::as_str),
Some("/tmp/watcher_root")
);
assert_eq!(
fields.get("reason").map(String::as_str),
Some("kernel_dropped")
);
assert_eq!(fields.get("cost_ms").map(String::as_str), Some("42"));
assert_eq!(
fields.get("rss_delta_bytes").map(String::as_str),
Some("-4096")
);
assert_eq!(
fields.get("raw_events_since_last").map(String::as_str),
Some("137")
);
}
#[test]
fn index_event_grammar_rejects_spaces_and_equals_in_values() {
let (result, lines) = capture_index_events(|| {
log_index_event(
IndexEvent::new(
IndexEventKind::BuildStarted,
IndexPlane::Search,
"b-1-1",
"/tmp/root",
"abc123",
)
.field("stage", "streaming"),
);
});
let _ = result;
assert_index_event_grammar(&lines);
let own: Vec<&String> = lines
.iter()
.filter(|line| {
index_event_fields(line).get("build_id").map(String::as_str) == Some("b-1-1")
})
.collect();
assert_eq!(own.len(), 1, "{lines:?}");
}
#[test]
fn index_event_keeps_required_fields_for_long_root() {
let root = format!("/{}", "a".repeat(399));
let (_, lines) = capture_index_events(|| {
log_index_event(IndexEvent::new(
IndexEventKind::BuildStarted,
IndexPlane::Search,
"b-9-9",
&root,
"keepkey",
));
});
assert_eq!(lines.len(), 1, "{lines:?}");
let fields = index_event_fields(&lines[0]);
assert_eq!(fields.get("build_id").map(String::as_str), Some("b-9-9"));
assert_eq!(fields.get("key").map(String::as_str), Some("keepkey"));
assert!(fields.get("root").is_some(), "{lines:?}");
assert_index_event_grammar(&lines);
}
#[test]
fn index_event_long_root_keeps_measurements_within_cap() {
let suffix = "/typescript-eslint/worker";
let root = format!("/{}{suffix}", "a".repeat(300 - 1 - suffix.len()));
assert_eq!(root.len(), 300);
let event = IndexEvent::new(
IndexEventKind::FirstQuery,
IndexPlane::Semantic,
"b-12345-123",
&root,
"workspace",
)
.field("tool", "semantic_search")
.field("queue_ms", 12)
.field("service_ms", 34)
.field("status", "ok")
.field("elapsed_ms", 5678)
.field("ready_to_first_query_ms", 9012)
.field("completed", 345)
.field("total", 678);
let line = format_index_event_line(&event);
assert!(line.len() <= INDEX_EVENT_MAX_BYTES, "{line}");
assert!(index_event_matches_grammar(&line), "{line}");
let fields = index_event_fields(&line);
for (key, value) in [
("elapsed_ms", "5678"),
("ready_to_first_query_ms", "9012"),
("completed", "345"),
("total", "678"),
("queue_ms", "12"),
("service_ms", "34"),
] {
assert_eq!(fields.get(key).map(String::as_str), Some(value), "{line}");
}
assert!(fields["root"].ends_with(suffix), "{line}");
assert_eq!(
line,
include_str!("../../../scripts/telemetry/fixtures/index-event-long-root.txt").trim()
);
}
#[test]
fn index_event_measurements_take_priority_over_long_descriptions() {
let event = IndexEvent::new(
IndexEventKind::FirstQuery,
IndexPlane::Search,
"b-1-1",
"/work/repo",
"0123456789abcdef",
)
.field("tool", "x".repeat(190))
.field("status", "x".repeat(300))
.field("ready_to_first_query_ms", 42);
let line = format_index_event_line(&event);
assert!(line.len() <= INDEX_EVENT_MAX_BYTES, "{line}");
assert_eq!(index_event_fields(&line)["ready_to_first_query_ms"], "42");
}
#[test]
fn shortened_index_roots_are_distinct_and_bounded() {
let root = format!("/{}/typescript-eslint/worker", "a".repeat(300));
let other = root.replacen('a', "b", 1);
let shortened = left_truncate_root(&root, 50);
assert!(shortened.starts_with(".../"));
assert!(shortened.ends_with("/typescript-eslint/worker"));
assert_ne!(shortened, left_truncate_root(&other, 50));
for budget in 0..50 {
assert!(left_truncate_root(&root, budget).len() <= budget);
}
}
#[test]
fn first_query_fires_once_per_build_id() {
let root = PathBuf::from("/tmp/first-query-root");
let key = "firstquerykey";
let build_id = "b-1-99";
let (_, lines) = capture_index_events(|| {
log_index_event(IndexEvent::new(
IndexEventKind::BuildReady,
IndexPlane::Search,
build_id,
&root,
key,
));
assert!(claim_first_query(
IndexPlane::Search,
&root,
"grep",
1,
2,
"ok"
));
assert!(!claim_first_query(
IndexPlane::Search,
&root,
"grep",
1,
2,
"ok"
));
});
let first_query: Vec<_> = lines
.iter()
.filter(|line| line.contains("kind=first_query"))
.collect();
assert_eq!(first_query.len(), 1, "{lines:?}");
let fields = index_event_fields(first_query[0]);
assert_eq!(fields.get("build_id").map(String::as_str), Some(build_id));
assert_eq!(fields.get("tool").map(String::as_str), Some("grep"));
}
}