nornir 0.5.2

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Iceberg writer + reader for **saga record/replay** (`saga_events`, EPIC SAGA
//! / task #25) — the production sibling of [`super::test_results`].
//!
//! The PURE model ([`SagaEvent`], [`EventKind`], [`ReplayPlan`], [`ReplayStep`],
//! the [`SagaSink`] trait) lives in the lean [`nornir_saga`] crate and is
//! **re-exported here**; this module keeps only the Iceberg-coupled write/read
//! and the [`IcebergSagaSink`] implementation over the warehouse.
//!
//! Write path: [`append_saga_events`] appends one Iceberg snapshot per drain.
//! Each event carries its own `session_id` + monotonic `seq`, so a batch is just
//! whatever the recorder drained.
//!
//! Read path: [`query_saga_events`] scans the table, scopes by `session_id` (or
//! all), and returns events sorted by `(session_id, seq)`. [`list_saga_sessions`]
//! rolls them up into one [`SagaSessionSummary`] per session (the viz Sessions
//! pane's row), and [`session_replay_plan`] hands back the [`ReplayPlan`] for one
//! session.
//!
//! Schema: [`super::iceberg_schema::saga_events`] (17 columns).

use std::collections::BTreeMap;
use std::sync::Arc;

use anyhow::{anyhow, Result};
use arrow::array::{Array, Int64Array, RecordBatch, StringArray, TimestampMicrosecondArray};
use iceberg::arrow::schema_to_arrow_schema;
use iceberg::Catalog;
use sha2::{Digest, Sha256};

use super::iceberg::{append_batch, IcebergWarehouse, TABLE_SAGA_EVENTS};

// ─── re-export the pure model from the lean crate ──────────────────────────
pub use nornir_saga::analysis::{frustration_by_session, NavFunnel, SessionFrustration};
pub use nornir_saga::event::{EventKind, SagaEvent, SessionCtx};
pub use nornir_saga::replay::{ReplayPlan, ReplayStep, StepKind};
pub use nornir_saga::sink::SagaSink;
// The process-global capture buffer the viz nav/click choke feeds (feature
// `saga`; no-ops otherwise). Re-exported so integration tests (which don't dep
// `nornir-saga` directly) can drain what the viz recorded.
pub use nornir_saga::{drain_saga_events, record};

// Column indices match `iceberg_schema::saga_events` field order.
const COL_SESSION_ID: usize = 0;
const COL_SEQ: usize = 1;
const COL_TS_MICROS: usize = 2;
const COL_KIND: usize = 3;
const COL_ROUTE: usize = 4;
const COL_COMPONENT: usize = 5;
const COL_ACTION: usize = 6;
const COL_DETAIL: usize = 7;
const COL_STATE_JSON: usize = 8;
const COL_LEVEL: usize = 9;
const COL_SPAN_ID: usize = 10;
const COL_PARENT: usize = 11;
const COL_APP_USER: usize = 12;
const COL_APP: usize = 13;
const COL_APP_VERSION: usize = 14;
const COL_GIT_SHA: usize = 15;
const COL_SHA: usize = 16;

/// The sha256 of an event's canonical payload (the replay-relevant fields) — the
/// `sha` column, used for integrity + dedup. Stable across runs of the same
/// recorded step.
pub fn event_sha(e: &SagaEvent) -> String {
    let mut h = Sha256::new();
    h.update(e.session_id.as_bytes());
    h.update([0]);
    h.update(e.seq.to_le_bytes());
    h.update(e.kind.as_str().as_bytes());
    h.update([0]);
    h.update(e.route.as_bytes());
    h.update([0]);
    h.update(e.component.as_bytes());
    h.update([0]);
    h.update(e.action.as_bytes());
    h.update([0]);
    h.update(e.state_json.as_bytes());
    format!("{:x}", h.finalize())
}

/// Append a batch of captured `saga_events`. An empty slice is a no-op success.
///
/// The table is partitioned by `session_id`, and skade appends one partition at
/// a time, so a process-wide drain that mixes sessions is split into one
/// per-session snapshot (each a single partition). Within a session the order is
/// preserved by the `seq` column the recorder stamps.
pub async fn append_saga_events(wh: &IcebergWarehouse, events: &[SagaEvent]) -> Result<()> {
    if events.is_empty() {
        return Ok(());
    }
    // Group by session so each append is a single `session_id` partition.
    let mut by_session: BTreeMap<&str, Vec<&SagaEvent>> = BTreeMap::new();
    for e in events {
        by_session.entry(e.session_id.as_str()).or_default().push(e);
    }
    for (_session, batch) in by_session {
        append_one_session(wh, &batch).await?;
    }
    Ok(())
}

/// Append one session's events (all sharing one `session_id` → one partition).
async fn append_one_session(wh: &IcebergWarehouse, events: &[&SagaEvent]) -> Result<()> {
    if events.is_empty() {
        return Ok(());
    }
    let ident = wh.table_ident(TABLE_SAGA_EVENTS);
    let table = wh.catalog().load_table(&ident).await?;
    let arrow_schema = Arc::new(schema_to_arrow_schema(table.metadata().current_schema())?);

    let s = |f: fn(&SagaEvent) -> String| -> Arc<dyn Array> {
        Arc::new(StringArray::from(events.iter().map(|e| f(e)).collect::<Vec<_>>()))
    };

    let cols: Vec<Arc<dyn Array>> = vec![
        s(|e| e.session_id.clone()),
        Arc::new(Int64Array::from(events.iter().map(|e| e.seq as i64).collect::<Vec<_>>())),
        Arc::new(
            TimestampMicrosecondArray::from(
                events.iter().map(|e| e.ts_micros as i64).collect::<Vec<_>>(),
            )
            .with_timezone("+00:00"),
        ),
        s(|e| e.kind.as_str().to_string()),
        s(|e| e.route.clone()),
        s(|e| e.component.clone()),
        s(|e| e.action.clone()),
        s(|e| e.detail.clone()),
        s(|e| e.state_json.clone()),
        s(|e| e.level.clone()),
        s(|e| e.span_id.clone()),
        s(|e| e.parent.clone()),
        s(|e| e.user.clone()),
        s(|e| e.app.clone()),
        s(|e| e.app_version.clone()),
        s(|e| e.git_sha.clone()),
        s(event_sha),
    ];
    let batch = RecordBatch::try_new(arrow_schema, cols)?;
    append_batch(wh.catalog(), table, batch).await?;
    Ok(())
}

/// Which sessions / events a [`query_saga_events`] read returns.
#[derive(Debug, Clone)]
pub enum SagaSelector {
    /// One session's events.
    Session(String),
    /// Every event in the table.
    All,
}

/// Read saga events, scoped by `sel`, returned sorted by `(session_id, seq)`.
pub async fn query_saga_events(
    wh: &IcebergWarehouse,
    sel: &SagaSelector,
) -> Result<Vec<SagaEvent>> {
    // Blank/torn Iceberg metadata JSON → 0 rows, never a JSON-EOF crash (load+read).
    let batches: Vec<RecordBatch> =
        super::iceberg::load_and_read_all(wh, TABLE_SAGA_EVENTS).await?;

    let mut out: Vec<SagaEvent> = Vec::new();
    for b in &batches {
        let session_id = col_str(b, COL_SESSION_ID)?;
        let seq = col_i64(b, COL_SEQ)?;
        let ts = col_ts(b, COL_TS_MICROS)?;
        let kind = col_str(b, COL_KIND)?;
        let route = col_str(b, COL_ROUTE)?;
        let component = col_str(b, COL_COMPONENT)?;
        let action = col_str(b, COL_ACTION)?;
        let detail = col_str(b, COL_DETAIL)?;
        let state_json = col_str(b, COL_STATE_JSON)?;
        let level = col_str(b, COL_LEVEL)?;
        let span_id = col_str(b, COL_SPAN_ID)?;
        let parent = col_str(b, COL_PARENT)?;
        let app_user = col_str(b, COL_APP_USER)?;
        let app = col_str(b, COL_APP)?;
        let app_version = col_str(b, COL_APP_VERSION)?;
        let git_sha = col_str(b, COL_GIT_SHA)?;
        let _sha = col_str(b, COL_SHA)?; // integrity column; not part of the model.
        for i in 0..b.num_rows() {
            let row = SagaEvent {
                seq: seq.value(i) as u64,
                ts_micros: ts.value(i) as u64,
                session_id: session_id.value(i).to_string(),
                user: app_user.value(i).to_string(),
                kind: EventKind::parse(kind.value(i)).unwrap_or(EventKind::Log),
                route: route.value(i).to_string(),
                component: component.value(i).to_string(),
                action: action.value(i).to_string(),
                detail: detail.value(i).to_string(),
                state_json: state_json.value(i).to_string(),
                level: level.value(i).to_string(),
                span_id: span_id.value(i).to_string(),
                parent: parent.value(i).to_string(),
                app: app.value(i).to_string(),
                app_version: app_version.value(i).to_string(),
                git_sha: git_sha.value(i).to_string(),
            };
            let keep = match sel {
                SagaSelector::Session(id) => &row.session_id == id,
                SagaSelector::All => true,
            };
            if keep {
                out.push(row);
            }
        }
    }
    out.sort_by(|a, b| (&a.session_id, a.seq).cmp(&(&b.session_id, b.seq)));
    Ok(out)
}

/// One row in the viz Sessions pane: a recorded session rolled up — its id, app,
/// user, event + step counts, whether it's replayable, and when it ran.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SagaSessionSummary {
    pub session_id: String,
    pub app: String,
    pub user: String,
    pub git_sha: String,
    /// Total captured events (all kinds).
    pub event_count: usize,
    /// Actionable (replayable) steps — `nav` + `click`.
    pub step_count: usize,
    /// Distinct error events captured in the session.
    pub error_count: usize,
    /// Earliest capture timestamp (micros) — when the session started.
    pub started_micros: u64,
    /// Whether the session has at least one replayable step.
    pub replayable: bool,
    /// Whether the session is flagged **stuck** — a rage-click cluster or a route
    /// the user hit repeated errors on (see [`SessionFrustration`]). Painful
    /// sessions float to the top of the list so a dev triages them first.
    pub stuck: bool,
    /// A monotone frustration score for ranking (higher = more painful). Only its
    /// ordering is meaningful; drives the "float to top" sort.
    pub frustration_score: u32,
}

/// Roll a flat (sorted) event list up into one summary per session, ordered by
/// `started_micros` (newest first — the viz lists the most recent session on top).
pub fn summarize_sessions(events: &[SagaEvent]) -> Vec<SagaSessionSummary> {
    let mut by_session: BTreeMap<String, SagaSessionSummary> = BTreeMap::new();
    for e in events {
        let s = by_session
            .entry(e.session_id.clone())
            .or_insert_with(|| SagaSessionSummary {
                session_id: e.session_id.clone(),
                app: e.app.clone(),
                user: e.user.clone(),
                git_sha: e.git_sha.clone(),
                event_count: 0,
                step_count: 0,
                error_count: 0,
                started_micros: e.ts_micros,
                replayable: false,
                stuck: false,
                frustration_score: 0,
            });
        s.event_count += 1;
        if e.kind.is_actionable() {
            s.step_count += 1;
            s.replayable = true;
        }
        if e.kind == EventKind::Error {
            s.error_count += 1;
        }
        if e.ts_micros > 0 && (s.started_micros == 0 || e.ts_micros < s.started_micros) {
            s.started_micros = e.ts_micros;
        }
        // Keep the first non-empty identity fields seen.
        if s.app.is_empty() {
            s.app = e.app.clone();
        }
        if s.user.is_empty() {
            s.user = e.user.clone();
        }
    }
    // Fold in the frustration signals (rage-click clusters + stuck routes) so a
    // painful session is flagged + scored. Same events, one extra pass.
    for fr in frustration_by_session(events) {
        if let Some(s) = by_session.get_mut(&fr.session_id) {
            s.stuck = fr.is_stuck;
            s.frustration_score = fr.score;
        }
    }

    let mut out: Vec<SagaSessionSummary> = by_session.into_values().collect();
    // Float the painful sessions to the top (highest frustration first), then the
    // most recent, then by id for a stable order — a dev triages the stuck
    // sessions before the calm ones.
    out.sort_by(|a, b| {
        b.frustration_score
            .cmp(&a.frustration_score)
            .then(b.started_micros.cmp(&a.started_micros))
            .then(a.session_id.cmp(&b.session_id))
    });
    out
}

/// List recorded sessions in the warehouse as viz-pane rows (newest first).
pub async fn list_saga_sessions(wh: &IcebergWarehouse) -> Result<Vec<SagaSessionSummary>> {
    let events = query_saga_events(wh, &SagaSelector::All).await?;
    Ok(summarize_sessions(&events))
}

/// The [`ReplayPlan`] for one session — read its events back, build the plan.
pub async fn session_replay_plan(
    wh: &IcebergWarehouse,
    session_id: &str,
) -> Result<ReplayPlan> {
    let events = query_saga_events(wh, &SagaSelector::Session(session_id.to_string())).await?;
    Ok(ReplayPlan::for_session(session_id, &events))
}

/// The **nav-path / funnel** for one session (the `nornir saga path <session>`
/// verb): read its `saga_events` back and fold the `nav` stream into an ordered
/// route [`NavFunnel`]. An unknown/empty session yields an empty funnel (never an
/// error) so the CLI prints a clear "no events" message instead of panicking.
pub async fn session_nav_funnel(
    wh: &IcebergWarehouse,
    session_id: &str,
) -> Result<NavFunnel> {
    let events = query_saga_events(wh, &SagaSelector::Session(session_id.to_string())).await?;
    Ok(NavFunnel::from_events(&events))
}

/// The warehouse-backed [`SagaSink`]: appends captured events to the Iceberg
/// `saga_events` table. Leaf apps with no warehouse use `nornir_saga`'s
/// `JsonFileSink` / `NullSink` instead.
pub struct IcebergSagaSink<'a> {
    wh: &'a IcebergWarehouse,
}

impl<'a> IcebergSagaSink<'a> {
    pub fn new(wh: &'a IcebergWarehouse) -> Self {
        Self { wh }
    }
}

impl SagaSink for IcebergSagaSink<'_> {
    fn write(&self, events: &[SagaEvent]) -> Result<()> {
        // The warehouse's block_on bridges the sync SagaSink trait to the async
        // Iceberg writer (the rest of nornir's CLI is sync over block_on too).
        self.wh.block_on(append_saga_events(self.wh, events))
    }
}

/// Bridge a UI-movement recording ([`nornir_saga::ui::Saga`]) into the warehouse
/// `saga_events` model — the `Nav`/`Click` movements become replayable
/// [`SagaEvent`]s (see [`nornir_saga::ui::Saga::to_saga_events`]). The seam that
/// lets a web/egui `Saga` capture flow into the same `saga_events` table + replay
/// path the native recorder feeds.
pub fn saga_from_ui(saga: &nornir_saga::ui::Saga) -> Vec<SagaEvent> {
    saga.to_saga_events()
}

// ─── column helpers ──────────────────────────────────────────────────────

fn col_str(b: &RecordBatch, idx: usize) -> Result<&StringArray> {
    b.column(idx)
        .as_any()
        .downcast_ref::<StringArray>()
        .ok_or_else(|| anyhow!("saga_events col {idx} is not StringArray"))
}

fn col_i64(b: &RecordBatch, idx: usize) -> Result<&Int64Array> {
    b.column(idx)
        .as_any()
        .downcast_ref::<Int64Array>()
        .ok_or_else(|| anyhow!("saga_events col {idx} is not Int64Array"))
}

fn col_ts(b: &RecordBatch, idx: usize) -> Result<&TimestampMicrosecondArray> {
    b.column(idx)
        .as_any()
        .downcast_ref::<TimestampMicrosecondArray>()
        .ok_or_else(|| anyhow!("saga_events col {idx} is not TimestampMicrosecondArray"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ev(session: &str, seq: u64, kind: EventKind, comp: &str) -> SagaEvent {
        let ctx = SessionCtx::new(session, "rickard", "njord", "0.9.0", "abc123");
        let mut e = match kind {
            EventKind::Nav => SagaEvent::nav("/home", comp, "open", r#"{"v":1}"#),
            EventKind::Click => SagaEvent::click("/home", comp, "submit", r#"{"v":2}"#),
            EventKind::Error => SagaEvent::error(comp, "boom"),
            EventKind::Log => SagaEvent::log("info", "noise"),
            EventKind::State => SagaEvent::state(comp, r#"{"v":3}"#),
        }
        .in_session(&ctx);
        e.seq = seq;
        e.ts_micros = 1000 + seq;
        e
    }

    #[test]
    fn ui_saga_bridges_and_round_trips_through_the_warehouse() {
        use nornir_saga::ui::{Saga, UiMsg};

        // A UI-movement recording (web/egui) with 2 actionable + 2 noise moves.
        let saga = Saga::new("checkout")
            .push(UiMsg::nav("/checkout").at(0).with_state(r#"{"step":1}"#))
            .push(UiMsg::pointer_move(1.0, 2.0).at(5))
            .push(UiMsg::click(3.0, 4.0, "💳 Pay").at(10))
            .push(UiMsg::key("Enter").at(15));
        let mut events = saga_from_ui(&saga);
        assert_eq!(events.len(), 2, "only Nav + Click bridge across");

        // Stamp identity + seq so they group into one session, then persist +
        // read back through the same warehouse path the native recorder uses.
        let ctx = SessionCtx::new("ui-sess", "rickard", "njord", "0.9.0", "abc123");
        for (i, e) in events.iter_mut().enumerate() {
            *e = e.clone().in_session(&ctx);
            e.seq = i as u64;
            e.ts_micros = 1000 + i as u64;
        }

        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        IcebergSagaSink::new(&wh).write(&events).unwrap();

        // The session lists + its replay plan carries exactly the nav+click steps.
        let plan = wh
            .block_on(session_replay_plan(&wh, "ui-sess"))
            .unwrap();
        assert_eq!(plan.steps.len(), 2, "nav + click → 2 replay steps");
        assert_eq!(plan.steps[0].route, "/checkout");
        assert_eq!(plan.steps[1].component, "💳 Pay");
        assert!(plan.is_replayable());
    }

    #[test]
    fn append_query_round_trips_and_scopes() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();

        let sess_a = vec![
            ev("sA", 0, EventKind::Nav, "Dashboard"),
            ev("sA", 1, EventKind::Log, "log"),
            ev("sA", 2, EventKind::Click, "Submit"),
        ];
        let sess_b = vec![
            ev("sB", 3, EventKind::Nav, "Map"),
            ev("sB", 4, EventKind::Error, "Map"),
        ];
        wh.block_on(append_saga_events(&wh, &sess_a)).unwrap();
        wh.block_on(append_saga_events(&wh, &sess_b)).unwrap();

        // Session scope returns just one journey, sorted by seq.
        let a = wh
            .block_on(query_saga_events(&wh, &SagaSelector::Session("sA".into())))
            .unwrap();
        assert_eq!(a.len(), 3);
        assert!(a.windows(2).all(|w| w[0].seq < w[1].seq), "sorted by seq");
        let click = a.iter().find(|e| e.component == "Submit").unwrap();
        assert_eq!(click.kind, EventKind::Click);
        assert_eq!(click.state_json, r#"{"v":2}"#, "state round-trips exactly");
        assert_eq!(click.app, "njord");

        // All scope sees both sessions.
        let all = wh.block_on(query_saga_events(&wh, &SagaSelector::All)).unwrap();
        assert_eq!(all.len(), 5);
    }

    #[test]
    fn summarize_and_replay_plan_from_warehouse() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        let events = vec![
            ev("sA", 0, EventKind::Nav, "Dashboard"),
            ev("sA", 1, EventKind::Log, "noise"),
            ev("sA", 2, EventKind::Click, "Submit"),
            ev("sB", 3, EventKind::Error, "Map"),
        ];
        wh.block_on(append_saga_events(&wh, &events)).unwrap();

        let sessions = wh.block_on(list_saga_sessions(&wh)).unwrap();
        assert_eq!(sessions.len(), 2);
        let a = sessions.iter().find(|s| s.session_id == "sA").unwrap();
        assert_eq!(a.event_count, 3);
        assert_eq!(a.step_count, 2, "nav + click are replayable steps");
        assert!(a.replayable);
        let b = sessions.iter().find(|s| s.session_id == "sB").unwrap();
        assert_eq!(b.step_count, 0, "an error-only session has no steps");
        assert_eq!(b.error_count, 1);
        assert!(!b.replayable);

        // The replay plan for sA is nav→click in capture order.
        let plan = wh.block_on(session_replay_plan(&wh, "sA")).unwrap();
        assert_eq!(plan.steps.len(), 2);
        assert_eq!(plan.steps[0].kind, StepKind::Navigate);
        assert_eq!(plan.steps[1].kind, StepKind::Activate);
    }

    #[test]
    fn session_nav_funnel_from_warehouse() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        let ctx = SessionCtx::new("sF", "rickard", "njord", "0.9.0", "abc123");
        let nav = |route: &str, seq: u64| {
            let mut e = SagaEvent::nav(route, "Page", "open", "{}").in_session(&ctx);
            e.seq = seq;
            e.ts_micros = 1000 + seq;
            e
        };
        // /a → /b → /c, deterministic order.
        let events = vec![nav("/a", 0), nav("/b", 1), nav("/c", 2)];
        wh.block_on(append_saga_events(&wh, &events)).unwrap();

        let funnel = wh.block_on(session_nav_funnel(&wh, "sF")).unwrap();
        assert_eq!(funnel.session_count, 1);
        assert_eq!(
            funnel.steps.iter().map(|s| s.route.as_str()).collect::<Vec<_>>(),
            vec!["/a", "/b", "/c"],
            "ordered route funnel read back from the warehouse"
        );

        // An unknown session is an EMPTY funnel, not an error (CLI prints "no events").
        let empty = wh.block_on(session_nav_funnel(&wh, "ghost")).unwrap();
        assert_eq!(empty.session_count, 0);
        assert!(empty.steps.is_empty());
    }

    #[test]
    fn iceberg_sink_writes_via_trait() {
        let dir = tempfile::tempdir().unwrap();
        let wh = IcebergWarehouse::open(dir.path()).unwrap();
        let sink = IcebergSagaSink::new(&wh);
        sink.write(&[ev("sS", 0, EventKind::Nav, "Home")]).unwrap();
        let back = wh
            .block_on(query_saga_events(&wh, &SagaSelector::Session("sS".into())))
            .unwrap();
        assert_eq!(back.len(), 1);
        assert_eq!(back[0].route, "/home");
    }

    #[test]
    fn stuck_sessions_float_to_the_top_of_the_summary() {
        // A calm session (started LATER) and a rage-click session (started
        // EARLIER). Recency alone would rank the calm one first; the frustration
        // score must override that and float the stuck session to the top.
        let calm = SessionCtx::new("calm", "u", "njord", "1.0", "sha");
        let rage = SessionCtx::new("rage", "u", "njord", "1.0", "sha");
        let mut events = Vec::new();
        // rage: 3 consecutive clicks on one component → a rage cluster.
        for s in 0..3u64 {
            let mut e = SagaEvent::click("/x", "Retry", "retry", "{}").in_session(&rage);
            e.seq = s;
            e.ts_micros = 100 + s; // earliest
            events.push(e);
        }
        // calm: a plain nav, later in wall-clock.
        let mut e = SagaEvent::nav("/home", "Home", "open", "{}").in_session(&calm);
        e.seq = 10;
        e.ts_micros = 9000; // most recent
        events.push(e);

        let summaries = summarize_sessions(&events);
        assert_eq!(summaries.len(), 2);
        assert_eq!(
            summaries[0].session_id, "rage",
            "the stuck session floats above the more-recent calm one"
        );
        assert!(summaries[0].stuck, "rage session flagged stuck");
        assert!(summaries[0].frustration_score > 0);
        assert!(!summaries[1].stuck, "calm session not stuck");
        assert_eq!(summaries[1].frustration_score, 0);
    }

    #[test]
    fn event_sha_is_stable_and_payload_sensitive() {
        let a = ev("sA", 0, EventKind::Nav, "Dashboard");
        let same = ev("sA", 0, EventKind::Nav, "Dashboard");
        assert_eq!(event_sha(&a), event_sha(&same), "same payload → same sha");
        let other = ev("sA", 0, EventKind::Click, "Dashboard");
        assert_ne!(event_sha(&a), event_sha(&other), "different kind → different sha");
    }
}