Skip to main content

lean_ctx/core/
request_ledger.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Request ledger of a serving process (#2197).
3//!
4//! A worker that stops answering looks the same from outside whether it is
5//! idle, saturated, or stuck in one handler. The ledger tells them apart
6//! without touching the request queue: it counts every admitted request and
7//! exactly one outcome per request, keeps the oldest pending request's method
8//! and stage, and remembers the last `tools/call` completion separately from
9//! the last `initialize`.
10//!
11//! Privacy: only method names (`tools/call:ctx_read`, never arguments, paths
12//! or content) are kept, truncated, and the pending set is bounded.
13//!
14//! A serving process publishes its snapshot to `<data_dir>/requests/<pid>.json`
15//! from a dedicated thread, so `lean-ctx doctor` can read it even when every
16//! request worker is busy. In-process, the HTTP `/v1/health` route serves the
17//! same snapshot.
18
19use std::collections::BTreeMap;
20use std::sync::Mutex;
21use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
22use std::time::Duration;
23
24use serde::{Deserialize, Serialize};
25
26/// Pending requests whose method and stage are tracked; beyond that a request
27/// is still counted, but its stage is reported as unknown.
28const MAX_TRACKED_PENDING: usize = 4_096;
29/// Longest method name kept (bytes, cut at a character boundary).
30const MAX_METHOD_BYTES: usize = 64;
31/// How often the publisher thread looks for a change.
32const PUBLISH_INTERVAL: Duration = Duration::from_secs(2);
33/// A live publisher rewrites its snapshot at least this often, so a reader
34/// can tell a running process from a file a dead one left behind.
35pub const HEARTBEAT: Duration = Duration::from_secs(10);
36/// Snapshots older than this belong to a process that is gone.
37pub const STALE_AFTER: Duration = Duration::from_secs(120);
38
39/// Where a pending request is.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum Stage {
43    /// Admitted, not yet handed to the tool handler.
44    PreDispatch,
45    /// Inside the tool handler.
46    Handler,
47    /// The handler returned; the response is being finalized.
48    Finalizing,
49}
50
51impl Stage {
52    pub fn label(self) -> &'static str {
53        match self {
54            Self::PreDispatch => "pre-dispatch",
55            Self::Handler => "handler",
56            Self::Finalizing => "finalizing",
57        }
58    }
59}
60
61/// How a request ended. Each admitted request ends exactly once.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Outcome {
65    Completed,
66    Errored,
67    /// The client cancelled or disconnected before a response.
68    Abandoned,
69}
70
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
72pub struct PendingRequest {
73    pub method: String,
74    pub stage: Stage,
75    pub admitted_at_ms: u64,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub age_ms: Option<u64>,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct CompletionRecord {
82    pub method: String,
83    pub outcome: Outcome,
84    pub finished_at_ms: u64,
85    pub duration_ms: u64,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub age_ms: Option<u64>,
88}
89
90#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91pub struct PhaseRecord {
92    pub name: String,
93    pub running_ms: u64,
94}
95
96/// One point-in-time view of the ledger. `None` fields are unknown or did not
97/// happen yet; renderers spell them out instead of guessing.
98#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
99pub struct RequestLedgerSnapshot {
100    pub pid: u32,
101    /// `mcp-stdio`, `http` or `daemon`.
102    pub kind: String,
103    /// The process's producer identity, distinct per start.
104    pub generation: String,
105    pub started_at_ms: u64,
106    pub snapshot_at_ms: u64,
107    pub admitted: u64,
108    pub completed: u64,
109    pub errored: u64,
110    pub refused: u64,
111    pub abandoned: u64,
112    pub pending: u64,
113    /// Pending requests beyond the tracked bound (their stage is unknown).
114    pub untracked_pending: u64,
115    pub oldest_pending: Option<PendingRequest>,
116    pub last_tool_completion: Option<CompletionRecord>,
117    pub last_initialize: Option<CompletionRecord>,
118    pub current_phase: Option<PhaseRecord>,
119    pub observations: crate::core::events::DetachedObservationStats,
120    /// #2279: handler threads still running after their request stopped
121    /// waiting for them (watchdog fired, or the request was dropped). Such a
122    /// thread holds a blocking-pool slot that no pending request shows.
123    #[serde(default)]
124    pub orphaned_handlers: u64,
125    /// The longest-orphaned of those threads.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub oldest_orphaned_handler: Option<OrphanedHandler>,
128}
129
130/// A handler thread whose request no longer waits for it.
131#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
132pub struct OrphanedHandler {
133    pub method: String,
134    /// When its handler started.
135    pub started_at_ms: u64,
136    /// When its request stopped waiting.
137    pub orphaned_at_ms: u64,
138}
139
140struct Tracked {
141    method: String,
142    stage: Stage,
143    admitted_at_ms: u64,
144}
145
146struct Ledger {
147    pending: BTreeMap<u64, Tracked>,
148    last_tool_completion: Option<CompletionRecord>,
149    last_initialize: Option<CompletionRecord>,
150}
151
152static LEDGER: Mutex<Ledger> = Mutex::new(Ledger {
153    pending: BTreeMap::new(),
154    last_tool_completion: None,
155    last_initialize: None,
156});
157static NEXT_ID: AtomicU64 = AtomicU64::new(1);
158static ADMITTED: AtomicU64 = AtomicU64::new(0);
159static COMPLETED: AtomicU64 = AtomicU64::new(0);
160static ERRORED: AtomicU64 = AtomicU64::new(0);
161static REFUSED: AtomicU64 = AtomicU64::new(0);
162static ABANDONED: AtomicU64 = AtomicU64::new(0);
163/// Orphaned handler threads by id (ids in orphaning order).
164static ORPHANS: Mutex<BTreeMap<u64, OrphanedHandler>> = Mutex::new(BTreeMap::new());
165static NEXT_ORPHAN_ID: AtomicU64 = AtomicU64::new(1);
166static STARTED_AT_MS: AtomicU64 = AtomicU64::new(0);
167static SERVING: AtomicBool = AtomicBool::new(false);
168static FINISHED: AtomicBool = AtomicBool::new(false);
169static DIRTY: AtomicBool = AtomicBool::new(false);
170static KIND: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
171
172fn ledger() -> std::sync::MutexGuard<'static, Ledger> {
173    LEDGER
174        .lock()
175        .unwrap_or_else(std::sync::PoisonError::into_inner)
176}
177
178fn now_ms() -> u64 {
179    std::time::SystemTime::now()
180        .duration_since(std::time::UNIX_EPOCH)
181        .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
182        .unwrap_or_default()
183}
184
185/// Method names as the ledger keeps them: printable ASCII only, bounded.
186fn sanitize_method(method: &str) -> String {
187    method
188        .chars()
189        .filter(char::is_ascii_graphic)
190        .take(MAX_METHOD_BYTES)
191        .collect()
192}
193
194/// Mark this process as serving requests of `kind`: observations no longer
195/// block dispatch (#2196) and the snapshot publisher starts. Idempotent.
196pub fn start_serving(kind: &'static str) {
197    crate::core::events::enable_detached_observations();
198    if SERVING.swap(true, Ordering::AcqRel) {
199        return;
200    }
201    let _ = KIND.set(kind);
202    STARTED_AT_MS.store(now_ms(), Ordering::Relaxed);
203    DIRTY.store(true, Ordering::Release);
204    if let Some(dir) = snapshot_dir() {
205        let _ = std::thread::Builder::new()
206            .name("lean-ctx-request-ledger".to_string())
207            .spawn(move || publish_loop(&dir));
208    }
209}
210
211pub fn serving() -> bool {
212    SERVING.load(Ordering::Acquire)
213}
214
215/// Shutdown of a serving process: persist the observations still queued for
216/// the detached writer (bounded by `timeout`) and withdraw this process's
217/// published snapshot, so `lean-ctx doctor` does not list a stopped server.
218/// Runs once; later calls return at once. Blocking — call it from a plain
219/// thread or `spawn_blocking`, never directly on an async worker.
220pub fn finish_serving(timeout: Duration) {
221    if FINISHED.swap(true, Ordering::AcqRel) {
222        return;
223    }
224    crate::core::events::flush_detached_observations(timeout);
225    if SERVING.load(Ordering::Acquire)
226        && let Some(dir) = snapshot_dir()
227    {
228        let _ = std::fs::remove_file(dir.join(format!("{}.json", std::process::id())));
229    }
230}
231
232/// Count a request turned away before admission (rate or concurrency limit).
233pub fn refused() {
234    REFUSED.fetch_add(1, Ordering::Relaxed);
235    DIRTY.store(true, Ordering::Release);
236}
237
238/// Admit one request. The returned guard records exactly one outcome: the
239/// one passed to [`RequestGuard::finish`], or `Abandoned` when it is dropped
240/// unfinished (the request future was cancelled or the client went away).
241#[must_use = "the request is abandoned when the guard drops unfinished"]
242pub fn begin(method: &str) -> RequestGuard {
243    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
244    let admitted_at_ms = now_ms();
245    let method = sanitize_method(method);
246    ADMITTED.fetch_add(1, Ordering::Relaxed);
247    {
248        let mut ledger = ledger();
249        if ledger.pending.len() < MAX_TRACKED_PENDING {
250            ledger.pending.insert(
251                id,
252                Tracked {
253                    method: method.clone(),
254                    stage: Stage::PreDispatch,
255                    admitted_at_ms,
256                },
257            );
258        }
259    }
260    DIRTY.store(true, Ordering::Release);
261    RequestGuard {
262        id,
263        method,
264        admitted_at_ms,
265        finished: false,
266    }
267}
268
269pub struct RequestGuard {
270    id: u64,
271    method: String,
272    admitted_at_ms: u64,
273    finished: bool,
274}
275
276impl RequestGuard {
277    pub fn stage(&self, stage: Stage) {
278        if let Some(tracked) = ledger().pending.get_mut(&self.id) {
279            tracked.stage = stage;
280        }
281        DIRTY.store(true, Ordering::Release);
282    }
283
284    pub fn finish(mut self, outcome: Outcome) {
285        self.record(outcome);
286    }
287
288    fn record(&mut self, outcome: Outcome) {
289        if std::mem::replace(&mut self.finished, true) {
290            return;
291        }
292        match outcome {
293            Outcome::Completed => &COMPLETED,
294            Outcome::Errored => &ERRORED,
295            Outcome::Abandoned => &ABANDONED,
296        }
297        .fetch_add(1, Ordering::Relaxed);
298        let finished_at_ms = now_ms();
299        let record = CompletionRecord {
300            method: std::mem::take(&mut self.method),
301            outcome,
302            finished_at_ms,
303            duration_ms: finished_at_ms.saturating_sub(self.admitted_at_ms),
304            age_ms: None,
305        };
306        {
307            let mut ledger = ledger();
308            ledger.pending.remove(&self.id);
309            if record.method == "initialize" {
310                ledger.last_initialize = Some(record);
311            } else if record.method.starts_with("tools/call") {
312                ledger.last_tool_completion = Some(record);
313            }
314        }
315        DIRTY.store(true, Ordering::Release);
316    }
317}
318
319impl Drop for RequestGuard {
320    fn drop(&mut self) {
321        self.record(Outcome::Abandoned);
322    }
323}
324
325fn orphans() -> std::sync::MutexGuard<'static, BTreeMap<u64, OrphanedHandler>> {
326    ORPHANS
327        .lock()
328        .unwrap_or_else(std::sync::PoisonError::into_inner)
329}
330
331enum HandlerState {
332    Running,
333    Orphaned(u64),
334    Done,
335}
336
337/// Pair of guards around one handler thread (#2279): [`HandlerRun`] lives
338/// on the thread, [`HandlerWait`] on the side that awaits it. When the
339/// waiting side lets go first, the still-running thread is listed as
340/// orphaned until it ends.
341pub fn watch_handler(method: &str) -> (HandlerWait, HandlerRun) {
342    let state = std::sync::Arc::new(Mutex::new(HandlerState::Running));
343    (
344        HandlerWait {
345            state: state.clone(),
346            method: sanitize_method(method),
347            started_at_ms: now_ms(),
348        },
349        HandlerRun { state },
350    )
351}
352
353/// The awaiting side's guard. Drop it once the wait is over, however it
354/// ended.
355pub struct HandlerWait {
356    state: std::sync::Arc<Mutex<HandlerState>>,
357    method: String,
358    started_at_ms: u64,
359}
360
361impl Drop for HandlerWait {
362    fn drop(&mut self) {
363        let mut state = self
364            .state
365            .lock()
366            .unwrap_or_else(std::sync::PoisonError::into_inner);
367        if matches!(*state, HandlerState::Running) {
368            let id = NEXT_ORPHAN_ID.fetch_add(1, Ordering::Relaxed);
369            orphans().insert(
370                id,
371                OrphanedHandler {
372                    method: std::mem::take(&mut self.method),
373                    started_at_ms: self.started_at_ms,
374                    orphaned_at_ms: now_ms(),
375                },
376            );
377            *state = HandlerState::Orphaned(id);
378            DIRTY.store(true, Ordering::Release);
379        }
380    }
381}
382
383/// The handler thread's guard. It drops when the handler ends, also by
384/// unwinding.
385pub struct HandlerRun {
386    state: std::sync::Arc<Mutex<HandlerState>>,
387}
388
389impl Drop for HandlerRun {
390    fn drop(&mut self) {
391        let mut state = self
392            .state
393            .lock()
394            .unwrap_or_else(std::sync::PoisonError::into_inner);
395        if let HandlerState::Orphaned(id) = *state {
396            orphans().remove(&id);
397            DIRTY.store(true, Ordering::Release);
398        }
399        *state = HandlerState::Done;
400    }
401}
402
403/// The ledger now, without ages (a snapshot is a cacheable fact; ages are
404/// the reader's arithmetic, see [`RequestLedgerSnapshot::with_ages`]).
405pub fn snapshot() -> RequestLedgerSnapshot {
406    let (oldest_pending, tracked, last_tool_completion, last_initialize) = {
407        let ledger = ledger();
408        // Ids are handed out in admission order, so the first key is the
409        // oldest pending request.
410        let oldest = ledger
411            .pending
412            .first_key_value()
413            .map(|(_, t)| PendingRequest {
414                method: t.method.clone(),
415                stage: t.stage,
416                admitted_at_ms: t.admitted_at_ms,
417                age_ms: None,
418            });
419        (
420            oldest,
421            ledger.pending.len() as u64,
422            ledger.last_tool_completion.clone(),
423            ledger.last_initialize.clone(),
424        )
425    };
426    // Outcome counters are read after the admitted counter would race; read
427    // admitted last so `pending` never underflows.
428    let completed = COMPLETED.load(Ordering::Relaxed);
429    let errored = ERRORED.load(Ordering::Relaxed);
430    let abandoned = ABANDONED.load(Ordering::Relaxed);
431    let admitted = ADMITTED.load(Ordering::Relaxed);
432    let pending = admitted.saturating_sub(completed + errored + abandoned);
433    let (orphaned_handlers, oldest_orphaned_handler) = {
434        let orphans = orphans();
435        (
436            orphans.len() as u64,
437            orphans.first_key_value().map(|(_, o)| o.clone()),
438        )
439    };
440    RequestLedgerSnapshot {
441        pid: std::process::id(),
442        kind: KIND.get().copied().unwrap_or("unknown").to_string(),
443        generation: crate::core::context_os::observation::producer_instance().to_string(),
444        started_at_ms: STARTED_AT_MS.load(Ordering::Relaxed),
445        snapshot_at_ms: now_ms(),
446        admitted,
447        completed,
448        errored,
449        refused: REFUSED.load(Ordering::Relaxed),
450        abandoned,
451        pending,
452        // A request stops being tracked only when the map is full. Below that
453        // bound a gap between the counters and the map is a request admitted
454        // between the two reads, not an untracked one.
455        untracked_pending: if tracked < MAX_TRACKED_PENDING as u64 {
456            0
457        } else {
458            pending.saturating_sub(tracked)
459        },
460        oldest_pending,
461        last_tool_completion,
462        last_initialize,
463        current_phase: crate::core::phase_timing::current().map(|(name, running)| PhaseRecord {
464            name: name.to_string(),
465            running_ms: u64::try_from(running.as_millis()).unwrap_or(u64::MAX),
466        }),
467        observations: crate::core::events::detached_observation_stats(),
468        orphaned_handlers,
469        oldest_orphaned_handler,
470    }
471}
472
473impl RequestLedgerSnapshot {
474    /// Fill the `age_ms` fields relative to `now_ms`.
475    #[must_use]
476    pub fn with_ages(mut self, now_ms: u64) -> Self {
477        if let Some(pending) = self.oldest_pending.as_mut() {
478            pending.age_ms = Some(now_ms.saturating_sub(pending.admitted_at_ms));
479        }
480        for record in [
481            self.last_tool_completion.as_mut(),
482            self.last_initialize.as_mut(),
483        ]
484        .into_iter()
485        .flatten()
486        {
487            record.age_ms = Some(now_ms.saturating_sub(record.finished_at_ms));
488        }
489        self
490    }
491
492    /// One human line for `lean-ctx doctor`.
493    pub fn render(&self, now_ms: u64) -> String {
494        let age = |at: u64| format_age(now_ms.saturating_sub(at));
495        let oldest = if self.pending == 0 {
496            "none".to_string()
497        } else {
498            match &self.oldest_pending {
499                Some(p) => format!(
500                    "{} {} in {}",
501                    p.method,
502                    age(p.admitted_at_ms),
503                    p.stage.label()
504                ),
505                None if self.untracked_pending > 0 => "unknown (untracked)".to_string(),
506                None => "none".to_string(),
507            }
508        };
509        let last = |record: &Option<CompletionRecord>| match record {
510            Some(r) => format!(
511                "{} ago ({}, {}ms)",
512                age(r.finished_at_ms),
513                outcome_label(r.outcome),
514                r.duration_ms
515            ),
516            None => "none yet".to_string(),
517        };
518        let mut line = format!(
519            "pid {} ({}), up {}: admitted {} · completed {} · errored {} · refused {} · abandoned {} · pending {}; oldest pending {}; last tool completion {}; last initialize {}",
520            self.pid,
521            self.kind,
522            age(self.started_at_ms),
523            self.admitted,
524            self.completed,
525            self.errored,
526            self.refused,
527            self.abandoned,
528            self.pending,
529            oldest,
530            last(&self.last_tool_completion),
531            last(&self.last_initialize),
532        );
533        if let Some(phase) = &self.current_phase {
534            line.push_str(&format!(
535                "; phase {} {}",
536                phase.name,
537                format_age(phase.running_ms)
538            ));
539        }
540        if self.orphaned_handlers > 0 {
541            let oldest = self.oldest_orphaned_handler.as_ref().map_or_else(
542                || "unknown".to_string(),
543                |o| format!("{} {} since abandoned", o.method, age(o.orphaned_at_ms)),
544            );
545            line.push_str(&format!(
546                "; orphaned handlers {} (oldest {oldest})",
547                self.orphaned_handlers
548            ));
549        }
550        if self.observations.dropped > 0 || self.observations.failed > 0 {
551            line.push_str(&format!(
552                "; observations dropped {} · failed {}",
553                self.observations.dropped, self.observations.failed
554            ));
555        }
556        let snapshot_age = now_ms.saturating_sub(self.snapshot_at_ms);
557        if snapshot_age > HEARTBEAT.as_millis() as u64 * 2 {
558            line.push_str(&format!("; snapshot {} old", format_age(snapshot_age)));
559        }
560        line
561    }
562
563    /// Age of the oldest pending request at `now_ms`, if one is tracked.
564    pub fn oldest_pending_age(&self, now_ms: u64) -> Option<Duration> {
565        self.oldest_pending
566            .as_ref()
567            .map(|p| Duration::from_millis(now_ms.saturating_sub(p.admitted_at_ms)))
568    }
569}
570
571fn outcome_label(outcome: Outcome) -> &'static str {
572    match outcome {
573        Outcome::Completed => "completed",
574        Outcome::Errored => "errored",
575        Outcome::Abandoned => "abandoned",
576    }
577}
578
579fn format_age(ms: u64) -> String {
580    match ms {
581        0..1_000 => format!("{ms}ms"),
582        1_000..120_000 => format!("{}s", ms / 1_000),
583        120_000..7_200_000 => format!("{}m", ms / 60_000),
584        _ => format!("{}h", ms / 3_600_000),
585    }
586}
587
588/// Milliseconds since the Unix epoch, the clock snapshots are stamped with.
589pub fn epoch_ms() -> u64 {
590    now_ms()
591}
592
593fn snapshot_dir() -> Option<std::path::PathBuf> {
594    crate::core::data_dir::lean_ctx_data_dir()
595        .ok()
596        .map(|dir| dir.join("requests"))
597}
598
599fn publish_loop(dir: &std::path::Path) {
600    if std::fs::create_dir_all(dir).is_err() {
601        return;
602    }
603    sweep_stale(dir, now_ms());
604    let path = dir.join(format!("{}.json", std::process::id()));
605    let mut last_write_ms = 0u64;
606    loop {
607        // Shutdown withdrew the snapshot; never write it back.
608        if FINISHED.load(Ordering::Acquire) {
609            return;
610        }
611        let now = now_ms();
612        let heartbeat_due = now.saturating_sub(last_write_ms) >= HEARTBEAT.as_millis() as u64;
613        if DIRTY.swap(false, Ordering::AcqRel) || heartbeat_due {
614            if let Ok(bytes) = serde_json::to_vec(&snapshot()) {
615                let _ = crate::core::atomic_fs::try_atomic_write(&path, &bytes, None);
616            }
617            // Shutdown may have withdrawn the snapshot while this write was
618            // in flight: withdraw it again, after the write.
619            if FINISHED.load(Ordering::Acquire) {
620                let _ = std::fs::remove_file(&path);
621                return;
622            }
623            last_write_ms = now;
624        }
625        std::thread::sleep(PUBLISH_INTERVAL);
626    }
627}
628
629/// Remove snapshots whose publisher stopped long ago (its process is gone:
630/// a live publisher rewrites its file every [`HEARTBEAT`]).
631fn sweep_stale(dir: &std::path::Path, now: u64) {
632    for snapshot in read_dir_snapshots(dir) {
633        if now.saturating_sub(snapshot.1.snapshot_at_ms) > STALE_AFTER.as_millis() as u64 * 5 {
634            let _ = std::fs::remove_file(&snapshot.0);
635        }
636    }
637}
638
639fn read_dir_snapshots(dir: &std::path::Path) -> Vec<(std::path::PathBuf, RequestLedgerSnapshot)> {
640    const MAX_BYTES: u64 = 64 * 1024;
641    let Ok(entries) = std::fs::read_dir(dir) else {
642        return Vec::new();
643    };
644    let mut snapshots: Vec<_> = entries
645        .flatten()
646        .map(|entry| entry.path())
647        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
648        .filter(|path| std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_BYTES))
649        .filter_map(|path| {
650            let text = std::fs::read_to_string(&path).ok()?;
651            let snapshot = serde_json::from_str(&text).ok()?;
652            Some((path, snapshot))
653        })
654        .collect();
655    snapshots.sort_by_key(|(_, s): &(_, RequestLedgerSnapshot)| s.pid);
656    snapshots
657}
658
659/// Snapshots published by serving processes that are still running, by pid.
660pub fn published_snapshots() -> Vec<RequestLedgerSnapshot> {
661    let Some(dir) = snapshot_dir() else {
662        return Vec::new();
663    };
664    let now = now_ms();
665    read_dir_snapshots(&dir)
666        .into_iter()
667        .map(|(_, snapshot)| snapshot)
668        .filter(|s| now.saturating_sub(s.snapshot_at_ms) <= STALE_AFTER.as_millis() as u64)
669        .collect()
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675
676    fn orphaned(method: &str) -> usize {
677        orphans().values().filter(|o| o.method == method).count()
678    }
679
680    /// #2279: a handler whose request stopped waiting is listed as orphaned
681    /// until its thread ends; one that ends first is never listed.
682    #[test]
683    fn handler_left_running_is_orphaned_until_it_ends() {
684        let (wait, run) = watch_handler("tools/call:orphan_test_done");
685        drop(run);
686        drop(wait);
687        assert_eq!(orphaned("tools/call:orphan_test_done"), 0);
688
689        let (wait, run) = watch_handler("tools/call:orphan_test_left");
690        drop(wait);
691        assert_eq!(orphaned("tools/call:orphan_test_left"), 1);
692        let snap = snapshot();
693        assert!(snap.orphaned_handlers >= 1);
694        assert!(snap.oldest_orphaned_handler.is_some());
695        let thread = std::thread::spawn(move || drop(run));
696        thread.join().unwrap();
697        assert_eq!(orphaned("tools/call:orphan_test_left"), 0);
698    }
699
700    /// The snapshot written by an older build has no orphan fields.
701    #[test]
702    fn snapshot_without_orphan_fields_still_parses() {
703        let mut value = serde_json::to_value(snapshot()).unwrap();
704        let object = value.as_object_mut().unwrap();
705        object.remove("orphaned_handlers");
706        object.remove("oldest_orphaned_handler");
707        let parsed: RequestLedgerSnapshot = serde_json::from_value(value).unwrap();
708        assert_eq!(parsed.orphaned_handlers, 0);
709        assert!(parsed.oldest_orphaned_handler.is_none());
710    }
711
712    fn counts() -> (u64, u64, u64, u64) {
713        (
714            ADMITTED.load(Ordering::Relaxed),
715            COMPLETED.load(Ordering::Relaxed),
716            ERRORED.load(Ordering::Relaxed),
717            ABANDONED.load(Ordering::Relaxed),
718        )
719    }
720
721    /// Acceptance of #2197: completion, error and disconnect each update
722    /// their own counter exactly once, the oldest pending request shows its
723    /// method and stage, and the last tool completion is kept apart from the
724    /// last initialize.
725    #[test]
726    fn each_request_path_counts_its_outcome_exactly_once() {
727        if crate::test_env::run_in_own_process(
728            "core::request_ledger::tests::each_request_path_counts_its_outcome_exactly_once",
729            &[],
730        ) {
731            return;
732        }
733        let init = begin("initialize");
734        init.finish(Outcome::Completed);
735
736        let stuck = begin("tools/call:ctx_read");
737        stuck.stage(Stage::Handler);
738        std::thread::sleep(Duration::from_millis(5));
739        let completed = begin("tools/call:ctx_search");
740        completed.stage(Stage::Handler);
741        completed.stage(Stage::Finalizing);
742        completed.finish(Outcome::Completed);
743        begin("tools/call:ctx_shell").finish(Outcome::Errored);
744        // A cancelled request future drops its guard without finishing.
745        drop(begin("tools/call:ctx_tree"));
746        refused();
747
748        assert_eq!(counts(), (5, 2, 1, 1));
749        let snap = snapshot();
750        assert_eq!(snap.pending, 1);
751        assert_eq!(snap.refused, 1);
752        assert_eq!(snap.untracked_pending, 0);
753        let oldest = snap.oldest_pending.clone().expect("pending tracked");
754        assert_eq!(
755            (oldest.method.as_str(), oldest.stage),
756            ("tools/call:ctx_read", Stage::Handler)
757        );
758        let tool = snap.last_tool_completion.clone().expect("tool completion");
759        // The abandoned call is the most recent tools/call outcome.
760        assert_eq!(tool.method, "tools/call:ctx_tree");
761        assert_eq!(tool.outcome, Outcome::Abandoned);
762        assert_eq!(
763            snap.last_initialize.as_ref().map(|r| r.outcome),
764            Some(Outcome::Completed)
765        );
766
767        let now = oldest.admitted_at_ms + 74_000;
768        let line = snap.clone().render(now);
769        assert!(
770            line.contains("oldest pending tools/call:ctx_read 74s in handler"),
771            "{line}"
772        );
773        assert!(
774            line.contains(
775                "admitted 5 · completed 2 · errored 1 · refused 1 · abandoned 1 · pending 1"
776            ),
777            "{line}"
778        );
779        assert_eq!(
780            snap.with_ages(now).oldest_pending.and_then(|p| p.age_ms),
781            Some(74_000)
782        );
783
784        stuck.finish(Outcome::Completed);
785        assert_eq!(counts(), (5, 3, 1, 1));
786        assert_eq!(snapshot().pending, 0);
787    }
788
789    /// A stopped server withdraws its snapshot and the publisher never
790    /// writes it back, so `lean-ctx doctor` does not list it (#2197).
791    #[test]
792    fn finish_serving_withdraws_the_published_snapshot() {
793        let data = tempfile::tempdir().expect("tempdir");
794        let data_dir = data.path().to_str().expect("utf-8 temp path");
795        if crate::test_env::run_in_own_process(
796            "core::request_ledger::tests::finish_serving_withdraws_the_published_snapshot",
797            &[("LEAN_CTX_DATA_DIR", data_dir)],
798        ) {
799            return;
800        }
801        let path = snapshot_dir()
802            .expect("data dir")
803            .join(format!("{}.json", std::process::id()));
804        start_serving("test");
805        let deadline = std::time::Instant::now() + PUBLISH_INTERVAL * 3;
806        while !path.exists() && std::time::Instant::now() < deadline {
807            std::thread::sleep(Duration::from_millis(50));
808        }
809        assert!(path.exists(), "snapshot published at {}", path.display());
810
811        finish_serving(Duration::from_secs(5));
812        assert!(!path.exists(), "snapshot withdrawn");
813        refused();
814        std::thread::sleep(PUBLISH_INTERVAL * 2);
815        assert!(!path.exists(), "publisher wrote the snapshot back");
816    }
817
818    #[test]
819    fn method_names_are_bounded_printable_identifiers() {
820        let long = format!("tools/call:{}\n{}", "x".repeat(200), "secret path");
821        let kept = sanitize_method(&long);
822        assert!(kept.len() <= MAX_METHOD_BYTES);
823        assert!(kept.chars().all(|c| c.is_ascii_graphic()));
824    }
825}