Skip to main content

skenion_runtime/
session_registry.rs

1use std::{
2    collections::{BTreeMap, VecDeque},
3    convert::Infallible,
4    sync::{Arc, Mutex, RwLock},
5};
6
7use axum::{http::HeaderMap, response::sse::Event};
8use serde::Deserialize;
9use serde_json::Value;
10use skenion_contracts::{
11    RuntimeConnectionProfile, RuntimeConnectionProfileMode, RuntimeEventReplayGap,
12    RuntimeEventReplayGapReason, RuntimeEventReplayMetadata, RuntimeEventReplayWindow,
13    RuntimeHistory as ContractRuntimeHistory, RuntimeHistoryEntry as ContractRuntimeHistoryEntry,
14    RuntimeSessionCapabilitySet, RuntimeSessionInfoResponse, RuntimeSessionLifecycleState,
15    validate_runtime_session_event,
16};
17pub use skenion_contracts::{RuntimeSessionEvent, RuntimeSessionEventKind};
18use tokio::sync::broadcast;
19use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
20
21use crate::{
22    COLLABORATION_EVENT_REPLAY_LIMIT, PreviewManager, RuntimeCollaborationLog, RuntimeDiagnostic,
23    RuntimeSession, RuntimeSessionSnapshot, runtime_time::created_at_now,
24};
25
26pub const DEFAULT_SESSION_ID: &str = "default";
27const SESSION_EVENT_REPLAY_LIMIT: usize = 256;
28
29#[derive(Debug, Clone, Deserialize)]
30#[serde(rename_all = "camelCase")]
31pub struct SessionEventsQuery {
32    pub after: Option<u64>,
33}
34
35#[derive(Clone)]
36pub struct RuntimeSessionRegistry {
37    sessions: Arc<RwLock<BTreeMap<String, RuntimeSessionRecord>>>,
38    default_session_id: String,
39    replay_limit: usize,
40    dry_preview: bool,
41}
42
43impl Default for RuntimeSessionRegistry {
44    fn default() -> Self {
45        Self::new(false)
46    }
47}
48
49impl RuntimeSessionRegistry {
50    pub fn new(dry_preview: bool) -> Self {
51        let registry = Self {
52            sessions: Arc::new(RwLock::new(BTreeMap::new())),
53            default_session_id: DEFAULT_SESSION_ID.to_owned(),
54            replay_limit: SESSION_EVENT_REPLAY_LIMIT,
55            dry_preview,
56        };
57        registry.get_or_create(DEFAULT_SESSION_ID);
58        registry
59    }
60
61    pub fn dry_preview() -> Self {
62        Self::new(true)
63    }
64
65    pub fn default_session_id(&self) -> &str {
66        &self.default_session_id
67    }
68
69    pub fn default_record(&self) -> RuntimeSessionRecord {
70        self.get_or_create(self.default_session_id())
71    }
72
73    pub fn get_or_create(&self, session_id: &str) -> RuntimeSessionRecord {
74        assert!(
75            !session_id.is_empty(),
76            "session_id must be explicit; use default_record() for the built-in default session"
77        );
78        if let Some(record) = self
79            .sessions
80            .read()
81            .expect("runtime session registry lock should not be poisoned")
82            .get(session_id)
83            .cloned()
84        {
85            return record;
86        }
87
88        let mut sessions = self
89            .sessions
90            .write()
91            .expect("runtime session registry lock should not be poisoned");
92        sessions
93            .entry(session_id.to_owned())
94            .or_insert_with(|| {
95                RuntimeSessionRecord::new(session_id, self.replay_limit, self.dry_preview)
96            })
97            .clone()
98    }
99}
100
101#[derive(Clone)]
102pub struct RuntimeSessionRecord {
103    pub id: String,
104    pub session: Arc<RwLock<RuntimeSession>>,
105    pub events: broadcast::Sender<RuntimeSessionEvent>,
106    pub collaboration: Arc<RuntimeCollaborationLog>,
107    pub event_store: Arc<Mutex<VecDeque<RuntimeSessionEvent>>>,
108    pub event_sequence: Arc<Mutex<u64>>,
109    pub preview: Arc<Mutex<PreviewManager>>,
110    replay_limit: usize,
111}
112
113#[derive(Debug, Clone)]
114pub struct RuntimeSessionReplay {
115    pub events: Vec<RuntimeSessionEvent>,
116    pub high_water_sequence: u64,
117}
118
119impl RuntimeSessionRecord {
120    fn new(session_id: &str, replay_limit: usize, dry_preview: bool) -> Self {
121        let (events, _) = broadcast::channel(replay_limit);
122        Self {
123            id: session_id.to_owned(),
124            session: Arc::new(RwLock::new(RuntimeSession::default())),
125            events,
126            collaboration: RuntimeCollaborationLog::new(COLLABORATION_EVENT_REPLAY_LIMIT),
127            event_store: Arc::new(Mutex::new(VecDeque::new())),
128            event_sequence: Arc::new(Mutex::new(1)),
129            preview: Arc::new(Mutex::new(if dry_preview {
130                PreviewManager::dry_run()
131            } else {
132                PreviewManager::from_env()
133            })),
134            replay_limit,
135        }
136    }
137
138    pub fn event_replay_window(&self) -> RuntimeEventReplayWindow {
139        let store = self
140            .event_store
141            .lock()
142            .expect("runtime session event store lock should not be poisoned");
143        let earliest_sequence = store.front().map(|event| event.sequence).unwrap_or(1);
144        let latest_sequence = store
145            .back()
146            .map(|event| event.sequence)
147            .unwrap_or_else(|| current_session_event_sequence(self));
148        RuntimeEventReplayWindow {
149            cursor_kind: "sequence".to_owned(),
150            current_cursor: latest_sequence.to_string(),
151            earliest_sequence,
152            latest_sequence,
153            replay_limit: Some(self.replay_limit as u64),
154            overflow: Some(store.len() >= self.replay_limit),
155        }
156    }
157
158    pub fn info_response(&self, profile: RuntimeConnectionProfile) -> RuntimeSessionInfoResponse {
159        let snapshot = {
160            let session = self
161                .session
162                .read()
163                .expect("runtime session lock should not be poisoned");
164            session.snapshot()
165        };
166        let mut diagnostics = Vec::new();
167        for diagnostic in &snapshot.diagnostics {
168            diagnostics.push(
169                serde_json::to_value(diagnostic)
170                    .expect("runtime diagnostic should serialize to JSON"),
171            );
172        }
173        RuntimeSessionInfoResponse {
174            schema: "skenion.runtime.session.info".to_owned(),
175            schema_version: "0.1.0".to_owned(),
176            ok: true,
177            session_id: self.id.clone(),
178            lifecycle: RuntimeSessionLifecycleState::Ready,
179            snapshot: contract_session_snapshot(&snapshot),
180            profile,
181            capabilities: runtime_session_capabilities(),
182            event_replay: self.event_replay_window(),
183            diagnostics,
184        }
185    }
186}
187
188pub fn publish_session_event(
189    record: &RuntimeSessionRecord,
190    kind: RuntimeSessionEventKind,
191    session: &RuntimeSession,
192    diagnostics: Vec<RuntimeDiagnostic>,
193) {
194    let sequence = next_session_event_sequence(record);
195    let event = session_event_from_session(
196        record,
197        kind,
198        session,
199        event_replay_fields(session_event_id(&record.id, sequence), sequence),
200        diagnostics,
201    );
202    store_session_event(record, event.clone());
203    let _ = record.events.send(event);
204}
205
206fn session_event_from_session(
207    record: &RuntimeSessionRecord,
208    kind: RuntimeSessionEventKind,
209    session: &RuntimeSession,
210    replay: SessionEventReplayFields,
211    diagnostics: Vec<RuntimeDiagnostic>,
212) -> RuntimeSessionEvent {
213    let snapshot = session.snapshot();
214    let history = session.history();
215    let event = RuntimeSessionEvent {
216        schema: "skenion.runtime.session.event".to_owned(),
217        schema_version: "0.1.0".to_owned(),
218        id: replay.id,
219        session_id: record.id.clone(),
220        sequence: replay.sequence,
221        session_revision: snapshot.session_revision,
222        kind,
223        snapshot: contract_session_snapshot(&snapshot),
224        mutation: history.entries.last().map(contract_history_entry),
225        history: contract_runtime_history(&history),
226        replay: RuntimeEventReplayMetadata {
227            cursor: replay.cursor,
228            previous_cursor: replay.previous_cursor,
229            replayed: replay.replayed,
230            gap: replay.gap,
231            overflow: replay.overflow,
232        },
233        diagnostics: contract_diagnostics(&diagnostics),
234        created_at: created_at_now(),
235    };
236    validate_runtime_session_event(&event).expect("runtime session event should validate");
237    event
238}
239
240pub fn session_snapshot_event(
241    record: &RuntimeSessionRecord,
242    session: &RuntimeSession,
243) -> RuntimeSessionEvent {
244    let latest_sequence = current_session_event_sequence(record);
245    let sequence = latest_sequence.max(1);
246    let previous_cursor = if latest_sequence == 0 {
247        None
248    } else {
249        previous_cursor_for(latest_sequence)
250    };
251    session_event_from_session(
252        record,
253        RuntimeSessionEventKind::Snapshot,
254        session,
255        SessionEventReplayFields {
256            id: format!("{}_snapshot_{latest_sequence:06}", record.id),
257            sequence,
258            cursor: latest_sequence.to_string(),
259            previous_cursor,
260            replayed: false,
261            gap: None,
262            overflow: false,
263        },
264        Vec::new(),
265    )
266}
267
268struct SessionEventReplayFields {
269    id: String,
270    sequence: u64,
271    cursor: String,
272    previous_cursor: Option<String>,
273    replayed: bool,
274    gap: Option<RuntimeEventReplayGap>,
275    overflow: bool,
276}
277
278fn event_replay_fields(id: String, sequence: u64) -> SessionEventReplayFields {
279    SessionEventReplayFields {
280        id,
281        sequence,
282        cursor: sequence.to_string(),
283        previous_cursor: previous_cursor_for(sequence),
284        replayed: false,
285        gap: None,
286        overflow: false,
287    }
288}
289
290fn next_session_event_sequence(record: &RuntimeSessionRecord) -> u64 {
291    let mut sequence = record
292        .event_sequence
293        .lock()
294        .expect("runtime session event sequence lock should not be poisoned");
295    let current = *sequence;
296    *sequence += 1;
297    current
298}
299
300pub fn current_session_event_sequence(record: &RuntimeSessionRecord) -> u64 {
301    let next_sequence = record
302        .event_sequence
303        .lock()
304        .expect("runtime session event sequence lock should not be poisoned");
305    next_sequence.saturating_sub(1)
306}
307
308fn previous_cursor_for(sequence: u64) -> Option<String> {
309    sequence
310        .checked_sub(1)
311        .filter(|previous| *previous > 0)
312        .map(|previous| previous.to_string())
313}
314
315fn session_event_id(session_id: &str, sequence: u64) -> String {
316    format!("{session_id}_event_{sequence:06}")
317}
318
319fn store_session_event(record: &RuntimeSessionRecord, event: RuntimeSessionEvent) {
320    let mut store = record
321        .event_store
322        .lock()
323        .expect("runtime session event store lock should not be poisoned");
324    store.push_back(event);
325    while store.len() > record.replay_limit {
326        store.pop_front();
327    }
328}
329
330pub fn capture_session_replay(
331    record: &RuntimeSessionRecord,
332    after: Option<u64>,
333    snapshot: RuntimeSessionEvent,
334) -> RuntimeSessionReplay {
335    let high_water_sequence = latest_stored_session_event_sequence(record)
336        .unwrap_or_else(|| current_session_event_sequence(record));
337    let Some(after) = after else {
338        return RuntimeSessionReplay {
339            events: vec![snapshot],
340            high_water_sequence,
341        };
342    };
343    let store = record
344        .event_store
345        .lock()
346        .expect("runtime session event store lock should not be poisoned");
347    let earliest = store.front().map(|event| event.sequence);
348    let mut replay = Vec::new();
349    for event in store.iter().filter(|event| event.sequence > after) {
350        let mut event = event.clone();
351        event.replay.replayed = true;
352        validate_runtime_session_event(&event).expect("runtime replay event should validate");
353        replay.push(event);
354    }
355    if let Some(earliest) = earliest
356        && after + 1 < earliest
357    {
358        let gap = replay_gap_event(
359            snapshot,
360            &record.id,
361            after,
362            earliest,
363            RuntimeEventReplayGapReason::RetentionOverflow,
364        );
365        replay.insert(0, gap);
366    }
367    RuntimeSessionReplay {
368        events: replay,
369        high_water_sequence,
370    }
371}
372
373fn replay_gap_event(
374    mut snapshot: RuntimeSessionEvent,
375    session_id: &str,
376    after: u64,
377    actual_sequence: u64,
378    reason: RuntimeEventReplayGapReason,
379) -> RuntimeSessionEvent {
380    let expected_sequence = after + 1;
381    snapshot.id = format!("{session_id}_gap_{expected_sequence:06}_{actual_sequence:06}");
382    snapshot.sequence = expected_sequence;
383    snapshot.replay = RuntimeEventReplayMetadata {
384        cursor: expected_sequence.to_string(),
385        previous_cursor: if after == 0 {
386            None
387        } else {
388            Some(after.to_string())
389        },
390        replayed: true,
391        gap: Some(RuntimeEventReplayGap {
392            expected_sequence,
393            actual_sequence,
394            reason,
395        }),
396        overflow: true,
397    };
398    validate_runtime_session_event(&snapshot).expect("runtime replay gap event should validate");
399    snapshot
400}
401
402pub fn event_cursor_from_headers(headers: &HeaderMap) -> Option<u64> {
403    match headers.get("last-event-id") {
404        Some(value) => value.to_str().ok().and_then(|cursor| cursor.parse().ok()),
405        None => None,
406    }
407}
408
409pub fn session_broadcast_event_after_high_water(
410    result: Result<RuntimeSessionEvent, BroadcastStreamRecvError>,
411    record: RuntimeSessionRecord,
412    high_water_sequence: u64,
413) -> Option<Result<Event, Infallible>> {
414    match result {
415        Ok(event) if event.sequence <= high_water_sequence => None,
416        Ok(event) => Some(session_event(event)),
417        Err(BroadcastStreamRecvError::Lagged(skipped)) => {
418            Some(session_event(session_lag_gap_event(&record, skipped)))
419        }
420    }
421}
422
423pub fn session_event(event: RuntimeSessionEvent) -> Result<Event, Infallible> {
424    Ok(Event::default()
425        .event("session")
426        .id(event.replay.cursor.clone())
427        .json_data(event)
428        .expect("runtime session event should serialize"))
429}
430
431pub fn session_lag_gap_event(record: &RuntimeSessionRecord, skipped: u64) -> RuntimeSessionEvent {
432    let actual_sequence = oldest_retained_session_event_sequence(record)
433        .unwrap_or_else(|| current_session_event_sequence(record))
434        .max(2);
435    let skipped = skipped.max(1);
436    let expected_sequence = actual_sequence.saturating_sub(skipped).max(1);
437    let session = record
438        .session
439        .read()
440        .expect("runtime session lock should not be poisoned");
441    session_event_from_session(
442        record,
443        RuntimeSessionEventKind::Snapshot,
444        &session,
445        SessionEventReplayFields {
446            id: format!(
447                "{}_stream_gap_{expected_sequence:06}_{actual_sequence:06}",
448                record.id
449            ),
450            sequence: expected_sequence,
451            cursor: expected_sequence.to_string(),
452            previous_cursor: previous_cursor_for(expected_sequence),
453            replayed: true,
454            gap: Some(RuntimeEventReplayGap {
455                expected_sequence,
456                actual_sequence,
457                reason: RuntimeEventReplayGapReason::StreamReset,
458            }),
459            overflow: true,
460        },
461        Vec::new(),
462    )
463}
464
465fn oldest_retained_session_event_sequence(record: &RuntimeSessionRecord) -> Option<u64> {
466    record
467        .event_store
468        .lock()
469        .expect("runtime session event store lock should not be poisoned")
470        .front()
471        .map(|event| event.sequence)
472}
473
474fn latest_stored_session_event_sequence(record: &RuntimeSessionRecord) -> Option<u64> {
475    record
476        .event_store
477        .lock()
478        .expect("runtime session event store lock should not be poisoned")
479        .back()
480        .map(|event| event.sequence)
481}
482
483fn contract_session_snapshot(
484    snapshot: &RuntimeSessionSnapshot,
485) -> skenion_contracts::RuntimeSessionSnapshot {
486    serde_json::from_value(
487        serde_json::to_value(snapshot).expect("runtime session snapshot should serialize"),
488    )
489    .expect("runtime session snapshot should match contract shape")
490}
491
492fn contract_runtime_history(history: &crate::RuntimeHistory) -> ContractRuntimeHistory {
493    serde_json::from_value(serde_json::to_value(history).expect("runtime history should serialize"))
494        .expect("runtime history should match contract shape")
495}
496
497fn contract_history_entry(entry: &crate::RuntimeHistoryEntry) -> ContractRuntimeHistoryEntry {
498    serde_json::from_value(
499        serde_json::to_value(entry).expect("runtime history entry should serialize"),
500    )
501    .expect("runtime history entry should match contract shape")
502}
503
504fn contract_diagnostics(diagnostics: &[RuntimeDiagnostic]) -> Vec<Value> {
505    let mut values = Vec::new();
506    for diagnostic in diagnostics {
507        values.push(
508            serde_json::to_value(diagnostic).expect("runtime diagnostic should serialize to JSON"),
509        );
510    }
511    values
512}
513
514fn runtime_session_capabilities() -> RuntimeSessionCapabilitySet {
515    RuntimeSessionCapabilitySet {
516        session_addressing: true,
517        event_replay: true,
518        multi_window: true,
519        profiles: vec![
520            RuntimeConnectionProfileMode::LocalManaged,
521            RuntimeConnectionProfileMode::LocalShared,
522            RuntimeConnectionProfileMode::Remote,
523        ],
524        auth_policy: "deferred".to_owned(),
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use axum::http::{HeaderMap, HeaderValue};
531    use skenion_contracts::RuntimeEventReplayGapReason;
532    use tokio_stream::{StreamExt, wrappers::BroadcastStream};
533
534    use super::*;
535    use crate::sidecar::RuntimeEndpointConfig;
536
537    #[test]
538    fn registry_creates_explicit_default_and_named_records() {
539        let registry = RuntimeSessionRegistry::dry_preview();
540
541        assert_eq!(registry.default_record().id, DEFAULT_SESSION_ID);
542        assert_eq!(
543            registry.get_or_create(DEFAULT_SESSION_ID).id,
544            DEFAULT_SESSION_ID
545        );
546        assert_eq!(registry.get_or_create("alpha").id, "alpha");
547        let endpoint = RuntimeEndpointConfig::new("127.0.0.1".to_owned(), 3761);
548        let profile = crate::sidecar::runtime_connection_profile(&endpoint, "unix-ms:1");
549        let info = registry.default_record().info_response(profile);
550        assert!(info.capabilities.session_addressing);
551    }
552
553    #[test]
554    fn per_session_events_are_monotonic_and_replay_gaps_are_deterministic() {
555        let record = RuntimeSessionRecord::new("gap-test", 2, true);
556        let session = RuntimeSession::default();
557
558        for _ in 0..3 {
559            publish_session_event(
560                &record,
561                RuntimeSessionEventKind::Snapshot,
562                &session,
563                Vec::new(),
564            );
565        }
566        let snapshot = session_snapshot_event(&record, &session);
567        let replay = capture_session_replay(&record, Some(0), snapshot).events;
568        let gap = replay[0]
569            .replay
570            .gap
571            .as_ref()
572            .expect("replay should include retention gap");
573
574        assert_eq!(
575            replay
576                .iter()
577                .map(|event| event.sequence)
578                .collect::<Vec<_>>(),
579            vec![1, 2, 3]
580        );
581        assert_eq!(gap.expected_sequence, 1);
582        assert_eq!(gap.actual_sequence, 2);
583        assert_eq!(gap.reason, RuntimeEventReplayGapReason::RetentionOverflow);
584        for event in replay {
585            validate_runtime_session_event(&event).expect("replayed event should validate");
586        }
587    }
588
589    #[test]
590    fn retention_gap_after_nonzero_cursor_preserves_previous_cursor() {
591        let record = RuntimeSessionRecord::new("gap-after-test", 2, true);
592        let session = RuntimeSession::default();
593
594        for _ in 0..4 {
595            publish_session_event(
596                &record,
597                RuntimeSessionEventKind::Snapshot,
598                &session,
599                Vec::new(),
600            );
601        }
602        let replay =
603            capture_session_replay(&record, Some(1), session_snapshot_event(&record, &session))
604                .events;
605        let gap = replay[0]
606            .replay
607            .gap
608            .as_ref()
609            .expect("replay should include retention gap");
610
611        assert_eq!(
612            replay
613                .iter()
614                .map(|event| event.sequence)
615                .collect::<Vec<_>>(),
616            vec![2, 3, 4]
617        );
618        assert_eq!(replay[0].replay.previous_cursor.as_deref(), Some("1"));
619        assert_eq!(gap.expected_sequence, 2);
620        assert_eq!(gap.actual_sequence, 3);
621    }
622
623    #[test]
624    fn stream_snapshot_does_not_consume_canonical_sequence() {
625        let record = RuntimeSessionRecord::new("snapshot-test", 2, true);
626        let session = RuntimeSession::default();
627
628        let snapshot = session_snapshot_event(&record, &session);
629
630        assert_eq!(current_session_event_sequence(&record), 0);
631        assert_eq!(snapshot.sequence, 1);
632        assert_eq!(snapshot.replay.cursor, "0");
633        validate_runtime_session_event(&snapshot).expect("snapshot event should validate");
634
635        publish_session_event(
636            &record,
637            RuntimeSessionEventKind::Snapshot,
638            &session,
639            vec![RuntimeDiagnostic::warning("covered diagnostic")],
640        );
641        let stored = record
642            .event_store
643            .lock()
644            .expect("event store should not be poisoned")
645            .front()
646            .cloned()
647            .expect("published event should be stored");
648        assert_eq!(stored.sequence, 1);
649        assert_eq!(stored.replay.cursor, "1");
650        assert_eq!(stored.diagnostics[0]["message"], "covered diagnostic");
651        assert_eq!(current_session_event_sequence(&record), 1);
652    }
653
654    #[test]
655    fn live_lag_gap_is_contract_shaped() {
656        let record = RuntimeSessionRecord::new("lag-test", 2, true);
657        let session = RuntimeSession::default();
658        for _ in 0..3 {
659            publish_session_event(
660                &record,
661                RuntimeSessionEventKind::Snapshot,
662                &session,
663                Vec::new(),
664            );
665        }
666
667        let gap = session_lag_gap_event(&record, 99);
668
669        assert_eq!(gap.session_id, "lag-test");
670        assert_eq!(
671            gap.replay.gap.as_ref().unwrap().reason,
672            RuntimeEventReplayGapReason::StreamReset
673        );
674        assert_eq!(gap.replay.gap.as_ref().unwrap().expected_sequence, 1);
675        assert_eq!(gap.replay.gap.as_ref().unwrap().actual_sequence, 2);
676        validate_runtime_session_event(&gap).expect("live lag gap event should validate");
677    }
678
679    #[tokio::test]
680    async fn broadcast_lag_gap_and_retained_live_events_are_monotonic() {
681        let record = RuntimeSessionRecord::new("lag-order-test", 2, true);
682        let session = RuntimeSession::default();
683        let receiver = record.events.subscribe();
684        for _ in 0..5 {
685            publish_session_event(
686                &record,
687                RuntimeSessionEventKind::Snapshot,
688                &session,
689                Vec::new(),
690            );
691        }
692
693        let mut stream = BroadcastStream::new(receiver);
694        let BroadcastStreamRecvError::Lagged(skipped) = stream
695            .next()
696            .await
697            .expect("lagged stream should yield an item")
698            .expect_err("first stream item should be a lag error");
699        let gap = session_lag_gap_event(&record, skipped);
700        let first_retained = stream
701            .next()
702            .await
703            .expect("first retained event should arrive")
704            .expect("first retained event should be ok");
705        let second_retained = stream
706            .next()
707            .await
708            .expect("second retained event should arrive")
709            .expect("second retained event should be ok");
710        let sequences = vec![
711            gap.sequence,
712            first_retained.sequence,
713            second_retained.sequence,
714        ];
715
716        assert_eq!(
717            gap.replay.gap.as_ref().unwrap().actual_sequence,
718            first_retained.sequence
719        );
720        assert_eq!(sequences, vec![1, 4, 5]);
721        assert!(sequences.windows(2).all(|pair| pair[0] <= pair[1]));
722        validate_runtime_session_event(&gap).expect("lag gap event should validate");
723        validate_runtime_session_event(&first_retained)
724            .expect("first retained live event should validate");
725        validate_runtime_session_event(&second_retained)
726            .expect("second retained live event should validate");
727    }
728
729    #[test]
730    fn live_lag_gap_at_stream_start_uses_valid_conservative_cursor() {
731        let record = RuntimeSessionRecord::new("lag-at-start-test", 2, true);
732        let session = RuntimeSession::default();
733        publish_session_event(
734            &record,
735            RuntimeSessionEventKind::Snapshot,
736            &session,
737            Vec::new(),
738        );
739
740        let gap = session_lag_gap_event(&record, 0);
741
742        assert_eq!(gap.sequence, 1);
743        assert_eq!(gap.replay.gap.as_ref().unwrap().expected_sequence, 1);
744        assert_eq!(gap.replay.gap.as_ref().unwrap().actual_sequence, 2);
745        validate_runtime_session_event(&gap).expect("start gap event should validate");
746    }
747
748    #[test]
749    fn high_water_filter_drops_replayed_live_duplicates() {
750        let record = RuntimeSessionRecord::new("high-water-test", 4, true);
751        let session = RuntimeSession::default();
752        publish_session_event(
753            &record,
754            RuntimeSessionEventKind::Snapshot,
755            &session,
756            Vec::new(),
757        );
758        let replay =
759            capture_session_replay(&record, Some(0), session_snapshot_event(&record, &session));
760        let first_event = record
761            .event_store
762            .lock()
763            .expect("event store should not be poisoned")[0]
764            .clone();
765
766        assert_eq!(replay.high_water_sequence, 1);
767        assert!(
768            session_broadcast_event_after_high_water(
769                Ok(first_event),
770                record.clone(),
771                replay.high_water_sequence
772            )
773            .is_none()
774        );
775
776        publish_session_event(
777            &record,
778            RuntimeSessionEventKind::Snapshot,
779            &session,
780            Vec::new(),
781        );
782        let second_event = record
783            .event_store
784            .lock()
785            .expect("event store should not be poisoned")[1]
786            .clone();
787        assert!(
788            session_broadcast_event_after_high_water(
789                Ok(second_event),
790                record,
791                replay.high_water_sequence
792            )
793            .is_some()
794        );
795    }
796
797    #[test]
798    fn event_cursor_reads_last_event_id_header() {
799        let mut headers = HeaderMap::new();
800        headers.insert("last-event-id", HeaderValue::from_static("41"));
801
802        assert_eq!(event_cursor_from_headers(&headers), Some(41));
803        assert_eq!(event_cursor_from_headers(&HeaderMap::new()), None);
804    }
805
806    #[test]
807    fn session_info_matches_contract_shape() {
808        let endpoint = RuntimeEndpointConfig::new("127.0.0.1".to_owned(), 3761);
809        let profile = crate::sidecar::runtime_connection_profile(&endpoint, "unix-ms:1");
810        let record = RuntimeSessionRegistry::dry_preview().default_record();
811
812        let response = record.info_response(profile);
813
814        assert_eq!(response.session_id, DEFAULT_SESSION_ID);
815        skenion_contracts::validate_runtime_session_info_response(&response)
816            .expect("session info should validate");
817    }
818
819    #[test]
820    fn session_info_preserves_snapshot_diagnostics() {
821        let endpoint = RuntimeEndpointConfig::new("127.0.0.1".to_owned(), 3761);
822        let profile = crate::sidecar::runtime_connection_profile(&endpoint, "unix-ms:1");
823        let record = RuntimeSessionRegistry::dry_preview().default_record();
824        record
825            .session
826            .write()
827            .expect("runtime session lock should not be poisoned")
828            .validate_current();
829
830        let response = record.info_response(profile);
831
832        assert_eq!(response.diagnostics.len(), 1);
833        assert_eq!(
834            response.diagnostics[0]["message"],
835            "no project loaded in runtime session"
836        );
837    }
838}