1use 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 BudgetWarning {
62 role: String,
63 dimension: String,
64 used: String,
65 limit: String,
66 percent: u8,
67 },
68 BudgetExhausted {
69 role: String,
70 dimension: String,
71 used: String,
72 limit: String,
73 },
74 PolicyViolation {
75 role: String,
76 tool: String,
77 reason: String,
78 },
79 RoleChanged {
80 from: String,
81 to: String,
82 },
83 ProfileChanged {
84 from: String,
85 to: String,
86 },
87 SloViolation {
88 slo_name: String,
89 metric: String,
90 threshold: f64,
91 actual: f64,
92 action: String,
93 },
94 Anomaly {
95 metric: String,
96 expected: f64,
97 actual: f64,
98 deviation_factor: f64,
99 },
100 VerificationWarning {
101 warning_kind: String,
102 detail: String,
103 severity: String,
104 },
105 ThresholdAdapted {
106 language: String,
107 arm: String,
108 old_threshold: f64,
109 new_threshold: f64,
110 },
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
174fn max_event_id_in_journal(path: &std::path::Path) -> u64 {
175 let Ok(content) = std::fs::read_to_string(path) else {
176 return 0;
177 };
178 content
179 .lines()
180 .filter_map(|line| serde_json::from_str::<LeanCtxEvent>(line).ok())
181 .map(|event| event.id)
182 .max()
183 .unwrap_or(0)
184}
185
186fn parse_sequence_record(record: &str) -> Option<u64> {
187 let (value, checksum) = record.trim().split_once(':')?;
188 let value = value.parse::<u64>().ok()?;
189 let checksum = checksum.parse::<u64>().ok()?;
190 (checksum == !value).then_some(value)
191}
192
193fn read_persisted_sequence(path: &std::path::Path) -> Option<u64> {
194 let content = std::fs::read_to_string(path).ok()?;
195 content.lines().rev().find_map(parse_sequence_record)
196}
197
198fn sequence_record(value: u64) -> String {
199 format!("{value}:{}", !value)
200}
201
202fn reserve_event_id_block_at(
203 sequence_path: &std::path::Path,
204 journal_path: &std::path::Path,
205 block_size: u64,
206) -> std::io::Result<(u64, u64)> {
207 use fs2::FileExt;
208
209 if block_size == 0 {
210 return Err(std::io::Error::other("event id block must not be empty"));
211 }
212 if let Some(parent) = sequence_path.parent() {
213 std::fs::create_dir_all(parent)?;
214 }
215 let lock_path = sequence_path.with_extension("seq.lock");
218 let lock = std::fs::OpenOptions::new()
219 .create(true)
220 .truncate(false)
221 .read(true)
222 .write(true)
223 .open(lock_path)?;
224 lock.lock_exclusive()?;
225
226 let result = (|| {
227 let persisted = read_persisted_sequence(sequence_path);
228 let baseline = persisted.unwrap_or_else(|| {
229 max_event_id_in_journal(journal_path).max(max_event_id_in_journal(
230 &journal_path.with_extension("jsonl.old"),
231 ))
232 });
233 let first = baseline
234 .checked_add(1)
235 .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
236 let last = baseline
237 .checked_add(block_size)
238 .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
239
240 let needs_leading_newline = std::fs::read(sequence_path)
244 .is_ok_and(|bytes| !bytes.is_empty() && bytes.last() != Some(&b'\n'));
245
246 let mut sequence = std::fs::OpenOptions::new()
247 .create(true)
248 .append(true)
249 .open(sequence_path)?;
250 let mut record = Vec::new();
251 if needs_leading_newline {
252 record.push(b'\n');
253 }
254 record.extend_from_slice(sequence_record(last).as_bytes());
255 record.push(b'\n');
256 sequence.write_all(&record)?;
257 sequence.sync_data()?;
258 Ok((first, last))
259 })();
260
261 let _ = FileExt::unlock(&lock);
262 result
263}
264
265#[cfg(test)]
266fn next_event_id_at(
267 sequence_path: &std::path::Path,
268 journal_path: &std::path::Path,
269) -> std::io::Result<u64> {
270 reserve_event_id_block_at(sequence_path, journal_path, 1).map(|(first, _)| first)
271}
272
273fn next_event_id() -> u64 {
274 #[derive(Default)]
275 struct LocalBlock {
276 next: u64,
277 last: u64,
278 }
279
280 static BLOCK: OnceLock<Mutex<LocalBlock>> = OnceLock::new();
281 static FALLBACK: AtomicU64 = AtomicU64::new(0);
282 if !is_test_environment()
283 && let Some((sequence, journal)) = event_sequence_path().zip(jsonl_path())
284 {
285 let mut block = BLOCK
286 .get_or_init(|| Mutex::new(LocalBlock::default()))
287 .lock()
288 .unwrap_or_else(std::sync::PoisonError::into_inner);
289 if block.next <= block.last && block.next != 0 {
290 let id = block.next;
291 block.next = block.next.saturating_add(1);
292 return id;
293 }
294 if let Ok((first, last)) =
295 reserve_event_id_block_at(&sequence, &journal, EVENT_ID_BLOCK_SIZE)
296 {
297 block.next = first.saturating_add(1);
298 block.last = last;
299 return first;
300 }
301 }
302
303 fallback_event_id(&FALLBACK, chrono::Utc::now().timestamp_millis())
304}
305
306fn fallback_event_id(last: &AtomicU64, now_millis: i64) -> u64 {
312 let now = u64::try_from(now_millis)
313 .unwrap_or_default()
314 .saturating_mul(1_000);
315 let mut current = last.load(Ordering::Relaxed);
316 loop {
317 let next = now.max(current.saturating_add(1));
318 match last.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
319 Ok(_) => return next,
320 Err(observed) => current = observed,
321 }
322 }
323}
324
325fn is_test_environment() -> bool {
326 use std::sync::OnceLock;
327 static CACHED: OnceLock<bool> = OnceLock::new();
328 *CACHED.get_or_init(|| {
329 if cfg!(test) {
330 return true;
331 }
332 if std::env::var_os("__LEAN_CTX_SKIP_EVENTS").is_some() {
333 return true;
334 }
335 std::env::current_exe().is_ok_and(|p| {
336 let s = p.to_string_lossy();
337 s.contains("/deps/") || s.contains("\\deps\\")
338 })
339 })
340}
341
342#[cfg(test)]
343fn append_jsonl_at(path: &std::path::Path, event: &LeanCtxEvent) -> std::io::Result<()> {
344 use fs2::FileExt;
345 use std::io::Write;
346
347 if let Some(parent) = path.parent() {
348 std::fs::create_dir_all(parent)?;
349 }
350
351 let lock_path = path.with_extension("jsonl.lock");
355 let lock = std::fs::OpenOptions::new()
356 .create(true)
357 .truncate(false)
358 .read(true)
359 .write(true)
360 .open(lock_path)?;
361 lock.lock_exclusive()?;
362
363 let result = (|| {
364 if let Ok(content) = std::fs::read_to_string(path)
365 && content.lines().count() >= JSONL_MAX_LINES
366 {
367 let old = path.with_extension("jsonl.old");
368 let _ = std::fs::remove_file(&old);
369 std::fs::rename(path, old)?;
370 }
371
372 let json = serde_json::to_string(event).map_err(std::io::Error::other)?;
373 let mut line = json.into_bytes();
374 line.push(b'\n');
375 let mut file = std::fs::OpenOptions::new()
376 .create(true)
377 .append(true)
378 .open(path)?;
379 file.write_all(&line)
382 })();
383
384 let _ = FileExt::unlock(&lock);
385 result
386}
387
388pub fn emit_compatibility(kind: EventKind) -> u64 {
395 match try_emit(kind) {
396 Ok(id) => id,
397 Err(error) => {
398 tracing::warn!("canonical legacy observation persistence failed: {error}");
399 0
400 }
401 }
402}
403
404pub(crate) fn try_emit(
407 kind: EventKind,
408) -> Result<u64, crate::core::context_os::ObservationPersistenceError> {
409 let id = next_event_id();
410 let event = LeanCtxEvent {
411 id,
412 timestamp: chrono::Local::now()
413 .format("%Y-%m-%dT%H:%M:%S%.3f")
414 .to_string(),
415 kind,
416 };
417 crate::core::context_os::try_runtime().and_then(|runtime| {
418 runtime.bus.append_legacy_observation(
419 crate::core::context_os::observation::producer_instance(),
420 &event,
421 )
422 })?;
423 bus().record(event);
424 Ok(id)
425}
426
427pub fn emit(kind: EventKind) -> u64 {
429 emit_compatibility(kind)
430}
431
432pub fn events_since(after_id: u64) -> Vec<LeanCtxEvent> {
433 bus().events_since(after_id)
434}
435
436pub fn latest_events(n: usize) -> Vec<LeanCtxEvent> {
437 bus().latest_events(n)
438}
439
440#[derive(Default)]
441struct FileEventCache {
442 path: Option<std::path::PathBuf>,
443 mtime: Option<std::time::SystemTime>,
444 len: u64,
445 events: Vec<LeanCtxEvent>,
446}
447
448fn load_historical_events(
449 path: &std::path::Path,
450) -> Result<Vec<LeanCtxEvent>, crate::core::context_os::ObservationPersistenceError> {
451 static CACHE: OnceLock<Mutex<FileEventCache>> = OnceLock::new();
452 let metadata = match std::fs::metadata(path) {
453 Ok(metadata) => metadata,
454 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
455 Err(error) => return Err(error.into()),
456 };
457 let (mtime, len) = (metadata.modified().ok(), metadata.len());
458 let cache = CACHE.get_or_init(|| Mutex::new(FileEventCache::default()));
459 let mut guard = crate::core::context_os::observation::lock_observation(cache)?;
460 let fresh = guard.path.as_deref() == Some(path) && guard.mtime == mtime && guard.len == len;
461 if !fresh {
462 let content = std::fs::read_to_string(path)?;
463 let events = content
464 .lines()
465 .filter(|line| !line.trim().is_empty())
466 .map(serde_json::from_str)
467 .collect::<Result<Vec<_>, _>>()?;
468 guard.events = events;
470 guard.path = Some(path.to_path_buf());
471 guard.mtime = mtime;
472 guard.len = len;
473 }
474 Ok(guard.events.clone())
475}
476
477pub fn load_events_from_file(n: usize) -> Vec<LeanCtxEvent> {
480 match try_load_events_from_file(n) {
481 Ok(events) => events,
482 Err(error) => {
483 tracing::warn!("canonical event history unavailable: {error}");
484 Vec::new()
485 }
486 }
487}
488
489pub fn try_load_events_from_file(
491 n: usize,
492) -> Result<Vec<LeanCtxEvent>, crate::core::context_os::ObservationPersistenceError> {
493 let mut events = jsonl_path()
494 .map(|path| load_historical_events(&path))
495 .transpose()?
496 .unwrap_or_default();
497
498 let compatibility = crate::core::context_os::try_runtime()?
499 .bus
500 .read_legacy_observations(n.max(1))?;
501 events.extend(compatibility);
502 let start = events.len().saturating_sub(n);
508 Ok(events[start..].to_vec())
509}
510
511pub fn emit_tool_call(
512 tool: &str,
513 tokens_original: u64,
514 tokens_saved: u64,
515 mode: Option<String>,
516 duration_ms: u64,
517 path: Option<String>,
518) {
519 emit(EventKind::ToolCall {
520 tool: tool.to_string(),
521 tokens_original,
522 tokens_saved,
523 mode,
524 duration_ms,
525 path,
526 });
527}
528
529pub fn emit_cache_hit(path: &str, saved_tokens: u64) {
530 emit(EventKind::CacheHit {
531 path: path.to_string(),
532 saved_tokens,
533 });
534}
535
536pub fn emit_agent_action(agent_id: &str, action: &str, tool: Option<&str>) {
537 emit(EventKind::AgentAction {
538 agent_id: agent_id.to_string(),
539 action: action.to_string(),
540 tool: tool.map(std::string::ToString::to_string),
541 });
542}
543
544pub fn emit_budget_warning(role: &str, dimension: &str, used: &str, limit: &str, percent: u8) {
545 if !budget_warning_due(role, dimension, percent) {
551 return;
552 }
553 emit(EventKind::BudgetWarning {
554 role: role.to_string(),
555 dimension: dimension.to_string(),
556 used: used.to_string(),
557 limit: limit.to_string(),
558 percent,
559 });
560}
561
562fn budget_warning_due(role: &str, dimension: &str, percent: u8) -> bool {
566 use std::collections::HashMap;
567 use std::sync::Mutex;
568 use std::time::{Duration, Instant};
569
570 const REPEAT_AFTER: Duration = Duration::from_mins(5);
571
572 type WarnState = HashMap<(String, String), (u8, Instant)>;
573 static LAST: Mutex<Option<WarnState>> = Mutex::new(None);
574
575 let mut guard = LAST
576 .lock()
577 .unwrap_or_else(std::sync::PoisonError::into_inner);
578 let map = guard.get_or_insert_with(HashMap::new);
579 let key = (role.to_string(), dimension.to_string());
580 let bucket = percent / 10;
581 match map.get(&key) {
582 Some((last_bucket, at)) if *last_bucket == bucket && at.elapsed() < REPEAT_AFTER => false,
583 _ => {
584 map.insert(key, (bucket, Instant::now()));
585 true
586 }
587 }
588}
589
590pub fn emit_budget_exhausted(role: &str, dimension: &str, used: &str, limit: &str) {
591 emit(EventKind::BudgetExhausted {
592 role: role.to_string(),
593 dimension: dimension.to_string(),
594 used: used.to_string(),
595 limit: limit.to_string(),
596 });
597}
598
599pub fn emit_policy_violation(role: &str, tool: &str, reason: &str) {
600 emit(EventKind::PolicyViolation {
601 role: role.to_string(),
602 tool: tool.to_string(),
603 reason: reason.to_string(),
604 });
605}
606
607pub fn emit_role_changed(from: &str, to: &str) {
608 emit(EventKind::RoleChanged {
609 from: from.to_string(),
610 to: to.to_string(),
611 });
612}
613
614pub fn emit_profile_changed(from: &str, to: &str) {
615 emit(EventKind::ProfileChanged {
616 from: from.to_string(),
617 to: to.to_string(),
618 });
619}
620
621pub fn emit_slo_violation(slo_name: &str, metric: &str, threshold: f64, actual: f64, action: &str) {
622 emit(EventKind::SloViolation {
623 slo_name: slo_name.to_string(),
624 metric: metric.to_string(),
625 threshold,
626 actual,
627 action: action.to_string(),
628 });
629}
630
631pub fn emit_anomaly(metric: &str, expected: f64, actual: f64, deviation_factor: f64) {
632 emit(EventKind::Anomaly {
633 metric: metric.to_string(),
634 expected,
635 actual,
636 deviation_factor,
637 });
638}
639
640pub fn emit_verification_warning(warning_kind: &str, detail: &str, severity: &str) {
641 emit(EventKind::VerificationWarning {
642 warning_kind: warning_kind.to_string(),
643 detail: detail.to_string(),
644 severity: severity.to_string(),
645 });
646}
647
648pub fn emit_threshold_adapted(language: &str, arm: &str, old_threshold: f64, new_threshold: f64) {
649 emit(EventKind::ThresholdAdapted {
650 language: language.to_string(),
651 arm: arm.to_string(),
652 old_threshold,
653 new_threshold,
654 });
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660
661 fn emit_persisted(kind: &EventKind) -> u64 {
666 use crate::core::context_os::ObservationPersistenceError;
667 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
671 let mut attempt = 0u32;
672 loop {
673 match try_emit(kind.clone()) {
674 Ok(id) => return id,
675 Err(ObservationPersistenceError::LockTimeout)
676 if std::time::Instant::now() < deadline =>
677 {
678 std::thread::sleep(std::time::Duration::from_millis(100 << attempt.min(4)));
679 attempt += 1;
680 }
681 Err(ObservationPersistenceError::LockTimeout) => {
682 panic!("canonical persistence: write lock still contended after 30 s");
683 }
684 Err(error) => panic!("canonical persistence: {error:?}"),
685 }
686 }
687 }
688
689 #[test]
690 fn emit_returns_positive_id() {
691 let id = emit_persisted(&EventKind::ToolCall {
692 tool: "ctx_read".to_string(),
693 tokens_original: 1000,
694 tokens_saved: 800,
695 mode: Some("map".to_string()),
696 duration_ms: 5,
697 path: Some("src/main.rs".to_string()),
698 });
699 assert!(id > 0);
700 let events = latest_events(100);
701 assert!(events.iter().any(|e| e.id == id));
702 }
703
704 #[test]
708 fn budget_warning_rate_limit_suppresses_repeats() {
709 let role = format!("test-role-{}", std::process::id());
710 assert!(budget_warning_due(&role, "tokens", 85));
711 assert!(!budget_warning_due(&role, "tokens", 85));
712 assert!(!budget_warning_due(&role, "tokens", 87)); assert!(budget_warning_due(&role, "tokens", 95)); assert!(!budget_warning_due(&role, "tokens", 95));
715 assert!(budget_warning_due(&role, "cost", 85)); }
717
718 #[test]
719 fn events_since_filters_correctly() {
720 let id1 = emit_persisted(&EventKind::CacheHit {
721 path: "filter_test_a.rs".to_string(),
722 saved_tokens: 100,
723 });
724 let id2 = emit_persisted(&EventKind::CacheHit {
725 path: "filter_test_b.rs".to_string(),
726 saved_tokens: 200,
727 });
728
729 let after = events_since(id1);
730 assert!(after.iter().any(|e| e.id == id2));
731 assert!(after.iter().all(|e| e.id > id1));
732 }
733
734 #[test]
735 fn fallback_ids_stay_unique_and_increasing_when_the_clock_steps_back() {
736 let last = AtomicU64::new(0);
737 let first = fallback_event_id(&last, 1_000);
738 let same_ms = fallback_event_id(&last, 1_000);
739 let stepped_back = fallback_event_id(&last, 990);
740 let later = fallback_event_id(&last, 2_000);
741 assert_eq!(first, 1_000_000);
742 assert!(same_ms > first);
743 assert!(
744 stepped_back > same_ms,
745 "a backwards clock step must not reuse or reorder ids"
746 );
747 assert_eq!(later, 2_000_000);
748 }
749
750 #[test]
756 fn load_events_from_file_sees_appended_events() {
757 let directory = tempfile::tempdir().expect("isolated historical journal");
758 let path = directory.path().join("events.jsonl");
759
760 let line_a = r#"{"id":900001,"timestamp":"2026-06-12T08:00:00.000","kind":{"type":"CacheHit","path":"cached_a.rs","saved_tokens":42}}"#;
761 std::fs::write(&path, format!("{line_a}\n")).expect("write events.jsonl");
762
763 let first = load_historical_events(&path).expect("read initial historical events");
764 assert!(
765 first.iter().any(|e| e.id == 900_001),
766 "initial load should parse the seeded event"
767 );
768
769 let cached = load_historical_events(&path).expect("read cached historical events");
771 assert_eq!(cached.len(), first.len());
772
773 let line_b = r#"{"id":900002,"timestamp":"2026-06-12T08:00:01.000","kind":{"type":"CacheHit","path":"cached_b.rs","saved_tokens":7}}"#;
774 {
775 use std::io::Write;
776 let mut f = std::fs::OpenOptions::new()
777 .append(true)
778 .open(&path)
779 .expect("append events.jsonl");
780 writeln!(f, "{line_b}").expect("append line");
781 }
782
783 let second = load_historical_events(&path).expect("read appended historical events");
784 assert!(
785 second.iter().any(|e| e.id == 900_002),
786 "append must invalidate the cache and surface the new event"
787 );
788 }
789
790 #[test]
791 fn events_jsonl_writer_child() {
792 let Some(path) = std::env::var_os("__LEAN_CTX_EVENTS_TEST_PATH") else {
793 return;
794 };
795 let writer = std::env::var("__LEAN_CTX_EVENTS_TEST_WRITER")
796 .expect("writer id")
797 .parse::<u64>()
798 .expect("numeric writer id");
799 for sequence in 0..100 {
800 let event = LeanCtxEvent {
801 id: writer * 100 + sequence,
802 timestamp: "2026-07-15T12:00:00.000".to_string(),
803 kind: EventKind::CacheHit {
804 path: format!("writer-{writer}.rs"),
805 saved_tokens: sequence,
806 },
807 };
808 append_jsonl_at(std::path::Path::new(&path), &event).expect("append event");
809 }
810 }
811
812 fn test_event(id: u64) -> LeanCtxEvent {
813 LeanCtxEvent {
814 id,
815 timestamp: "2026-07-15T12:00:00.000".to_string(),
816 kind: EventKind::CacheHit {
817 path: "event-id-test.rs".to_string(),
818 saved_tokens: 1,
819 },
820 }
821 }
822
823 #[test]
824 fn concurrent_processes_append_complete_json_lines() {
825 let dir = tempfile::tempdir().expect("temp dir");
826 let path = dir.path().join("events.jsonl");
827 let executable = std::env::current_exe().expect("test executable");
828
829 let mut children = Vec::new();
830 for writer in 0..4 {
831 children.push(
832 std::process::Command::new(&executable)
833 .args([
834 "--exact",
835 "core::events::tests::events_jsonl_writer_child",
836 "--nocapture",
837 ])
838 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
839 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
840 .spawn()
841 .expect("spawn writer"),
842 );
843 }
844 for mut child in children {
845 assert!(child.wait().expect("wait for writer").success());
846 }
847
848 let content = std::fs::read_to_string(&path).expect("read events");
849 let lines: Vec<_> = content.lines().collect();
850 assert_eq!(lines.len(), 400, "every append must produce one line");
851 for line in lines {
852 serde_json::from_str::<LeanCtxEvent>(line)
853 .unwrap_or_else(|error| panic!("invalid JSONL line: {error}: {line}"));
854 }
855 }
856
857 #[test]
858 fn concurrent_processes_serialize_rotation_and_append() {
859 let dir = tempfile::tempdir().expect("temp dir");
860 let path = dir.path().join("events.jsonl");
861 let seed = serde_json::to_string(&LeanCtxEvent {
862 id: 1,
863 timestamp: "2026-07-15T12:00:00.000".to_string(),
864 kind: EventKind::CacheHit {
865 path: "seed.rs".to_string(),
866 saved_tokens: 1,
867 },
868 })
869 .expect("serialize seed");
870 std::fs::write(&path, format!("{seed}\n").repeat(JSONL_MAX_LINES))
871 .expect("seed rotation threshold");
872
873 let executable = std::env::current_exe().expect("test executable");
874 let mut children = Vec::new();
875 for writer in 0..4 {
876 children.push(
877 std::process::Command::new(&executable)
878 .args(["--exact", "core::events::tests::events_jsonl_writer_child"])
879 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
880 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
881 .spawn()
882 .expect("spawn writer"),
883 );
884 }
885 for mut child in children {
886 assert!(child.wait().expect("wait for writer").success());
887 }
888
889 let old =
890 std::fs::read_to_string(path.with_extension("jsonl.old")).expect("rotated journal");
891 assert_eq!(old.lines().count(), JSONL_MAX_LINES);
892 assert!(
893 old.lines()
894 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
895 "rotated journal must contain complete JSON lines"
896 );
897
898 let current = std::fs::read_to_string(&path).expect("current journal");
899 assert_eq!(current.lines().count(), 400);
900 assert!(
901 current
902 .lines()
903 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
904 "replacement journal must contain complete JSON lines"
905 );
906 }
907
908 #[test]
909 fn persistent_event_id_writer_child() {
910 let Some(dir) = std::env::var_os("__LEAN_CTX_EVENT_ID_TEST_DIR") else {
911 return;
912 };
913 let writer = std::env::var("__LEAN_CTX_EVENT_ID_TEST_WRITER").expect("writer id");
914 let dir = std::path::PathBuf::from(dir);
915 let sequence = dir.join("events.seq");
916 let journal = dir.join("events.jsonl");
917 let (first, last) =
918 reserve_event_id_block_at(&sequence, &journal, 100).expect("reserve event id block");
919 let ids: Vec<String> = (first..=last).map(|id| id.to_string()).collect();
920 std::fs::write(dir.join(format!("writer-{writer}.ids")), ids.join("\n"))
921 .expect("write allocated ids");
922 }
923
924 #[test]
925 fn persistent_event_id_bootstraps_above_existing_journals() {
926 let dir = tempfile::tempdir().expect("temp dir");
927 let sequence = dir.path().join("events.seq");
928 let journal = dir.path().join("events.jsonl");
929 let old = journal.with_extension("jsonl.old");
930 std::fs::write(
931 &journal,
932 format!("{}\n", serde_json::to_string(&test_event(41)).unwrap()),
933 )
934 .unwrap();
935 std::fs::write(
936 &old,
937 format!("{}\n", serde_json::to_string(&test_event(73)).unwrap()),
938 )
939 .unwrap();
940
941 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 74);
942 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 75);
943 }
944
945 #[test]
946 fn corrupt_sequence_recovers_above_existing_journal() {
947 let dir = tempfile::tempdir().expect("temp dir");
948 let sequence = dir.path().join("events.seq");
949 let journal = dir.path().join("events.jsonl");
950 std::fs::write(&sequence, "76:broken").unwrap();
951 std::fs::write(
952 &journal,
953 format!("{}\n", serde_json::to_string(&test_event(80)).unwrap()),
954 )
955 .unwrap();
956
957 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 81);
958 assert_eq!(read_persisted_sequence(&sequence), Some(81));
959 }
960
961 #[test]
962 fn concurrent_processes_allocate_unique_event_ids() {
963 let dir = tempfile::tempdir().expect("temp dir");
964 let executable = std::env::current_exe().expect("test executable");
965 let mut children = Vec::new();
966 for writer in 0..4 {
967 children.push(
968 std::process::Command::new(&executable)
969 .args([
970 "--exact",
971 "core::events::tests::persistent_event_id_writer_child",
972 ])
973 .env("__LEAN_CTX_EVENT_ID_TEST_DIR", dir.path())
974 .env("__LEAN_CTX_EVENT_ID_TEST_WRITER", writer.to_string())
975 .spawn()
976 .expect("spawn event id writer"),
977 );
978 }
979 for mut child in children {
980 assert!(child.wait().expect("wait for event id writer").success());
981 }
982
983 let mut ids = Vec::new();
984 for writer in 0..4 {
985 let content = std::fs::read_to_string(dir.path().join(format!("writer-{writer}.ids")))
986 .expect("read allocated ids");
987 ids.extend(content.lines().map(|line| line.parse::<u64>().unwrap()));
988 }
989 ids.sort_unstable();
990 ids.dedup();
991 assert_eq!(ids.len(), 400, "every process must receive unique ids");
992 assert_eq!(ids.first(), Some(&1));
993 assert_eq!(ids.last(), Some(&400));
994 let sequence_path = dir.path().join("events.seq");
995 assert_eq!(read_persisted_sequence(&sequence_path), Some(400));
996 assert_eq!(
997 std::fs::read_to_string(sequence_path)
998 .expect("read sequence journal")
999 .lines()
1000 .count(),
1001 4,
1002 "four writers should persist four block reservations, not 400 ids"
1003 );
1004 }
1005}