1use serde::{Deserialize, Serialize};
2use std::collections::VecDeque;
3use std::io::Write;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Mutex, OnceLock};
6
7const RING_CAPACITY: usize = 1000;
8const JSONL_MAX_LINES: usize = 10_000;
9const EVENT_ID_BLOCK_SIZE: u64 = 1_024;
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub struct LeanCtxEvent {
13 pub id: u64,
14 pub timestamp: String,
15 pub kind: EventKind,
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize)]
19#[serde(tag = "type")]
20pub enum EventKind {
21 ToolCall {
22 tool: String,
23 tokens_original: u64,
24 tokens_saved: u64,
25 mode: Option<String>,
26 duration_ms: u64,
27 path: Option<String>,
28 },
29 CacheHit {
30 path: String,
31 saved_tokens: u64,
32 },
33 Compression {
34 path: String,
35 before_lines: u32,
36 after_lines: u32,
37 strategy: String,
38 kept_line_count: u32,
39 removed_line_count: u32,
40 },
41 AgentAction {
42 agent_id: String,
43 action: String,
44 tool: Option<String>,
45 },
46 KnowledgeUpdate {
47 category: String,
48 key: String,
49 action: String,
50 },
51 ThresholdShift {
52 language: String,
53 old_entropy: f64,
54 new_entropy: f64,
55 old_jaccard: f64,
56 new_jaccard: f64,
57 },
58 BudgetWarning {
59 role: String,
60 dimension: String,
61 used: String,
62 limit: String,
63 percent: u8,
64 },
65 BudgetExhausted {
66 role: String,
67 dimension: String,
68 used: String,
69 limit: String,
70 },
71 PolicyViolation {
72 role: String,
73 tool: String,
74 reason: String,
75 },
76 RoleChanged {
77 from: String,
78 to: String,
79 },
80 ProfileChanged {
81 from: String,
82 to: String,
83 },
84 SloViolation {
85 slo_name: String,
86 metric: String,
87 threshold: f64,
88 actual: f64,
89 action: String,
90 },
91 Anomaly {
92 metric: String,
93 expected: f64,
94 actual: f64,
95 deviation_factor: f64,
96 },
97 VerificationWarning {
98 warning_kind: String,
99 detail: String,
100 severity: String,
101 },
102 ThresholdAdapted {
103 language: String,
104 arm: String,
105 old_threshold: f64,
106 new_threshold: f64,
107 },
108}
109
110struct EventBus {
111 ring: Mutex<VecDeque<LeanCtxEvent>>,
112}
113
114impl EventBus {
115 fn new() -> Self {
116 Self {
117 ring: Mutex::new(VecDeque::with_capacity(RING_CAPACITY)),
118 }
119 }
120
121 fn emit(&self, kind: EventKind) -> u64 {
122 let id = next_event_id();
123 let event = LeanCtxEvent {
124 id,
125 timestamp: chrono::Local::now()
126 .format("%Y-%m-%dT%H:%M:%S%.3f")
127 .to_string(),
128 kind,
129 };
130
131 {
132 let mut ring = self
133 .ring
134 .lock()
135 .unwrap_or_else(std::sync::PoisonError::into_inner);
136 if ring.len() >= RING_CAPACITY {
137 ring.pop_front();
138 }
139 ring.push_back(event.clone());
140 }
141
142 append_jsonl(&event);
143 id
144 }
145
146 fn events_since(&self, after_id: u64) -> Vec<LeanCtxEvent> {
147 let ring = self
148 .ring
149 .lock()
150 .unwrap_or_else(std::sync::PoisonError::into_inner);
151 ring.iter().filter(|e| e.id > after_id).cloned().collect()
152 }
153
154 fn latest_events(&self, n: usize) -> Vec<LeanCtxEvent> {
155 let ring = self
156 .ring
157 .lock()
158 .unwrap_or_else(std::sync::PoisonError::into_inner);
159 let len = ring.len();
160 let start = len.saturating_sub(n);
161 ring.iter().skip(start).cloned().collect()
162 }
163}
164
165fn bus() -> &'static EventBus {
166 static INSTANCE: OnceLock<EventBus> = OnceLock::new();
167 INSTANCE.get_or_init(EventBus::new)
168}
169
170fn jsonl_path() -> Option<std::path::PathBuf> {
171 crate::core::paths::state_dir()
172 .ok()
173 .map(|d| d.join("events.jsonl"))
174}
175
176fn event_sequence_path() -> Option<std::path::PathBuf> {
177 crate::core::paths::state_dir()
178 .ok()
179 .map(|d| d.join("events.seq"))
180}
181
182fn max_event_id_in_journal(path: &std::path::Path) -> u64 {
183 let Ok(content) = std::fs::read_to_string(path) else {
184 return 0;
185 };
186 content
187 .lines()
188 .filter_map(|line| serde_json::from_str::<LeanCtxEvent>(line).ok())
189 .map(|event| event.id)
190 .max()
191 .unwrap_or(0)
192}
193
194fn parse_sequence_record(record: &str) -> Option<u64> {
195 let (value, checksum) = record.trim().split_once(':')?;
196 let value = value.parse::<u64>().ok()?;
197 let checksum = checksum.parse::<u64>().ok()?;
198 (checksum == !value).then_some(value)
199}
200
201fn read_persisted_sequence(path: &std::path::Path) -> Option<u64> {
202 let content = std::fs::read_to_string(path).ok()?;
203 content.lines().rev().find_map(parse_sequence_record)
204}
205
206fn sequence_record(value: u64) -> String {
207 format!("{value}:{}", !value)
208}
209
210fn reserve_event_id_block_at(
211 sequence_path: &std::path::Path,
212 journal_path: &std::path::Path,
213 block_size: u64,
214) -> std::io::Result<(u64, u64)> {
215 use fs2::FileExt;
216
217 if block_size == 0 {
218 return Err(std::io::Error::other("event id block must not be empty"));
219 }
220 if let Some(parent) = sequence_path.parent() {
221 std::fs::create_dir_all(parent)?;
222 }
223 let lock_path = sequence_path.with_extension("seq.lock");
226 let lock = std::fs::OpenOptions::new()
227 .create(true)
228 .truncate(false)
229 .read(true)
230 .write(true)
231 .open(lock_path)?;
232 lock.lock_exclusive()?;
233
234 let result = (|| {
235 let persisted = read_persisted_sequence(sequence_path);
236 let baseline = persisted.unwrap_or_else(|| {
237 max_event_id_in_journal(journal_path).max(max_event_id_in_journal(
238 &journal_path.with_extension("jsonl.old"),
239 ))
240 });
241 let first = baseline
242 .checked_add(1)
243 .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
244 let last = baseline
245 .checked_add(block_size)
246 .ok_or_else(|| std::io::Error::other("event id space exhausted"))?;
247
248 let needs_leading_newline = std::fs::read(sequence_path)
252 .is_ok_and(|bytes| !bytes.is_empty() && bytes.last() != Some(&b'\n'));
253
254 let mut sequence = std::fs::OpenOptions::new()
255 .create(true)
256 .append(true)
257 .open(sequence_path)?;
258 let mut record = Vec::new();
259 if needs_leading_newline {
260 record.push(b'\n');
261 }
262 record.extend_from_slice(sequence_record(last).as_bytes());
263 record.push(b'\n');
264 sequence.write_all(&record)?;
265 sequence.sync_data()?;
266 Ok((first, last))
267 })();
268
269 let _ = FileExt::unlock(&lock);
270 result
271}
272
273#[cfg(test)]
274fn next_event_id_at(
275 sequence_path: &std::path::Path,
276 journal_path: &std::path::Path,
277) -> std::io::Result<u64> {
278 reserve_event_id_block_at(sequence_path, journal_path, 1).map(|(first, _)| first)
279}
280
281fn next_event_id() -> u64 {
282 #[derive(Default)]
283 struct LocalBlock {
284 next: u64,
285 last: u64,
286 }
287
288 static BLOCK: OnceLock<Mutex<LocalBlock>> = OnceLock::new();
289 static FALLBACK: AtomicU64 = AtomicU64::new(0);
290 if !is_test_environment()
291 && let Some((sequence, journal)) = event_sequence_path().zip(jsonl_path())
292 {
293 let mut block = BLOCK
294 .get_or_init(|| Mutex::new(LocalBlock::default()))
295 .lock()
296 .unwrap_or_else(std::sync::PoisonError::into_inner);
297 if block.next <= block.last && block.next != 0 {
298 let id = block.next;
299 block.next = block.next.saturating_add(1);
300 return id;
301 }
302 if let Ok((first, last)) =
303 reserve_event_id_block_at(&sequence, &journal, EVENT_ID_BLOCK_SIZE)
304 {
305 block.next = first.saturating_add(1);
306 block.last = last;
307 return first;
308 }
309 }
310
311 let base = u64::try_from(chrono::Utc::now().timestamp_millis())
312 .unwrap_or_default()
313 .saturating_mul(1_000);
314 base.saturating_add(FALLBACK.fetch_add(1, Ordering::Relaxed))
315}
316
317fn is_test_environment() -> bool {
318 use std::sync::OnceLock;
319 static CACHED: OnceLock<bool> = OnceLock::new();
320 *CACHED.get_or_init(|| {
321 if cfg!(test) {
322 return true;
323 }
324 if std::env::var_os("__LEAN_CTX_SKIP_EVENTS").is_some() {
325 return true;
326 }
327 std::env::current_exe().is_ok_and(|p| {
328 let s = p.to_string_lossy();
329 s.contains("/deps/") || s.contains("\\deps\\")
330 })
331 })
332}
333
334fn append_jsonl(event: &LeanCtxEvent) {
335 if is_test_environment() {
336 return;
337 }
338 let Some(path) = jsonl_path() else { return };
339 let _ = append_jsonl_at(&path, event);
340}
341
342fn append_jsonl_at(path: &std::path::Path, event: &LeanCtxEvent) -> std::io::Result<()> {
343 use fs2::FileExt;
344 use std::io::Write;
345
346 if let Some(parent) = path.parent() {
347 std::fs::create_dir_all(parent)?;
348 }
349
350 let lock_path = path.with_extension("jsonl.lock");
354 let lock = std::fs::OpenOptions::new()
355 .create(true)
356 .truncate(false)
357 .read(true)
358 .write(true)
359 .open(lock_path)?;
360 lock.lock_exclusive()?;
361
362 let result = (|| {
363 if let Ok(content) = std::fs::read_to_string(path)
364 && content.lines().count() >= JSONL_MAX_LINES
365 {
366 let old = path.with_extension("jsonl.old");
367 let _ = std::fs::remove_file(&old);
368 std::fs::rename(path, old)?;
369 }
370
371 let json = serde_json::to_string(event).map_err(std::io::Error::other)?;
372 let mut line = json.into_bytes();
373 line.push(b'\n');
374 let mut file = std::fs::OpenOptions::new()
375 .create(true)
376 .append(true)
377 .open(path)?;
378 file.write_all(&line)
381 })();
382
383 let _ = FileExt::unlock(&lock);
384 result
385}
386
387pub fn emit(kind: EventKind) -> u64 {
390 bus().emit(kind)
391}
392
393pub fn events_since(after_id: u64) -> Vec<LeanCtxEvent> {
394 bus().events_since(after_id)
395}
396
397pub fn latest_events(n: usize) -> Vec<LeanCtxEvent> {
398 bus().latest_events(n)
399}
400
401#[derive(Default)]
402struct FileEventCache {
403 path: Option<std::path::PathBuf>,
404 mtime: Option<std::time::SystemTime>,
405 len: u64,
406 events: Vec<LeanCtxEvent>,
407}
408
409pub fn load_events_from_file(n: usize) -> Vec<LeanCtxEvent> {
413 static CACHE: OnceLock<Mutex<FileEventCache>> = OnceLock::new();
414 let Some(path) = jsonl_path() else {
415 return Vec::new();
416 };
417 let (mtime, len) = match std::fs::metadata(&path) {
418 Ok(m) => (m.modified().ok(), m.len()),
419 Err(_) => return Vec::new(),
420 };
421
422 let cache = CACHE.get_or_init(|| Mutex::new(FileEventCache::default()));
423 let mut guard = match cache.lock() {
424 Ok(g) => g,
425 Err(poisoned) => poisoned.into_inner(),
426 };
427
428 let fresh =
429 guard.path.as_deref() == Some(path.as_path()) && guard.mtime == mtime && guard.len == len;
430 if !fresh {
431 let Ok(content) = std::fs::read_to_string(&path) else {
432 return Vec::new();
433 };
434 guard.events = content
435 .lines()
436 .filter(|l| !l.trim().is_empty())
437 .filter_map(|l| serde_json::from_str(l).ok())
438 .collect();
439 guard.path = Some(path);
440 guard.mtime = mtime;
441 guard.len = len;
442 }
443
444 let start = guard.events.len().saturating_sub(n);
445 guard.events[start..].to_vec()
446}
447
448pub fn emit_tool_call(
449 tool: &str,
450 tokens_original: u64,
451 tokens_saved: u64,
452 mode: Option<String>,
453 duration_ms: u64,
454 path: Option<String>,
455) {
456 emit(EventKind::ToolCall {
457 tool: tool.to_string(),
458 tokens_original,
459 tokens_saved,
460 mode,
461 duration_ms,
462 path,
463 });
464}
465
466pub fn emit_cache_hit(path: &str, saved_tokens: u64) {
467 emit(EventKind::CacheHit {
468 path: path.to_string(),
469 saved_tokens,
470 });
471}
472
473pub fn emit_agent_action(agent_id: &str, action: &str, tool: Option<&str>) {
474 emit(EventKind::AgentAction {
475 agent_id: agent_id.to_string(),
476 action: action.to_string(),
477 tool: tool.map(std::string::ToString::to_string),
478 });
479}
480
481pub fn emit_budget_warning(role: &str, dimension: &str, used: &str, limit: &str, percent: u8) {
482 if !budget_warning_due(role, dimension, percent) {
488 return;
489 }
490 emit(EventKind::BudgetWarning {
491 role: role.to_string(),
492 dimension: dimension.to_string(),
493 used: used.to_string(),
494 limit: limit.to_string(),
495 percent,
496 });
497}
498
499fn budget_warning_due(role: &str, dimension: &str, percent: u8) -> bool {
503 use std::collections::HashMap;
504 use std::sync::Mutex;
505 use std::time::{Duration, Instant};
506
507 const REPEAT_AFTER: Duration = Duration::from_mins(5);
508
509 type WarnState = HashMap<(String, String), (u8, Instant)>;
510 static LAST: Mutex<Option<WarnState>> = Mutex::new(None);
511
512 let mut guard = LAST
513 .lock()
514 .unwrap_or_else(std::sync::PoisonError::into_inner);
515 let map = guard.get_or_insert_with(HashMap::new);
516 let key = (role.to_string(), dimension.to_string());
517 let bucket = percent / 10;
518 match map.get(&key) {
519 Some((last_bucket, at)) if *last_bucket == bucket && at.elapsed() < REPEAT_AFTER => false,
520 _ => {
521 map.insert(key, (bucket, Instant::now()));
522 true
523 }
524 }
525}
526
527pub fn emit_budget_exhausted(role: &str, dimension: &str, used: &str, limit: &str) {
528 emit(EventKind::BudgetExhausted {
529 role: role.to_string(),
530 dimension: dimension.to_string(),
531 used: used.to_string(),
532 limit: limit.to_string(),
533 });
534}
535
536pub fn emit_policy_violation(role: &str, tool: &str, reason: &str) {
537 emit(EventKind::PolicyViolation {
538 role: role.to_string(),
539 tool: tool.to_string(),
540 reason: reason.to_string(),
541 });
542}
543
544pub fn emit_role_changed(from: &str, to: &str) {
545 emit(EventKind::RoleChanged {
546 from: from.to_string(),
547 to: to.to_string(),
548 });
549}
550
551pub fn emit_profile_changed(from: &str, to: &str) {
552 emit(EventKind::ProfileChanged {
553 from: from.to_string(),
554 to: to.to_string(),
555 });
556}
557
558pub fn emit_slo_violation(slo_name: &str, metric: &str, threshold: f64, actual: f64, action: &str) {
559 emit(EventKind::SloViolation {
560 slo_name: slo_name.to_string(),
561 metric: metric.to_string(),
562 threshold,
563 actual,
564 action: action.to_string(),
565 });
566}
567
568pub fn emit_anomaly(metric: &str, expected: f64, actual: f64, deviation_factor: f64) {
569 emit(EventKind::Anomaly {
570 metric: metric.to_string(),
571 expected,
572 actual,
573 deviation_factor,
574 });
575}
576
577pub fn emit_verification_warning(warning_kind: &str, detail: &str, severity: &str) {
578 emit(EventKind::VerificationWarning {
579 warning_kind: warning_kind.to_string(),
580 detail: detail.to_string(),
581 severity: severity.to_string(),
582 });
583}
584
585pub fn emit_threshold_adapted(language: &str, arm: &str, old_threshold: f64, new_threshold: f64) {
586 emit(EventKind::ThresholdAdapted {
587 language: language.to_string(),
588 arm: arm.to_string(),
589 old_threshold,
590 new_threshold,
591 });
592}
593
594#[cfg(test)]
595mod tests {
596 use super::*;
597
598 #[test]
599 fn emit_returns_positive_id() {
600 let id = emit(EventKind::ToolCall {
601 tool: "ctx_read".to_string(),
602 tokens_original: 1000,
603 tokens_saved: 800,
604 mode: Some("map".to_string()),
605 duration_ms: 5,
606 path: Some("src/main.rs".to_string()),
607 });
608 assert!(id > 0);
609 let events = latest_events(100);
610 assert!(events.iter().any(|e| e.id == id));
611 }
612
613 #[test]
617 fn budget_warning_rate_limit_suppresses_repeats() {
618 let role = format!("test-role-{}", std::process::id());
619 assert!(budget_warning_due(&role, "tokens", 85));
620 assert!(!budget_warning_due(&role, "tokens", 85));
621 assert!(!budget_warning_due(&role, "tokens", 87)); assert!(budget_warning_due(&role, "tokens", 95)); assert!(!budget_warning_due(&role, "tokens", 95));
624 assert!(budget_warning_due(&role, "cost", 85)); }
626
627 #[test]
628 fn events_since_filters_correctly() {
629 let id1 = emit(EventKind::CacheHit {
630 path: "filter_test_a.rs".to_string(),
631 saved_tokens: 100,
632 });
633 let id2 = emit(EventKind::CacheHit {
634 path: "filter_test_b.rs".to_string(),
635 saved_tokens: 200,
636 });
637
638 let after = events_since(id1);
639 assert!(after.iter().any(|e| e.id == id2));
640 assert!(after.iter().all(|e| e.id > id1));
641 }
642
643 #[test]
647 fn load_events_from_file_sees_appended_events() {
648 let path = jsonl_path().expect("test sandbox data dir");
649 if let Some(parent) = path.parent() {
650 std::fs::create_dir_all(parent).expect("create data dir");
651 }
652
653 let line_a = r#"{"id":900001,"timestamp":"2026-06-12T08:00:00.000","kind":{"type":"CacheHit","path":"cached_a.rs","saved_tokens":42}}"#;
654 std::fs::write(&path, format!("{line_a}\n")).expect("write events.jsonl");
655
656 let first = load_events_from_file(50);
657 assert!(
658 first.iter().any(|e| e.id == 900_001),
659 "initial load should parse the seeded event"
660 );
661
662 let cached = load_events_from_file(50);
664 assert_eq!(cached.len(), first.len());
665
666 let line_b = r#"{"id":900002,"timestamp":"2026-06-12T08:00:01.000","kind":{"type":"CacheHit","path":"cached_b.rs","saved_tokens":7}}"#;
667 {
668 use std::io::Write;
669 let mut f = std::fs::OpenOptions::new()
670 .append(true)
671 .open(&path)
672 .expect("append events.jsonl");
673 writeln!(f, "{line_b}").expect("append line");
674 }
675
676 let second = load_events_from_file(50);
677 assert!(
678 second.iter().any(|e| e.id == 900_002),
679 "append must invalidate the cache and surface the new event"
680 );
681 }
682
683 #[test]
684 fn events_jsonl_writer_child() {
685 let Some(path) = std::env::var_os("__LEAN_CTX_EVENTS_TEST_PATH") else {
686 return;
687 };
688 let writer = std::env::var("__LEAN_CTX_EVENTS_TEST_WRITER")
689 .expect("writer id")
690 .parse::<u64>()
691 .expect("numeric writer id");
692 for sequence in 0..100 {
693 let event = LeanCtxEvent {
694 id: writer * 100 + sequence,
695 timestamp: "2026-07-15T12:00:00.000".to_string(),
696 kind: EventKind::CacheHit {
697 path: format!("writer-{writer}.rs"),
698 saved_tokens: sequence,
699 },
700 };
701 append_jsonl_at(std::path::Path::new(&path), &event).expect("append event");
702 }
703 }
704
705 fn test_event(id: u64) -> LeanCtxEvent {
706 LeanCtxEvent {
707 id,
708 timestamp: "2026-07-15T12:00:00.000".to_string(),
709 kind: EventKind::CacheHit {
710 path: "event-id-test.rs".to_string(),
711 saved_tokens: 1,
712 },
713 }
714 }
715
716 #[test]
717 fn concurrent_processes_append_complete_json_lines() {
718 let dir = tempfile::tempdir().expect("temp dir");
719 let path = dir.path().join("events.jsonl");
720 let executable = std::env::current_exe().expect("test executable");
721
722 let mut children = Vec::new();
723 for writer in 0..4 {
724 children.push(
725 std::process::Command::new(&executable)
726 .args([
727 "--exact",
728 "core::events::tests::events_jsonl_writer_child",
729 "--nocapture",
730 ])
731 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
732 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
733 .spawn()
734 .expect("spawn writer"),
735 );
736 }
737 for mut child in children {
738 assert!(child.wait().expect("wait for writer").success());
739 }
740
741 let content = std::fs::read_to_string(&path).expect("read events");
742 let lines: Vec<_> = content.lines().collect();
743 assert_eq!(lines.len(), 400, "every append must produce one line");
744 for line in lines {
745 serde_json::from_str::<LeanCtxEvent>(line)
746 .unwrap_or_else(|error| panic!("invalid JSONL line: {error}: {line}"));
747 }
748 }
749
750 #[test]
751 fn concurrent_processes_serialize_rotation_and_append() {
752 let dir = tempfile::tempdir().expect("temp dir");
753 let path = dir.path().join("events.jsonl");
754 let seed = serde_json::to_string(&LeanCtxEvent {
755 id: 1,
756 timestamp: "2026-07-15T12:00:00.000".to_string(),
757 kind: EventKind::CacheHit {
758 path: "seed.rs".to_string(),
759 saved_tokens: 1,
760 },
761 })
762 .expect("serialize seed");
763 std::fs::write(&path, format!("{seed}\n").repeat(JSONL_MAX_LINES))
764 .expect("seed rotation threshold");
765
766 let executable = std::env::current_exe().expect("test executable");
767 let mut children = Vec::new();
768 for writer in 0..4 {
769 children.push(
770 std::process::Command::new(&executable)
771 .args(["--exact", "core::events::tests::events_jsonl_writer_child"])
772 .env("__LEAN_CTX_EVENTS_TEST_PATH", &path)
773 .env("__LEAN_CTX_EVENTS_TEST_WRITER", writer.to_string())
774 .spawn()
775 .expect("spawn writer"),
776 );
777 }
778 for mut child in children {
779 assert!(child.wait().expect("wait for writer").success());
780 }
781
782 let old =
783 std::fs::read_to_string(path.with_extension("jsonl.old")).expect("rotated journal");
784 assert_eq!(old.lines().count(), JSONL_MAX_LINES);
785 assert!(
786 old.lines()
787 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
788 "rotated journal must contain complete JSON lines"
789 );
790
791 let current = std::fs::read_to_string(&path).expect("current journal");
792 assert_eq!(current.lines().count(), 400);
793 assert!(
794 current
795 .lines()
796 .all(|line| serde_json::from_str::<LeanCtxEvent>(line).is_ok()),
797 "replacement journal must contain complete JSON lines"
798 );
799 }
800
801 #[test]
802 fn persistent_event_id_writer_child() {
803 let Some(dir) = std::env::var_os("__LEAN_CTX_EVENT_ID_TEST_DIR") else {
804 return;
805 };
806 let writer = std::env::var("__LEAN_CTX_EVENT_ID_TEST_WRITER").expect("writer id");
807 let dir = std::path::PathBuf::from(dir);
808 let sequence = dir.join("events.seq");
809 let journal = dir.join("events.jsonl");
810 let (first, last) =
811 reserve_event_id_block_at(&sequence, &journal, 100).expect("reserve event id block");
812 let ids: Vec<String> = (first..=last).map(|id| id.to_string()).collect();
813 std::fs::write(dir.join(format!("writer-{writer}.ids")), ids.join("\n"))
814 .expect("write allocated ids");
815 }
816
817 #[test]
818 fn persistent_event_id_bootstraps_above_existing_journals() {
819 let dir = tempfile::tempdir().expect("temp dir");
820 let sequence = dir.path().join("events.seq");
821 let journal = dir.path().join("events.jsonl");
822 let old = journal.with_extension("jsonl.old");
823 std::fs::write(
824 &journal,
825 format!("{}\n", serde_json::to_string(&test_event(41)).unwrap()),
826 )
827 .unwrap();
828 std::fs::write(
829 &old,
830 format!("{}\n", serde_json::to_string(&test_event(73)).unwrap()),
831 )
832 .unwrap();
833
834 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 74);
835 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 75);
836 }
837
838 #[test]
839 fn corrupt_sequence_recovers_above_existing_journal() {
840 let dir = tempfile::tempdir().expect("temp dir");
841 let sequence = dir.path().join("events.seq");
842 let journal = dir.path().join("events.jsonl");
843 std::fs::write(&sequence, "76:broken").unwrap();
844 std::fs::write(
845 &journal,
846 format!("{}\n", serde_json::to_string(&test_event(80)).unwrap()),
847 )
848 .unwrap();
849
850 assert_eq!(next_event_id_at(&sequence, &journal).unwrap(), 81);
851 assert_eq!(read_persisted_sequence(&sequence), Some(81));
852 }
853
854 #[test]
855 fn concurrent_processes_allocate_unique_event_ids() {
856 let dir = tempfile::tempdir().expect("temp dir");
857 let executable = std::env::current_exe().expect("test executable");
858 let mut children = Vec::new();
859 for writer in 0..4 {
860 children.push(
861 std::process::Command::new(&executable)
862 .args([
863 "--exact",
864 "core::events::tests::persistent_event_id_writer_child",
865 ])
866 .env("__LEAN_CTX_EVENT_ID_TEST_DIR", dir.path())
867 .env("__LEAN_CTX_EVENT_ID_TEST_WRITER", writer.to_string())
868 .spawn()
869 .expect("spawn event id writer"),
870 );
871 }
872 for mut child in children {
873 assert!(child.wait().expect("wait for event id writer").success());
874 }
875
876 let mut ids = Vec::new();
877 for writer in 0..4 {
878 let content = std::fs::read_to_string(dir.path().join(format!("writer-{writer}.ids")))
879 .expect("read allocated ids");
880 ids.extend(content.lines().map(|line| line.parse::<u64>().unwrap()));
881 }
882 ids.sort_unstable();
883 ids.dedup();
884 assert_eq!(ids.len(), 400, "every process must receive unique ids");
885 assert_eq!(ids.first(), Some(&1));
886 assert_eq!(ids.last(), Some(&400));
887 let sequence_path = dir.path().join("events.seq");
888 assert_eq!(read_persisted_sequence(&sequence_path), Some(400));
889 assert_eq!(
890 std::fs::read_to_string(sequence_path)
891 .expect("read sequence journal")
892 .lines()
893 .count(),
894 4,
895 "four writers should persist four block reservations, not 400 ids"
896 );
897 }
898}