Skip to main content

lean_ctx/core/
events.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use serde::{Deserialize, Serialize};
4use std::collections::VecDeque;
5use std::io::Write;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Mutex, OnceLock};
8
9const RING_CAPACITY: usize = 1000;
10#[cfg(test)]
11const JSONL_MAX_LINES: usize = 10_000;
12const EVENT_ID_BLOCK_SIZE: u64 = 1_024;
13
14#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
15pub struct LeanCtxEvent {
16    pub id: u64,
17    pub timestamp: String,
18    pub kind: EventKind,
19}
20
21#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
22#[serde(tag = "type")]
23pub enum EventKind {
24    ToolCall {
25        tool: String,
26        tokens_original: u64,
27        tokens_saved: u64,
28        mode: Option<String>,
29        duration_ms: u64,
30        path: Option<String>,
31    },
32    CacheHit {
33        path: String,
34        saved_tokens: u64,
35    },
36    Compression {
37        path: String,
38        before_lines: u32,
39        after_lines: u32,
40        strategy: String,
41        kept_line_count: u32,
42        removed_line_count: u32,
43    },
44    AgentAction {
45        agent_id: String,
46        action: String,
47        tool: Option<String>,
48    },
49    KnowledgeUpdate {
50        category: String,
51        key: String,
52        action: String,
53    },
54    ThresholdShift {
55        language: String,
56        old_entropy: f64,
57        new_entropy: f64,
58        old_jaccard: f64,
59        new_jaccard: f64,
60    },
61    PolicyViolation {
62        role: String,
63        tool: String,
64        reason: String,
65    },
66    RoleChanged {
67        from: String,
68        to: String,
69    },
70    ProfileChanged {
71        from: String,
72        to: String,
73    },
74    VerificationWarning {
75        warning_kind: String,
76        detail: String,
77        severity: String,
78    },
79    ThresholdAdapted {
80        language: String,
81        arm: String,
82        old_threshold: f64,
83        new_threshold: f64,
84    },
85}
86
87/// Event kinds written by older releases whose feature was removed (agent
88/// budget limits, SLO evaluation, anomaly detection). Persisted records of
89/// these kinds are skipped on read so existing journals and observation stores
90/// stay loadable; every other record is still validated strictly.
91const RETIRED_EVENT_KINDS: &[&str] = &[
92    "BudgetWarning",
93    "BudgetExhausted",
94    "SloViolation",
95    "Anomaly",
96];
97
98/// True when `json` is a serialized [`LeanCtxEvent`] of a retired kind.
99pub(crate) fn is_retired_event_record(json: &str) -> bool {
100    #[derive(Deserialize)]
101    struct KindTag {
102        #[serde(rename = "type")]
103        tag: String,
104    }
105    #[derive(Deserialize)]
106    struct Record {
107        kind: KindTag,
108    }
109    serde_json::from_str::<Record>(json)
110        .is_ok_and(|record| RETIRED_EVENT_KINDS.contains(&record.kind.tag.as_str()))
111}
112
113struct EventBus {
114    ring: Mutex<VecDeque<LeanCtxEvent>>,
115}
116
117impl EventBus {
118    fn new() -> Self {
119        Self {
120            ring: Mutex::new(VecDeque::with_capacity(RING_CAPACITY)),
121        }
122    }
123
124    fn record(&self, event: LeanCtxEvent) {
125        let Ok(mut ring) = crate::core::context_os::observation::lock_observation(&self.ring)
126        else {
127            tracing::warn!(
128                "legacy projection unavailable; committed observation retained in ContextBus"
129            );
130            return;
131        };
132        if ring.len() >= RING_CAPACITY {
133            ring.pop_front();
134        }
135        ring.push_back(event);
136    }
137
138    fn events_since(&self, after_id: u64) -> Vec<LeanCtxEvent> {
139        let ring = self
140            .ring
141            .lock()
142            .unwrap_or_else(std::sync::PoisonError::into_inner);
143        ring.iter().filter(|e| e.id > after_id).cloned().collect()
144    }
145
146    fn latest_events(&self, n: usize) -> Vec<LeanCtxEvent> {
147        let ring = self
148            .ring
149            .lock()
150            .unwrap_or_else(std::sync::PoisonError::into_inner);
151        let len = ring.len();
152        let start = len.saturating_sub(n);
153        ring.iter().skip(start).cloned().collect()
154    }
155}
156
157fn bus() -> &'static EventBus {
158    static INSTANCE: OnceLock<EventBus> = OnceLock::new();
159    INSTANCE.get_or_init(EventBus::new)
160}
161
162fn jsonl_path() -> Option<std::path::PathBuf> {
163    crate::core::paths::state_dir()
164        .ok()
165        .map(|d| d.join("events.jsonl"))
166}
167
168fn event_sequence_path() -> Option<std::path::PathBuf> {
169    crate::core::paths::state_dir()
170        .ok()
171        .map(|d| d.join("events.seq"))
172}
173
174/// Identity-only view of a journal line: retired event kinds still reserve
175/// their IDs, so the next allocated ID never collides with old history.
176#[derive(Deserialize)]
177struct EventIdOnly {
178    id: u64,
179}
180
181fn max_event_id_in_journal(path: &std::path::Path) -> u64 {
182    let Ok(content) = std::fs::read_to_string(path) else {
183        return 0;
184    };
185    content
186        .lines()
187        .filter_map(|line| serde_json::from_str::<EventIdOnly>(line).ok())
188        .map(|event| event.id)
189        .max()
190        .unwrap_or(0)
191}
192
193fn parse_sequence_record(record: &str) -> Option<u64> {
194    let (value, checksum) = record.trim().split_once(':')?;
195    let value = value.parse::<u64>().ok()?;
196    let checksum = checksum.parse::<u64>().ok()?;
197    (checksum == !value).then_some(value)
198}
199
200fn read_persisted_sequence(path: &std::path::Path) -> Option<u64> {
201    let content = std::fs::read_to_string(path).ok()?;
202    content.lines().rev().find_map(parse_sequence_record)
203}
204
205fn sequence_record(value: u64) -> String {
206    format!("{value}:{}", !value)
207}
208
209fn reserve_event_id_block_at(
210    sequence_path: &std::path::Path,
211    journal_path: &std::path::Path,
212    block_size: u64,
213) -> std::io::Result<(u64, u64)> {
214    use fs2::FileExt;
215
216    if block_size == 0 {
217        return Err(std::io::Error::other("event id block must not be empty"));
218    }
219    if let Some(parent) = sequence_path.parent() {
220        std::fs::create_dir_all(parent)?;
221    }
222    // Lock a stable companion inode. The append-only sequence journal can be
223    // repaired without allowing another process to bypass the lock.
224    let lock_path = sequence_path.with_extension("seq.lock");
225    let lock = std::fs::OpenOptions::new()
226        .create(true)
227        .truncate(false)
228        .read(true)
229        .write(true)
230        .open(lock_path)?;
231    lock.lock_exclusive()?;
232
233    let result = (|| {
234        let persisted = read_persisted_sequence(sequence_path);
235        let baseline = persisted.unwrap_or_else(|| {
236            max_event_id_in_journal(journal_path).max(max_event_id_in_journal(
237                &journal_path.with_extension("jsonl.old"),
238            ))
239        });
240        let first = baseline
241            .checked_add(1)
242            .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
243        let last = baseline
244            .checked_add(block_size)
245            .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
246
247        // A prior writer's record (or corruption) may leave the file without
248        // a trailing newline; appending directly would fuse onto that line
249        // and make both records unparsable. Start a fresh line first.
250        let needs_leading_newline = std::fs::read(sequence_path)
251            .is_ok_and(|bytes| !bytes.is_empty() && bytes.last() != Some(&b'\n'));
252
253        let mut sequence = std::fs::OpenOptions::new()
254            .create(true)
255            .append(true)
256            .open(sequence_path)?;
257        let mut record = Vec::new();
258        if needs_leading_newline {
259            record.push(b'\n');
260        }
261        record.extend_from_slice(sequence_record(last).as_bytes());
262        record.push(b'\n');
263        sequence.write_all(&record)?;
264        sequence.sync_data()?;
265        Ok((first, last))
266    })();
267
268    let _ = FileExt::unlock(&lock);
269    result
270}
271
272#[cfg(test)]
273fn next_event_id_at(
274    sequence_path: &std::path::Path,
275    journal_path: &std::path::Path,
276) -> std::io::Result<u64> {
277    reserve_event_id_block_at(sequence_path, journal_path, 1).map(|(first, _)| first)
278}
279
280fn next_event_id() -> u64 {
281    #[derive(Default)]
282    struct LocalBlock {
283        next: u64,
284        last: u64,
285    }
286
287    static BLOCK: OnceLock<Mutex<LocalBlock>> = OnceLock::new();
288    static FALLBACK: AtomicU64 = AtomicU64::new(0);
289    if !is_test_environment()
290        && let Some((sequence, journal)) = event_sequence_path().zip(jsonl_path())
291    {
292        let mut block = BLOCK
293            .get_or_init(|| Mutex::new(LocalBlock::default()))
294            .lock()
295            .unwrap_or_else(std::sync::PoisonError::into_inner);
296        if block.next <= block.last && block.next != 0 {
297            let id = block.next;
298            block.next = block.next.saturating_add(1);
299            return id;
300        }
301        if let Ok((first, last)) =
302            reserve_event_id_block_at(&sequence, &journal, EVENT_ID_BLOCK_SIZE)
303        {
304            block.next = first.saturating_add(1);
305            block.last = last;
306            return first;
307        }
308    }
309
310    fallback_event_id(
311        &FALLBACK,
312        lean_ctx_time::UtcDateTime::now().timestamp_millis(),
313    )
314}
315
316/// Clock-derived id (milliseconds × 1000) that is strictly increasing within
317/// the process even when the wall clock steps back (an NTP correction on a
318/// CI runner): `max(last + 1, now)`. The former `now + counter` could repeat
319/// an id after such a step — the canonical store then rejects the event as an
320/// identity conflict — or order a later event before an earlier one.
321fn fallback_event_id(last: &AtomicU64, now_millis: i64) -> u64 {
322    let now = u64::try_from(now_millis)
323        .unwrap_or_default()
324        .saturating_mul(1_000);
325    let mut current = last.load(Ordering::Relaxed);
326    loop {
327        let next = now.max(current.saturating_add(1));
328        match last.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
329            Ok(_) => return next,
330            Err(observed) => current = observed,
331        }
332    }
333}
334
335fn is_test_environment() -> bool {
336    use std::sync::OnceLock;
337    static CACHED: OnceLock<bool> = OnceLock::new();
338    *CACHED.get_or_init(|| {
339        if cfg!(test) {
340            return true;
341        }
342        if std::env::var_os("__LEAN_CTX_SKIP_EVENTS").is_some() {
343            return true;
344        }
345        std::env::current_exe().is_ok_and(|p| {
346            let s = p.to_string_lossy();
347            s.contains("/deps/") || s.contains("\\deps\\")
348        })
349    })
350}
351
352#[cfg(test)]
353fn append_jsonl_at(path: &std::path::Path, event: &LeanCtxEvent) -> std::io::Result<()> {
354    use fs2::FileExt;
355    use std::io::Write;
356
357    if let Some(parent) = path.parent() {
358        std::fs::create_dir_all(parent)?;
359    }
360
361    // Lock a stable companion inode rather than events.jsonl itself: rotation
362    // renames the data file, so locking that inode would let another process
363    // open the replacement and bypass the lock.
364    let lock_path = path.with_extension("jsonl.lock");
365    let lock = std::fs::OpenOptions::new()
366        .create(true)
367        .truncate(false)
368        .read(true)
369        .write(true)
370        .open(lock_path)?;
371    lock.lock_exclusive()?;
372
373    let result = (|| {
374        if let Ok(content) = std::fs::read_to_string(path)
375            && content.lines().count() >= JSONL_MAX_LINES
376        {
377            let old = path.with_extension("jsonl.old");
378            let _ = std::fs::remove_file(&old);
379            std::fs::rename(path, old)?;
380        }
381
382        let json = serde_json::to_string(event).map_err(std::io::Error::other)?;
383        let mut line = json.into_bytes();
384        line.push(b'\n');
385        let mut file = std::fs::OpenOptions::new()
386            .create(true)
387            .append(true)
388            .open(path)?;
389        // One logical write while holding the interprocess lock prevents JSON
390        // objects and their trailing newlines from interleaving.
391        file.write_all(&line)
392    })();
393
394    let _ = FileExt::unlock(&lock);
395    result
396}
397
398// --- Public API ---
399
400/// Persist a legacy event as a canonical local observation.
401///
402/// This compatibility adapter deliberately never appends to `events.jsonl`;
403/// that journal remains an immutable historical read source.
404///
405/// In a serving process (after [`enable_detached_observations`]) the write is
406/// handed to a dedicated writer thread: a tool handler never waits on the
407/// observation lock or SQLite (#2196), and when the bounded queue is full the
408/// observation is dropped and counted instead of blocking dispatch. Storage
409/// admission still runs here, on the producer's thread and policy view.
410pub fn emit_compatibility(kind: EventKind) -> u64 {
411    let result = if DETACHED_ENABLED.load(Ordering::Acquire) {
412        emit_detached(kind)
413    } else {
414        try_emit(kind)
415    };
416    match result {
417        Ok(id) => id,
418        Err(error) => {
419            log_persistence_failure(&error);
420            0
421        }
422    }
423}
424
425/// [`emit_compatibility`] that reports why persistence failed instead of
426/// collapsing the failure into id `0`. Always synchronous.
427pub(crate) fn try_emit(
428    kind: EventKind,
429) -> Result<u64, crate::core::context_os::ObservationPersistenceError> {
430    persist_admitted(&admit_observation(kind)?)
431}
432
433fn admit_observation(
434    kind: EventKind,
435) -> Result<
436    crate::core::context_os::AdmittedLegacyObservation,
437    crate::core::context_os::ObservationPersistenceError,
438> {
439    let event = LeanCtxEvent {
440        id: next_event_id(),
441        timestamp: lean_ctx_time::LocalDateTime::now()
442            .format("%Y-%m-%dT%H:%M:%S%.3f")
443            .to_string(),
444        kind,
445    };
446    crate::core::context_os::ContextBus::admit_legacy_observation(&event)
447}
448
449fn persist_admitted(
450    admitted: &crate::core::context_os::AdmittedLegacyObservation,
451) -> Result<u64, crate::core::context_os::ObservationPersistenceError> {
452    crate::core::context_os::try_runtime().and_then(|runtime| {
453        runtime.bus.append_admitted_legacy_observation(
454            crate::core::context_os::observation::producer_instance(),
455            admitted,
456        )
457    })?;
458    bus().record(admitted.event.clone());
459    Ok(admitted.event.id)
460}
461
462/// A withheld observation is the gateway working as configured, not a fault:
463/// at warn level it flooded the worker log (765 lines in 5 minutes, #2196).
464fn log_persistence_failure(error: &crate::core::context_os::ObservationPersistenceError) {
465    if matches!(
466        error,
467        crate::core::context_os::ObservationPersistenceError::Withheld
468    ) {
469        tracing::debug!("canonical legacy observation persistence skipped: {error}");
470    } else {
471        tracing::warn!("canonical legacy observation persistence failed: {error}");
472    }
473}
474
475// --- Detached persistence for serving processes (#2196) ---
476
477/// Observations a serving process may have waiting for the writer thread.
478const DETACHED_QUEUE_CAPACITY: usize = 4_096;
479
480static DETACHED_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
481static DETACHED_QUEUED: AtomicU64 = AtomicU64::new(0);
482static DETACHED_PERSISTED: AtomicU64 = AtomicU64::new(0);
483static DETACHED_FAILED: AtomicU64 = AtomicU64::new(0);
484static DETACHED_DROPPED: AtomicU64 = AtomicU64::new(0);
485
486enum DetachedMessage {
487    Persist(crate::core::context_os::AdmittedLegacyObservation),
488    Flush(std::sync::mpsc::SyncSender<()>),
489}
490
491/// Counters of the detached observation writer, for doctor and health.
492#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
493pub struct DetachedObservationStats {
494    pub enabled: bool,
495    pub queued: u64,
496    pub persisted: u64,
497    pub failed: u64,
498    pub dropped: u64,
499}
500
501pub fn detached_observation_stats() -> DetachedObservationStats {
502    DetachedObservationStats {
503        enabled: DETACHED_ENABLED.load(Ordering::Acquire),
504        queued: DETACHED_QUEUED.load(Ordering::Relaxed),
505        persisted: DETACHED_PERSISTED.load(Ordering::Relaxed),
506        failed: DETACHED_FAILED.load(Ordering::Relaxed),
507        dropped: DETACHED_DROPPED.load(Ordering::Relaxed),
508    }
509}
510
511/// Route [`emit_compatibility`] through the detached writer for the rest of
512/// this process. Called once by a serving process before it accepts requests;
513/// one-shot CLI commands keep synchronous persistence.
514pub fn enable_detached_observations() {
515    if detached_sender().is_some() {
516        DETACHED_ENABLED.store(true, Ordering::Release);
517    }
518}
519
520fn detached_sender() -> Option<&'static std::sync::mpsc::SyncSender<DetachedMessage>> {
521    static SENDER: OnceLock<Option<std::sync::mpsc::SyncSender<DetachedMessage>>> = OnceLock::new();
522    SENDER
523        .get_or_init(|| {
524            let (sender, receiver) =
525                std::sync::mpsc::sync_channel::<DetachedMessage>(DETACHED_QUEUE_CAPACITY);
526            std::thread::Builder::new()
527                .name("lean-ctx-observations".to_string())
528                .spawn(move || run_detached_writer(&receiver))
529                .map_err(|error| {
530                    tracing::warn!("detached observation writer unavailable: {error}");
531                })
532                .ok()
533                .map(|_| sender)
534        })
535        .as_ref()
536}
537
538fn run_detached_writer(receiver: &std::sync::mpsc::Receiver<DetachedMessage>) {
539    while let Ok(message) = receiver.recv() {
540        match message {
541            DetachedMessage::Persist(admitted) => {
542                // A panic in one write must not end the writer: the queue
543                // behind it would be lost and every later flush would wait
544                // for nothing.
545                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
546                    persist_with_retry(&admitted)
547                }));
548                match outcome {
549                    Ok(Ok(_)) => {
550                        DETACHED_PERSISTED.fetch_add(1, Ordering::Relaxed);
551                    }
552                    Ok(Err(error)) => {
553                        DETACHED_FAILED.fetch_add(1, Ordering::Relaxed);
554                        log_persistence_failure(&error);
555                    }
556                    Err(_) => {
557                        DETACHED_FAILED.fetch_add(1, Ordering::Relaxed);
558                        tracing::warn!("canonical legacy observation persistence panicked");
559                    }
560                }
561            }
562            DetachedMessage::Flush(done) => {
563                let _ = done.send(());
564            }
565        }
566    }
567}
568
569/// The writer thread may wait where a request may not: one lock timeout
570/// there (another process holding the store) is retried once after a short
571/// pause before the observation is counted as failed. Each attempt already
572/// waits the full lock bound, so more retries would only stall the queue.
573fn persist_with_retry(
574    admitted: &crate::core::context_os::AdmittedLegacyObservation,
575) -> Result<u64, crate::core::context_os::ObservationPersistenceError> {
576    match persist_admitted(admitted) {
577        Err(crate::core::context_os::ObservationPersistenceError::LockTimeout) => {
578            std::thread::sleep(std::time::Duration::from_millis(250));
579            persist_admitted(admitted)
580        }
581        result => result,
582    }
583}
584
585fn emit_detached(
586    kind: EventKind,
587) -> Result<u64, crate::core::context_os::ObservationPersistenceError> {
588    let admitted = admit_observation(kind)?;
589    let id = admitted.event.id;
590    let Some(sender) = detached_sender() else {
591        return persist_admitted(&admitted);
592    };
593    match sender.try_send(DetachedMessage::Persist(admitted)) {
594        Ok(()) => {
595            DETACHED_QUEUED.fetch_add(1, Ordering::Relaxed);
596            Ok(id)
597        }
598        Err(std::sync::mpsc::TrySendError::Full(_)) => {
599            // Dropping one observation is the price of never stalling a
600            // request on a saturated store; the counter keeps it visible.
601            let dropped = DETACHED_DROPPED.fetch_add(1, Ordering::Relaxed) + 1;
602            if dropped.is_power_of_two() {
603                tracing::warn!(
604                    "observation writer saturated; {dropped} observations dropped so far"
605                );
606            }
607            Ok(0)
608        }
609        Err(std::sync::mpsc::TrySendError::Disconnected(DetachedMessage::Persist(admitted))) => {
610            persist_admitted(&admitted)
611        }
612        Err(std::sync::mpsc::TrySendError::Disconnected(DetachedMessage::Flush(_))) => Ok(0),
613    }
614}
615
616/// Wait until every observation queued before this call is persisted, or
617/// `timeout` passes. Returns whether the queue drained. Used at shutdown so a
618/// serving process does not lose its last observations.
619pub fn flush_detached_observations(timeout: std::time::Duration) -> bool {
620    if !DETACHED_ENABLED.load(Ordering::Acquire) {
621        return true;
622    }
623    let Some(sender) = detached_sender() else {
624        return true;
625    };
626    let deadline = std::time::Instant::now() + timeout;
627    let (done, drained) = std::sync::mpsc::sync_channel(1);
628    let mut message = DetachedMessage::Flush(done);
629    loop {
630        match sender.try_send(message) {
631            Ok(()) => break,
632            Err(std::sync::mpsc::TrySendError::Full(returned)) => {
633                if std::time::Instant::now() >= deadline {
634                    return false;
635                }
636                message = returned;
637                std::thread::sleep(std::time::Duration::from_millis(5));
638            }
639            // The writer is gone: whatever it still held is lost.
640            Err(std::sync::mpsc::TrySendError::Disconnected(_)) => return false,
641        }
642    }
643    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
644    drained.recv_timeout(remaining).is_ok()
645}
646
647/// Backward-compatible spelling for the explicit legacy compatibility adapter.
648pub fn emit(kind: EventKind) -> u64 {
649    emit_compatibility(kind)
650}
651
652pub fn events_since(after_id: u64) -> Vec<LeanCtxEvent> {
653    bus().events_since(after_id)
654}
655
656pub fn latest_events(n: usize) -> Vec<LeanCtxEvent> {
657    bus().latest_events(n)
658}
659
660#[derive(Default)]
661struct FileEventCache {
662    path: Option<std::path::PathBuf>,
663    mtime: Option<std::time::SystemTime>,
664    len: u64,
665    events: Vec<LeanCtxEvent>,
666}
667
668fn load_historical_events(
669    path: &std::path::Path,
670) -> Result<Vec<LeanCtxEvent>, crate::core::context_os::ObservationPersistenceError> {
671    static CACHE: OnceLock<Mutex<FileEventCache>> = OnceLock::new();
672    let metadata = match std::fs::metadata(path) {
673        Ok(metadata) => metadata,
674        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
675        Err(error) => return Err(error.into()),
676    };
677    let (mtime, len) = (metadata.modified().ok(), metadata.len());
678    let cache = CACHE.get_or_init(|| Mutex::new(FileEventCache::default()));
679    let mut guard = crate::core::context_os::observation::lock_observation(cache)?;
680    let fresh = guard.path.as_deref() == Some(path) && guard.mtime == mtime && guard.len == len;
681    if !fresh {
682        let content = std::fs::read_to_string(path)?;
683        let events = content
684            .lines()
685            .filter(|line| !line.trim().is_empty() && !is_retired_event_record(line))
686            .map(serde_json::from_str)
687            .collect::<Result<Vec<_>, _>>()?;
688        // Replace the cache only after every nonempty record validates.
689        guard.events = events;
690        guard.path = Some(path.to_path_buf());
691        guard.mtime = mtime;
692        guard.len = len;
693    }
694    Ok(guard.events.clone())
695}
696
697/// Compatibility reader: an unavailable canonical store returns no events,
698/// never apparently current history. Use the fallible API to inspect the error.
699pub fn load_events_from_file(n: usize) -> Vec<LeanCtxEvent> {
700    match try_load_events_from_file(n) {
701        Ok(events) => events,
702        Err(error) => {
703            tracing::warn!("canonical event history unavailable: {error}");
704            Vec::new()
705        }
706    }
707}
708
709/// [`load_events_from_file`] for a surface that SHOWS events — paths, names,
710/// free text — to a host or a model, for a reader working in `project` (the
711/// project of the running request when `None`). Every event passes the
712/// serve-time rule of the observation store (`ObservationGate`): an event
713/// that names a file is shown only while that file is admitted now; one
714/// without a source on record follows the originless rule. Historical JSONL
715/// records and rows written before admission existed are asked the same way.
716/// Counts and timestamps need no gate: use [`load_events_from_file`].
717///
718/// With a reader project the whole call — the admission snapshot, every
719/// payload check and every source read — runs inside ONE pinned policy view
720/// of that project (`policy::runtime::with_project_source_view`): every read
721/// sees the same project policy and role, and the view compares both again
722/// when it ends. A view that cannot be opened, that is not the view of the
723/// reader's project, or that reports a change shows NOTHING for this call.
724/// A reader without a project has no view; only the originless rule applies.
725pub fn load_served_events(n: usize, project: Option<&std::path::Path>) -> Vec<LeanCtxEvent> {
726    use crate::core::context_os::observation::ObservationGate;
727
728    let request = crate::core::admitted_sources::request_root();
729    let reader = project
730        .map(|root| root.to_string_lossy().into_owned())
731        .or_else(|| (!request.is_empty()).then_some(request));
732    let Some(reader) = reader else {
733        return served_through(ObservationGate::for_project(None), n);
734    };
735    crate::core::policy::runtime::with_project_source_view(&reader, || {
736        // The view pins the project the request is already bound to, if any.
737        // The gate reads under that project; a reader that asked for another
738        // one is not served from it.
739        // Compared in the view's own spelling: it pins `Path::canonicalize`
740        // of the project (`policy::runtime::canonical_project_root`).
741        let pinned = crate::core::admitted_sources::request_root();
742        let same = std::path::Path::new(&reader)
743            .canonicalize()
744            .is_ok_and(|asked| asked == std::path::Path::new(&pinned));
745        if same {
746            served_through(ObservationGate::for_project(None), n)
747        } else {
748            Vec::new()
749        }
750    })
751    .unwrap_or_else(|error| {
752        tracing::debug!("[events] nothing shown: {error}");
753        Vec::new()
754    })
755}
756
757fn served_through(
758    mut gate: crate::core::context_os::observation::ObservationGate,
759    n: usize,
760) -> Vec<LeanCtxEvent> {
761    let mut events = load_events_from_file(n);
762    events.retain(|event| gate.serves(event));
763    // The view pins project policy and role, not the gateway rules: those are
764    // compared once more before anything is returned. Changed mid-call:
765    // nothing is shown.
766    if !gate.gateway_unchanged() {
767        tracing::debug!("[events] nothing shown: gateway rules changed during the call");
768        return Vec::new();
769    }
770    if gate.withheld() > 0 {
771        tracing::debug!(
772            "[events] {} observation(s) withheld: no current source authority",
773            gate.withheld()
774        );
775    }
776    events
777}
778
779/// Merge immutable historical JSONL with validated canonical observations.
780pub fn try_load_events_from_file(
781    n: usize,
782) -> Result<Vec<LeanCtxEvent>, crate::core::context_os::ObservationPersistenceError> {
783    let mut events = jsonl_path()
784        .map(|path| load_historical_events(&path))
785        .transpose()?
786        .unwrap_or_default();
787
788    let compatibility = crate::core::context_os::try_runtime()?
789        .bus
790        .read_legacy_observations(n.max(1))?;
791    events.extend(compatibility);
792    // Historical file order predates the canonical cursor. Block-allocated
793    // IDs from concurrent producers do not encode append order.
794    // Never discard distinct records just because historical/fallback IDs
795    // collide. The legacy projection omits producer identity, so even equal
796    // projected payloads cannot establish that two observations are duplicates.
797    let start = events.len().saturating_sub(n);
798    Ok(events[start..].to_vec())
799}
800
801pub fn emit_tool_call(
802    tool: &str,
803    tokens_original: u64,
804    tokens_saved: u64,
805    mode: Option<String>,
806    duration_ms: u64,
807    path: Option<String>,
808) {
809    emit(EventKind::ToolCall {
810        tool: tool.to_string(),
811        tokens_original,
812        tokens_saved,
813        mode,
814        duration_ms,
815        path,
816    });
817}
818
819pub fn emit_cache_hit(path: &str, saved_tokens: u64) {
820    emit(EventKind::CacheHit {
821        path: path.to_string(),
822        saved_tokens,
823    });
824}
825
826pub fn emit_agent_action(agent_id: &str, action: &str, tool: Option<&str>) {
827    emit(EventKind::AgentAction {
828        agent_id: agent_id.to_string(),
829        action: action.to_string(),
830        tool: tool.map(std::string::ToString::to_string),
831    });
832}
833
834pub fn emit_policy_violation(role: &str, tool: &str, reason: &str) {
835    emit(EventKind::PolicyViolation {
836        role: role.to_string(),
837        tool: tool.to_string(),
838        reason: reason.to_string(),
839    });
840}
841
842pub fn emit_role_changed(from: &str, to: &str) {
843    emit(EventKind::RoleChanged {
844        from: from.to_string(),
845        to: to.to_string(),
846    });
847}
848
849pub fn emit_profile_changed(from: &str, to: &str) {
850    emit(EventKind::ProfileChanged {
851        from: from.to_string(),
852        to: to.to_string(),
853    });
854}
855
856pub fn emit_verification_warning(warning_kind: &str, detail: &str, severity: &str) {
857    emit(EventKind::VerificationWarning {
858        warning_kind: warning_kind.to_string(),
859        detail: detail.to_string(),
860        severity: severity.to_string(),
861    });
862}
863
864pub fn emit_threshold_adapted(language: &str, arm: &str, old_threshold: f64, new_threshold: f64) {
865    emit(EventKind::ThresholdAdapted {
866        language: language.to_string(),
867        arm: arm.to_string(),
868        old_threshold,
869        new_threshold,
870    });
871}
872
873#[cfg(test)]
874mod tests {
875    use super::*;
876
877    /// Every parallel test in this process emits into one shared store, and
878    /// the write lock wait is bounded on purpose (fire-and-forget emitters).
879    /// On a loaded Windows runner that queue can exceed the bound, so only a
880    /// `LockTimeout` is retried; any other persistence failure still fails.
881    fn emit_persisted(kind: &EventKind) -> u64 {
882        use crate::core::context_os::ObservationPersistenceError;
883        // Five backoff attempts (~3 s) still lost the queue on a loaded
884        // windows-latest lib run (2026-10-07, 12k tests in parallel); bound
885        // the retry by wall clock instead.
886        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
887        let mut attempt = 0u32;
888        loop {
889            match try_emit(kind.clone()) {
890                Ok(id) => return id,
891                Err(ObservationPersistenceError::LockTimeout)
892                    if std::time::Instant::now() < deadline =>
893                {
894                    std::thread::sleep(std::time::Duration::from_millis(100 << attempt.min(4)));
895                    attempt += 1;
896                }
897                Err(ObservationPersistenceError::LockTimeout) => {
898                    panic!("canonical persistence: write lock still contended after 30 s");
899                }
900                Err(error) => panic!("canonical persistence: {error:?}"),
901            }
902        }
903    }
904
905    #[test]
906    fn emit_returns_positive_id() {
907        // Keep real persistence, without queueing behind the whole suite's emitters.
908        if crate::test_env::run_in_own_process("core::events::tests::emit_returns_positive_id", &[])
909        {
910            return;
911        }
912        let id = emit_persisted(&EventKind::ToolCall {
913            tool: "ctx_read".to_string(),
914            tokens_original: 1000,
915            tokens_saved: 800,
916            mode: Some("map".to_string()),
917            duration_ms: 5,
918            path: Some("src/main.rs".to_string()),
919        });
920        assert!(id > 0);
921        let events = latest_events(100);
922        assert!(events.iter().any(|e| e.id == id));
923    }
924
925    /// #2196: a tool handler emitting an observation must not wait on the
926    /// observation writer. With the writer held (a long transaction or a
927    /// contended store), the synchronous path blocks for the full lock bound
928    /// and fails; a serving process returns at once and persists the
929    /// observation after the writer is released.
930    #[test]
931    fn serving_emit_does_not_wait_for_a_held_observation_lock() {
932        if crate::test_env::run_in_own_process(
933            "core::events::tests::serving_emit_does_not_wait_for_a_held_observation_lock",
934            &[],
935        ) {
936            return;
937        }
938        let kind = || EventKind::ToolCall {
939            tool: "ctx_read".to_string(),
940            tokens_original: 10,
941            tokens_saved: 5,
942            mode: Some("full".to_string()),
943            duration_ms: 1,
944            path: None,
945        };
946        let runtime = crate::core::context_os::try_runtime().expect("runtime");
947        let writer = runtime.bus.hold_observation_writer();
948
949        // The pre-#2196 dispatch path: the caller sleeps out the lock bound.
950        let started = std::time::Instant::now();
951        let blocked = try_emit(kind());
952        let synchronous_wait = started.elapsed();
953        assert!(
954            matches!(
955                blocked,
956                Err(crate::core::context_os::ObservationPersistenceError::LockTimeout)
957            ),
958            "synchronous emit with the writer held: {blocked:?}"
959        );
960        assert!(synchronous_wait >= std::time::Duration::from_secs(4));
961
962        enable_detached_observations();
963        let started = std::time::Instant::now();
964        let id = emit_compatibility(kind());
965        let detached_wait = started.elapsed();
966        assert!(id > 0, "the observation was admitted and queued");
967        assert!(
968            detached_wait < std::time::Duration::from_secs(1),
969            "dispatch waited {detached_wait:?} on a held observation lock"
970        );
971        assert!(!latest_events(1_000).iter().any(|e| e.id == id));
972
973        drop(writer);
974        assert!(flush_detached_observations(std::time::Duration::from_secs(
975            30
976        )));
977        assert!(latest_events(1_000).iter().any(|e| e.id == id));
978        let stats = detached_observation_stats();
979        assert_eq!((stats.queued, stats.persisted, stats.dropped), (1, 1, 0));
980    }
981
982    /// Project an event into the in-memory ring only. The filter tests are
983    /// about `events_since`, not persistence: routing them through the shared
984    /// SQLite observation store made them queue behind every other emitting
985    /// test, and on windows-latest that queue outlasted even a 30 s retry.
986    fn record_in_ring(kind: EventKind) -> u64 {
987        let id = next_event_id();
988        bus().record(LeanCtxEvent {
989            id,
990            timestamp: lean_ctx_time::LocalDateTime::now()
991                .format("%Y-%m-%dT%H:%M:%S%.3f")
992                .to_string(),
993            kind,
994        });
995        id
996    }
997
998    #[test]
999    fn events_since_filters_correctly() {
1000        let id1 = record_in_ring(EventKind::CacheHit {
1001            path: "filter_test_a.rs".to_string(),
1002            saved_tokens: 100,
1003        });
1004        let id2 = record_in_ring(EventKind::CacheHit {
1005            path: "filter_test_b.rs".to_string(),
1006            saved_tokens: 200,
1007        });
1008
1009        let after = events_since(id1);
1010        assert!(after.iter().any(|e| e.id == id2));
1011        assert!(after.iter().all(|e| e.id > id1));
1012    }
1013
1014    #[test]
1015    fn fallback_ids_stay_unique_and_increasing_when_the_clock_steps_back() {
1016        let last = AtomicU64::new(0);
1017        let first = fallback_event_id(&last, 1_000);
1018        let same_ms = fallback_event_id(&last, 1_000);
1019        let stepped_back = fallback_event_id(&last, 990);
1020        let later = fallback_event_id(&last, 2_000);
1021        assert_eq!(first, 1_000_000);
1022        assert!(same_ms > first);
1023        assert!(
1024            stepped_back > same_ms,
1025            "a backwards clock step must not reuse or reorder ids"
1026        );
1027        assert_eq!(later, 2_000_000);
1028    }
1029
1030    /// The (path, mtime, len) cache must never serve stale events: appending a
1031    /// line changes the file length, which has nanosecond-independent
1032    /// granularity (unlike mtime), so new events show up on the next poll.
1033    /// An isolated journal keeps unrelated canonical emissions from evicting
1034    /// these historical fixtures from the merged public reader's result window.
1035    #[test]
1036    fn load_events_from_file_sees_appended_events() {
1037        let directory = tempfile::tempdir().expect("isolated historical journal");
1038        let path = directory.path().join("events.jsonl");
1039
1040        let line_a = r#"{"id":900001,"timestamp":"2026-06-12T08:00:00.000","kind":{"type":"CacheHit","path":"cached_a.rs","saved_tokens":42}}"#;
1041        std::fs::write(&path, format!("{line_a}\n")).expect("write events.jsonl");
1042
1043        let first = load_historical_events(&path).expect("read initial historical events");
1044        assert!(
1045            first.iter().any(|e| e.id == 900_001),
1046            "initial load should parse the seeded event"
1047        );
1048
1049        // Second call with unchanged file exercises the cached branch.
1050        let cached = load_historical_events(&path).expect("read cached historical events");
1051        assert_eq!(cached.len(), first.len());
1052
1053        let line_b = r#"{"id":900002,"timestamp":"2026-06-12T08:00:01.000","kind":{"type":"CacheHit","path":"cached_b.rs","saved_tokens":7}}"#;
1054        {
1055            use std::io::Write;
1056            let mut f = std::fs::OpenOptions::new()
1057                .append(true)
1058                .open(&path)
1059                .expect("append events.jsonl");
1060            writeln!(f, "{line_b}").expect("append line");
1061        }
1062
1063        let second = load_historical_events(&path).expect("read appended historical events");
1064        assert!(
1065            second.iter().any(|e| e.id == 900_002),
1066            "append must invalidate the cache and surface the new event"
1067        );
1068    }
1069
1070    #[test]
1071    fn events_jsonl_writer_child() {
1072        let Some(path) = std::env::var_os("__LEAN_CTX_EVENTS_TEST_PATH") else {
1073            return;
1074        };
1075        let writer = std::env::var("__LEAN_CTX_EVENTS_TEST_WRITER")
1076            .expect("writer id")
1077            .parse::<u64>()
1078            .expect("numeric writer id");
1079        for sequence in 0..100 {
1080            let event = LeanCtxEvent {
1081                id: writer * 100 + sequence,
1082                timestamp: "2026-07-15T12:00:00.000".to_string(),
1083                kind: EventKind::CacheHit {
1084                    path: format!("writer-{writer}.rs"),
1085                    saved_tokens: sequence,
1086                },
1087            };
1088            append_jsonl_at(std::path::Path::new(&path), &event).expect("append event");
1089        }
1090    }
1091
1092    fn test_event(id: u64) -> LeanCtxEvent {
1093        LeanCtxEvent {
1094            id,
1095            timestamp: "2026-07-15T12:00:00.000".to_string(),
1096            kind: EventKind::CacheHit {
1097                path: "event-id-test.rs".to_string(),
1098                saved_tokens: 1,
1099            },
1100        }
1101    }
1102
1103    #[test]
1104    fn retired_event_kinds_are_skipped_and_still_reserve_ids() {
1105        let dir = tempfile::tempdir().expect("temp dir");
1106        let journal = dir.path().join("events.jsonl");
1107        let retired = r#"{"id":90,"timestamp":"2026-07-15T12:00:00.000","kind":{"type":"BudgetWarning","role":"coder","dimension":"tokens","used":"1","limit":"2","percent":50}}"#;
1108        assert!(is_retired_event_record(retired));
1109        let current = serde_json::to_string(&test_event(42)).unwrap();
1110        assert!(!is_retired_event_record(&current));
1111        std::fs::write(&journal, format!("{current}\n{retired}\n")).unwrap();
1112
1113        let events = load_historical_events(&journal).expect("retired kinds must not fail reads");
1114        assert_eq!(events, vec![test_event(42)]);
1115        assert_eq!(max_event_id_in_journal(&journal), 90);
1116    }
1117
1118    #[test]
1119    fn concurrent_processes_append_complete_json_lines() {
1120        let dir = tempfile::tempdir().expect("temp dir");
1121        let path = dir.path().join("events.jsonl");
1122        let executable = std::env::current_exe().expect("test executable");
1123
1124        let mut children = Vec::new();
1125        for writer in 0..4 {
1126            children.push(
1127                std::process::Command::new(&executable)
1128                    .args([
1129                        "--exact",
1130                        "core::events::tests::events_jsonl_writer_child",
1131                        "--nocapture",
1132                    ])
1133                    .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
1134                    .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
1135                    .spawn()
1136                    .expect("spawn writer"),
1137            );
1138        }
1139        for mut child in children {
1140            assert!(child.wait().expect("wait for writer").success());
1141        }
1142
1143        let content = std::fs::read_to_string(&path).expect("read events");
1144        let lines: Vec<_> = content.lines().collect();
1145        assert_eq!(lines.len(), 400, "every append must produce one line");
1146        for line in lines {
1147            serde_json::from_str::<LeanCtxEvent>(line)
1148                .unwrap_or_else(|error| panic!("invalid JSONL line: {error}: {line}"));
1149        }
1150    }
1151
1152    #[test]
1153    fn concurrent_processes_serialize_rotation_and_append() {
1154        let dir = tempfile::tempdir().expect("temp dir");
1155        let path = dir.path().join("events.jsonl");
1156        let seed = serde_json::to_string(&LeanCtxEvent {
1157            id: 1,
1158            timestamp: "2026-07-15T12:00:00.000".to_string(),
1159            kind: EventKind::CacheHit {
1160                path: "seed.rs".to_string(),
1161                saved_tokens: 1,
1162            },
1163        })
1164        .expect("serialize seed");
1165        std::fs::write(&path, format!("{seed}\n").repeat(JSONL_MAX_LINES))
1166            .expect("seed rotation threshold");
1167
1168        let executable = std::env::current_exe().expect("test executable");
1169        let mut children = Vec::new();
1170        for writer in 0..4 {
1171            children.push(
1172                std::process::Command::new(&executable)
1173                    .args(["--exact", "core::events::tests::events_jsonl_writer_child"])
1174                    .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
1175                    .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
1176                    .spawn()
1177                    .expect("spawn writer"),
1178            );
1179        }
1180        for mut child in children {
1181            assert!(child.wait().expect("wait for writer").success());
1182        }
1183
1184        let old =
1185            std::fs::read_to_string(path.with_extension("jsonl.old")).expect("rotated journal");
1186        assert_eq!(old.lines().count(), JSONL_MAX_LINES);
1187        assert!(
1188            old.lines()
1189                .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
1190            "rotated journal must contain complete JSON lines"
1191        );
1192
1193        let current = std::fs::read_to_string(&path).expect("current journal");
1194        assert_eq!(current.lines().count(), 400);
1195        assert!(
1196            current
1197                .lines()
1198                .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
1199            "replacement journal must contain complete JSON lines"
1200        );
1201    }
1202
1203    #[test]
1204    fn persistent_event_id_writer_child() {
1205        let Some(dir) = std::env::var_os("__LEAN_CTX_EVENT_ID_TEST_DIR") else {
1206            return;
1207        };
1208        let writer = std::env::var("__LEAN_CTX_EVENT_ID_TEST_WRITER").expect("writer id");
1209        let dir = std::path::PathBuf::from(dir);
1210        let sequence = dir.join("events.seq");
1211        let journal = dir.join("events.jsonl");
1212        let (first, last) =
1213            reserve_event_id_block_at(&sequence, &journal, 100).expect("reserve event id block");
1214        let ids: Vec<String> = (first..=last).map(|id| id.to_string()).collect();
1215        std::fs::write(dir.join(format!("writer-{writer}.ids")), ids.join("\n"))
1216            .expect("write allocated ids");
1217    }
1218
1219    #[test]
1220    fn persistent_event_id_bootstraps_above_existing_journals() {
1221        let dir = tempfile::tempdir().expect("temp dir");
1222        let sequence = dir.path().join("events.seq");
1223        let journal = dir.path().join("events.jsonl");
1224        let old = journal.with_extension("jsonl.old");
1225        std::fs::write(
1226            &journal,
1227            format!("{}\n", serde_json::to_string(&test_event(41)).unwrap()),
1228        )
1229        .unwrap();
1230        std::fs::write(
1231            &old,
1232            format!("{}\n", serde_json::to_string(&test_event(73)).unwrap()),
1233        )
1234        .unwrap();
1235
1236        assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 74);
1237        assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 75);
1238    }
1239
1240    #[test]
1241    fn corrupt_sequence_recovers_above_existing_journal() {
1242        let dir = tempfile::tempdir().expect("temp dir");
1243        let sequence = dir.path().join("events.seq");
1244        let journal = dir.path().join("events.jsonl");
1245        std::fs::write(&sequence, "76:broken").unwrap();
1246        std::fs::write(
1247            &journal,
1248            format!("{}\n", serde_json::to_string(&test_event(80)).unwrap()),
1249        )
1250        .unwrap();
1251
1252        assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 81);
1253        assert_eq!(read_persisted_sequence(&sequence), Some(81));
1254    }
1255
1256    #[test]
1257    fn concurrent_processes_allocate_unique_event_ids() {
1258        let dir = tempfile::tempdir().expect("temp dir");
1259        let executable = std::env::current_exe().expect("test executable");
1260        let mut children = Vec::new();
1261        for writer in 0..4 {
1262            children.push(
1263                std::process::Command::new(&executable)
1264                    .args([
1265                        "--exact",
1266                        "core::events::tests::persistent_event_id_writer_child",
1267                    ])
1268                    .env("__LEAN_CTX_EVENT_ID_TEST_DIR", dir.path())
1269                    .env("__LEAN_CTX_EVENT_ID_TEST_WRITER", writer.to_string())
1270                    .spawn()
1271                    .expect("spawn event id writer"),
1272            );
1273        }
1274        for mut child in children {
1275            assert!(child.wait().expect("wait for event id writer").success());
1276        }
1277
1278        let mut ids = Vec::new();
1279        for writer in 0..4 {
1280            let content = std::fs::read_to_string(dir.path().join(format!("writer-{writer}.ids")))
1281                .expect("read allocated ids");
1282            ids.extend(content.lines().map(|line| line.parse::<u64>().unwrap()));
1283        }
1284        ids.sort_unstable();
1285        ids.dedup();
1286        assert_eq!(ids.len(), 400, "every process must receive unique ids");
1287        assert_eq!(ids.first(), Some(&1));
1288        assert_eq!(ids.last(), Some(&400));
1289        let sequence_path = dir.path().join("events.seq");
1290        assert_eq!(read_persisted_sequence(&sequence_path), Some(400));
1291        assert_eq!(
1292            std::fs::read_to_string(sequence_path)
1293                .expect("read sequence journal")
1294                .lines()
1295                .count(),
1296            4,
1297            "four writers should persist four block reservations, not 400 ids"
1298        );
1299    }
1300}