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 fn record_in_ring(kind: EventKind) -> u64 {
723 let id = next_event_id();
724 bus().record(LeanCtxEvent {
725 id,
726 timestamp: chrono::Local::now()
727 .format("%Y-%m-%dT%H:%M:%S%.3f")
728 .to_string(),
729 kind,
730 });
731 id
732 }
733
734 #[test]
735 fn events_since_filters_correctly() {
736 let id1 = record_in_ring(EventKind::CacheHit {
737 path: "filter_test_a.rs".to_string(),
738 saved_tokens: 100,
739 });
740 let id2 = record_in_ring(EventKind::CacheHit {
741 path: "filter_test_b.rs".to_string(),
742 saved_tokens: 200,
743 });
744
745 let after = events_since(id1);
746 assert!(after.iter().any(|e| e.id == id2));
747 assert!(after.iter().all(|e| e.id > id1));
748 }
749
750 #[test]
751 fn fallback_ids_stay_unique_and_increasing_when_the_clock_steps_back() {
752 let last = AtomicU64::new(0);
753 let first = fallback_event_id(&last, 1_000);
754 let same_ms = fallback_event_id(&last, 1_000);
755 let stepped_back = fallback_event_id(&last, 990);
756 let later = fallback_event_id(&last, 2_000);
757 assert_eq!(first, 1_000_000);
758 assert!(same_ms > first);
759 assert!(
760 stepped_back > same_ms,
761 "a backwards clock step must not reuse or reorder ids"
762 );
763 assert_eq!(later, 2_000_000);
764 }
765
766 #[test]
772 fn load_events_from_file_sees_appended_events() {
773 let directory = tempfile::tempdir().expect("isolated historical journal");
774 let path = directory.path().join("events.jsonl");
775
776 let line_a = r#"{"id":900001,"timestamp":"2026-06-12T08:00:00.000","kind":{"type":"CacheHit","path":"cached_a.rs","saved_tokens":42}}"#;
777 std::fs::write(&path, format!("{line_a}\n")).expect("write events.jsonl");
778
779 let first = load_historical_events(&path).expect("read initial historical events");
780 assert!(
781 first.iter().any(|e| e.id == 900_001),
782 "initial load should parse the seeded event"
783 );
784
785 let cached = load_historical_events(&path).expect("read cached historical events");
787 assert_eq!(cached.len(), first.len());
788
789 let line_b = r#"{"id":900002,"timestamp":"2026-06-12T08:00:01.000","kind":{"type":"CacheHit","path":"cached_b.rs","saved_tokens":7}}"#;
790 {
791 use std::io::Write;
792 let mut f = std::fs::OpenOptions::new()
793 .append(true)
794 .open(&path)
795 .expect("append events.jsonl");
796 writeln!(f, "{line_b}").expect("append line");
797 }
798
799 let second = load_historical_events(&path).expect("read appended historical events");
800 assert!(
801 second.iter().any(|e| e.id == 900_002),
802 "append must invalidate the cache and surface the new event"
803 );
804 }
805
806 #[test]
807 fn events_jsonl_writer_child() {
808 let Some(path) = std::env::var_os("__LEAN_CTX_EVENTS_TEST_PATH") else {
809 return;
810 };
811 let writer = std::env::var("__LEAN_CTX_EVENTS_TEST_WRITER")
812 .expect("writer id")
813 .parse::<u64>()
814 .expect("numeric writer id");
815 for sequence in 0..100 {
816 let event = LeanCtxEvent {
817 id: writer * 100 + sequence,
818 timestamp: "2026-07-15T12:00:00.000".to_string(),
819 kind: EventKind::CacheHit {
820 path: format!("writer-{writer}.rs"),
821 saved_tokens: sequence,
822 },
823 };
824 append_jsonl_at(std::path::Path::new(&path), &event).expect("append event");
825 }
826 }
827
828 fn test_event(id: u64) -> LeanCtxEvent {
829 LeanCtxEvent {
830 id,
831 timestamp: "2026-07-15T12:00:00.000".to_string(),
832 kind: EventKind::CacheHit {
833 path: "event-id-test.rs".to_string(),
834 saved_tokens: 1,
835 },
836 }
837 }
838
839 #[test]
840 fn concurrent_processes_append_complete_json_lines() {
841 let dir = tempfile::tempdir().expect("temp dir");
842 let path = dir.path().join("events.jsonl");
843 let executable = std::env::current_exe().expect("test executable");
844
845 let mut children = Vec::new();
846 for writer in 0..4 {
847 children.push(
848 std::process::Command::new(&executable)
849 .args([
850 "--exact",
851 "core::events::tests::events_jsonl_writer_child",
852 "--nocapture",
853 ])
854 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
855 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
856 .spawn()
857 .expect("spawn writer"),
858 );
859 }
860 for mut child in children {
861 assert!(child.wait().expect("wait for writer").success());
862 }
863
864 let content = std::fs::read_to_string(&path).expect("read events");
865 let lines: Vec<_> = content.lines().collect();
866 assert_eq!(lines.len(), 400, "every append must produce one line");
867 for line in lines {
868 serde_json::from_str::<LeanCtxEvent>(line)
869 .unwrap_or_else(|error| panic!("invalid JSONL line: {error}: {line}"));
870 }
871 }
872
873 #[test]
874 fn concurrent_processes_serialize_rotation_and_append() {
875 let dir = tempfile::tempdir().expect("temp dir");
876 let path = dir.path().join("events.jsonl");
877 let seed = serde_json::to_string(&LeanCtxEvent {
878 id: 1,
879 timestamp: "2026-07-15T12:00:00.000".to_string(),
880 kind: EventKind::CacheHit {
881 path: "seed.rs".to_string(),
882 saved_tokens: 1,
883 },
884 })
885 .expect("serialize seed");
886 std::fs::write(&path, format!("{seed}\n").repeat(JSONL_MAX_LINES))
887 .expect("seed rotation threshold");
888
889 let executable = std::env::current_exe().expect("test executable");
890 let mut children = Vec::new();
891 for writer in 0..4 {
892 children.push(
893 std::process::Command::new(&executable)
894 .args(["--exact", "core::events::tests::events_jsonl_writer_child"])
895 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
896 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
897 .spawn()
898 .expect("spawn writer"),
899 );
900 }
901 for mut child in children {
902 assert!(child.wait().expect("wait for writer").success());
903 }
904
905 let old =
906 std::fs::read_to_string(path.with_extension("jsonl.old")).expect("rotated journal");
907 assert_eq!(old.lines().count(), JSONL_MAX_LINES);
908 assert!(
909 old.lines()
910 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
911 "rotated journal must contain complete JSON lines"
912 );
913
914 let current = std::fs::read_to_string(&path).expect("current journal");
915 assert_eq!(current.lines().count(), 400);
916 assert!(
917 current
918 .lines()
919 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
920 "replacement journal must contain complete JSON lines"
921 );
922 }
923
924 #[test]
925 fn persistent_event_id_writer_child() {
926 let Some(dir) = std::env::var_os("__LEAN_CTX_EVENT_ID_TEST_DIR") else {
927 return;
928 };
929 let writer = std::env::var("__LEAN_CTX_EVENT_ID_TEST_WRITER").expect("writer id");
930 let dir = std::path::PathBuf::from(dir);
931 let sequence = dir.join("events.seq");
932 let journal = dir.join("events.jsonl");
933 let (first, last) =
934 reserve_event_id_block_at(&sequence, &journal, 100).expect("reserve event id block");
935 let ids: Vec<String> = (first..=last).map(|id| id.to_string()).collect();
936 std::fs::write(dir.join(format!("writer-{writer}.ids")), ids.join("\n"))
937 .expect("write allocated ids");
938 }
939
940 #[test]
941 fn persistent_event_id_bootstraps_above_existing_journals() {
942 let dir = tempfile::tempdir().expect("temp dir");
943 let sequence = dir.path().join("events.seq");
944 let journal = dir.path().join("events.jsonl");
945 let old = journal.with_extension("jsonl.old");
946 std::fs::write(
947 &journal,
948 format!("{}\n", serde_json::to_string(&test_event(41)).unwrap()),
949 )
950 .unwrap();
951 std::fs::write(
952 &old,
953 format!("{}\n", serde_json::to_string(&test_event(73)).unwrap()),
954 )
955 .unwrap();
956
957 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 74);
958 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 75);
959 }
960
961 #[test]
962 fn corrupt_sequence_recovers_above_existing_journal() {
963 let dir = tempfile::tempdir().expect("temp dir");
964 let sequence = dir.path().join("events.seq");
965 let journal = dir.path().join("events.jsonl");
966 std::fs::write(&sequence, "76:broken").unwrap();
967 std::fs::write(
968 &journal,
969 format!("{}\n", serde_json::to_string(&test_event(80)).unwrap()),
970 )
971 .unwrap();
972
973 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 81);
974 assert_eq!(read_persisted_sequence(&sequence), Some(81));
975 }
976
977 #[test]
978 fn concurrent_processes_allocate_unique_event_ids() {
979 let dir = tempfile::tempdir().expect("temp dir");
980 let executable = std::env::current_exe().expect("test executable");
981 let mut children = Vec::new();
982 for writer in 0..4 {
983 children.push(
984 std::process::Command::new(&executable)
985 .args([
986 "--exact",
987 "core::events::tests::persistent_event_id_writer_child",
988 ])
989 .env("__LEAN_CTX_EVENT_ID_TEST_DIR", dir.path())
990 .env("__LEAN_CTX_EVENT_ID_TEST_WRITER", writer.to_string())
991 .spawn()
992 .expect("spawn event id writer"),
993 );
994 }
995 for mut child in children {
996 assert!(child.wait().expect("wait for event id writer").success());
997 }
998
999 let mut ids = Vec::new();
1000 for writer in 0..4 {
1001 let content = std::fs::read_to_string(dir.path().join(format!("writer-{writer}.ids")))
1002 .expect("read allocated ids");
1003 ids.extend(content.lines().map(|line| line.parse::<u64>().unwrap()));
1004 }
1005 ids.sort_unstable();
1006 ids.dedup();
1007 assert_eq!(ids.len(), 400, "every process must receive unique ids");
1008 assert_eq!(ids.first(), Some(&1));
1009 assert_eq!(ids.last(), Some(&400));
1010 let sequence_path = dir.path().join("events.seq");
1011 assert_eq!(read_persisted_sequence(&sequence_path), Some(400));
1012 assert_eq!(
1013 std::fs::read_to_string(sequence_path)
1014 .expect("read sequence journal")
1015 .lines()
1016 .count(),
1017 4,
1018 "four writers should persist four block reservations, not 400 ids"
1019 );
1020 }
1021}