fv-streams-ops 0.2.0

Stateful streaming operators for FusionVault Streams: event-time tumbling and sliding windows with keyed incremental aggregation, session windows, stream joins, top-N and last-N, watermarks and snapshots. Pure and synchronous — no I/O, no runtime.
Documentation
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
//! SESSION windows — the stateful operator behind Nexmark Q11.
//!
//! Unlike fixed tumbling/sliding windows, a session window has DYNAMIC bounds: per group key, events
//! within `gap` of each other belong to one session; a gap longer than `gap` starts a new one. An
//! event that lands between two existing sessions (bridging them) MERGES them into one. A session is
//! `[first, last + gap)`; it fires (emits + evicts) once the watermark passes `last + gap` (no further
//! event can extend it). Watermark = min across partitions − lateness (the same rule as the windowed
//! aggregator and the join). Pure + synchronous; implements [`WindowOperator`](crate::WindowOperator)
//! so the stream worker drives it through the same path as `WindowAgg`.

use std::collections::HashMap;

use fv_value::Value;

use crate::acc::Acc;
use crate::watermark::Watermark;
use crate::{Agg, WindowOperator, WindowRow};

/// One open session for a group key: its event-time span and running accumulator.
struct Session {
    first: i64,
    last: i64,
    acc: Acc,
}

/// All of one group key's open sessions (T2: the key's emission values live HERE, once per key —
/// not inside every session's accumulator).
struct Bucket {
    vals: Vec<Value>,
    sessions: Vec<Session>,
}

/// A session-window keyed aggregator.
pub struct SessionAgg {
    gap_ms: i64,
    group_by: Vec<String>,
    aggs: Vec<Agg>,
    /// Keyed by the composite group-key string (see `acc::composite_of`).
    sessions: HashMap<String, Bucket>,
    /// Precomputed `needs_sets(&aggs)` — per-event accumulator creation never rescans the agg list.
    with_sets: bool,
    with_welford: bool,
    wm: Watermark,
    fired_through: i64,
    late_dropped: u64,
}

impl SessionAgg {
    /// Sessions close after `gap_ms` of inactivity; `allowed_lateness_ms` extra grace before firing.
    pub fn new(gap_ms: i64, allowed_lateness_ms: i64, group_by: Vec<String>, aggs: Vec<Agg>) -> Self {
        assert!(gap_ms > 0, "session gap must be > 0");
        let with_sets = crate::acc::needs_sets(&aggs);
        let with_welford = crate::acc::needs_welford(&aggs);
        Self {
            gap_ms,
            group_by,
            aggs,
            sessions: HashMap::new(),
            with_sets,
            with_welford,
            wm: Watermark::new(allowed_lateness_ms),
            fired_through: i64::MIN,
            late_dropped: 0,
        }
    }

    /// Enable bounded idleness: a partition silent longer than `idle_timeout_ms` (processing time)
    /// stops holding the watermark back. `<= 0` leaves it disabled. See `Watermark`.
    pub fn with_idle_timeout(mut self, idle_timeout_ms: i64) -> Self {
        self.wm = self.wm.with_idle_timeout(idle_timeout_ms);
        self
    }

    pub fn watermark(&self, now_ms: i64) -> i64 {
        self.wm.current(now_ms)
    }

    pub fn late_dropped(&self) -> u64 {
        self.late_dropped
    }

    fn fire_through(&mut self, wm: i64) -> Vec<WindowRow> {
        if wm == i64::MIN {
            return Vec::new();
        }
        let out = self.fire(|end| end <= wm);
        self.fired_through = self.fired_through.max(wm);
        out
    }

    fn fire(&mut self, closed: impl Fn(i64) -> bool) -> Vec<WindowRow> {
        let gap = self.gap_ms;
        let aggs = &self.aggs;
        let mut out = Vec::new();
        for bucket in self.sessions.values_mut() {
            let mut i = 0;
            while i < bucket.sessions.len() {
                if closed(bucket.sessions[i].last + gap) {
                    let s = bucket.sessions.remove(i);
                    out.push(WindowRow {
                        window_start: s.first,
                        window_end: s.last + gap,
                        aggs: s.acc.finalize_aggs(aggs),
                        key: bucket.vals.clone(),
                    });
                } else {
                    i += 1;
                }
            }
        }
        self.sessions.retain(|_, b| !b.sessions.is_empty());
        out.sort_by_key(|w| w.window_start);
        out
    }

    // ── snapshot/restore (see `snapshot` module). ──

    fn cfg_fingerprint(&self) -> String {
        format!(
            "gap={};group_by={:?};aggs={:?};{}",
            self.gap_ms,
            self.group_by,
            self.aggs,
            self.wm.cfg_fingerprint()
        )
    }

    /// Serialize the DYNAMIC state: open sessions, watermark timers, fired-through, late count.
    /// FORMAT 2 (T2): the key's composite + emission values once per bucket, accumulators as compact
    /// tuples.
    pub fn snapshot(&self) -> Vec<u8> {
        use serde_json::json;
        let sessions: Vec<serde_json::Value> = self
            .sessions
            .iter()
            .map(|(composite, bucket)| {
                let b: Vec<serde_json::Value> = bucket
                    .sessions
                    .iter()
                    .map(|s| json!([s.first, s.last, crate::snapshot::acc_to_json_v2(&s.acc)]))
                    .collect();
                json!([
                    composite,
                    bucket.vals.iter().map(fv_value::value_to_json).collect::<Vec<_>>(),
                    b
                ])
            })
            .collect();
        crate::snapshot::envelope(
            "session",
            &self.cfg_fingerprint(),
            json!({
                "format": 2,
                "sessions": sessions,
                "wm": self.wm.state_to_json(),
                "fired_through": self.fired_through,
                "late_dropped": self.late_dropped,
            }),
        )
    }

    /// Restore dynamic state into this freshly-configured aggregator (config mismatch refused).
    /// DUAL-READ: format 2 (current) and the pre-T2 format (group key as a string vector + the
    /// emission values embedded in every acc) — old checkpoints MUST load correctly (refusing them
    /// would silently lose consumed-but-unfired rows).
    pub fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        let s = crate::snapshot::open_envelope("session", &self.cfg_fingerprint(), bytes)?;
        let v2 = s["format"].as_i64() == Some(2);
        let mut map = HashMap::new();
        for e in s["sessions"]
            .as_array()
            .ok_or("session snapshot: sessions not an array")?
        {
            if v2 {
                let a = e
                    .as_array()
                    .filter(|a| a.len() == 3)
                    .ok_or("session snapshot v2: bad entry")?;
                let composite = a[0].as_str().ok_or("session snapshot v2: bad composite")?.to_string();
                let vals: Vec<Value> = a[1]
                    .as_array()
                    .ok_or("session snapshot v2: bad key vals")?
                    .iter()
                    .map(fv_value::json_to_value)
                    .collect();
                let sessions: Vec<Session> = a[2]
                    .as_array()
                    .ok_or("session snapshot v2: bad bucket")?
                    .iter()
                    .map(|se| {
                        let t = se
                            .as_array()
                            .filter(|t| t.len() == 3)
                            .ok_or("session snapshot v2: bad session")?;
                        Ok(Session {
                            first: t[0].as_i64().ok_or("session snapshot v2: bad first")?,
                            last: t[1].as_i64().ok_or("session snapshot v2: bad last")?,
                            acc: crate::snapshot::acc_from_json_v2(&t[2])?,
                        })
                    })
                    .collect::<Result<_, String>>()?;
                map.insert(composite, Bucket { vals, sessions });
            } else {
                let a = e
                    .as_array()
                    .filter(|a| a.len() == 2)
                    .ok_or("session snapshot: bad entry")?;
                let gk: Vec<String> = a[0]
                    .as_array()
                    .ok_or("session snapshot: bad group key")?
                    .iter()
                    .map(|s| {
                        s.as_str()
                            .map(String::from)
                            .ok_or_else(|| "session snapshot: bad group key part".to_string())
                    })
                    .collect::<Result<_, _>>()?;
                let mut vals: Vec<Value> = Vec::new();
                let sessions: Vec<Session> = a[1]
                    .as_array()
                    .ok_or("session snapshot: bad bucket")?
                    .iter()
                    .map(|se| {
                        let t = se
                            .as_array()
                            .filter(|t| t.len() == 3)
                            .ok_or("session snapshot: bad session")?;
                        let (key, acc) = crate::snapshot::acc_from_json_v1(&t[2])?;
                        if vals.is_empty() {
                            vals = key;
                        }
                        Ok(Session {
                            first: t[0].as_i64().ok_or("session snapshot: bad first")?,
                            last: t[1].as_i64().ok_or("session snapshot: bad last")?,
                            acc,
                        })
                    })
                    .collect::<Result<_, String>>()?;
                map.insert(gk.join("\u{1}"), Bucket { vals, sessions });
            }
        }
        self.sessions = map;
        self.wm.load_state(&s["wm"])?;
        self.fired_through = s["fired_through"]
            .as_i64()
            .ok_or("session snapshot: missing fired_through")?;
        self.late_dropped = s["late_dropped"]
            .as_u64()
            .ok_or("session snapshot: missing late_dropped")?;
        Ok(())
    }
}

impl WindowOperator for SessionAgg {
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        self.wm.expect(partitions, now_ms);
    }

    fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, Value)]) -> bool {
        self.wm.observe(partition, event_ms);
        // Too old — even a fresh session for it would already be past the fired watermark.
        if self.fired_through != i64::MIN && event_ms + self.gap_ms <= self.fired_through {
            self.late_dropped += 1;
            return false;
        }
        let gap = self.gap_ms;
        let (n_aggs, with_sets, with_welford) = (self.aggs.len(), self.with_sets, self.with_welford);
        // One composite build per event; the emission values only when the key is first seen (T2).
        let composite = crate::acc::composite_of(row, &self.group_by);

        // Take this key's bucket OUT of the map so `self` is free for the accumulator helpers.
        let mut bucket = self.sessions.remove(&composite).unwrap_or_else(|| Bucket {
            vals: crate::acc::vals_of(row, &self.group_by),
            sessions: Vec::new(),
        });
        // Sessions this event joins (within `gap` of their span) — merge them all with the event.
        let hit: Vec<usize> = bucket
            .sessions
            .iter()
            .enumerate()
            .filter(|(_, s)| s.first - gap <= event_ms && event_ms <= s.last + gap)
            .map(|(i, _)| i)
            .collect();
        let mut merged = Session {
            first: event_ms,
            last: event_ms,
            acc: Acc::new(n_aggs, with_sets, with_welford),
        };
        for &i in hit.iter().rev() {
            let s = bucket.sessions.remove(i); // high-index-first keeps indices valid
            merged.first = merged.first.min(s.first);
            merged.last = merged.last.max(s.last);
            merged.acc.merge(&self.aggs, &s.acc);
        }
        merged.acc.add(&self.aggs, row);
        bucket.sessions.push(merged);
        self.sessions.insert(composite, bucket);
        true
    }

    fn advance(&mut self, now_ms: i64) -> Vec<WindowRow> {
        self.wm.tick(now_ms);
        let wm = self.wm.current(now_ms);
        self.fire_through(wm)
    }

    fn advance_to(&mut self, watermark_ms: i64) -> Vec<WindowRow> {
        let wm = self.wm.after_lateness(watermark_ms);
        self.fire_through(wm)
    }

    fn flush(&mut self) -> Vec<WindowRow> {
        self.fired_through = i64::MAX;
        self.fire(|_| true)
    }

    fn snapshot(&mut self) -> Vec<u8> {
        SessionAgg::snapshot(self)
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        SessionAgg::load_snapshot(self, bytes)
    }
}

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

    fn row(pairs: &[(&str, Value)]) -> Vec<(String, Value)> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }
    fn num(w: &WindowRow, alias: &str) -> f64 {
        match &w.aggs.iter().find(|(a, _)| a == alias).unwrap().1 {
            Value::Num(n) => *n,
            other => panic!("expected num for {alias}, got {other:?}"),
        }
    }

    #[test]
    fn events_within_gap_form_one_session() {
        let mut s = SessionAgg::new(
            1000,
            0,
            vec![],
            vec![Agg::count("n"), Agg::of(AggOp::Sum, "amount", "total")],
        );
        for (t, a) in [(100, 1.0), (500, 2.0), (1400, 3.0)] {
            s.push(0, t, &row(&[("amount", Value::Num(a))])); // each within 1000 of the previous
        }
        s.push(0, 5000, &row(&[("amount", Value::Num(9.0))])); // gap → new session + advances watermark
        let out = s.advance(0); // watermark 5000 → the first session (last 1400, end 2400) fires
        assert_eq!(out.len(), 1);
        assert_eq!((out[0].window_start, out[0].window_end), (100, 2400));
        assert_eq!(num(&out[0], "n"), 3.0);
        assert_eq!(num(&out[0], "total"), 6.0);
    }

    #[test]
    fn a_gap_starts_a_new_session() {
        let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
        s.push(0, 100, &row(&[]));
        s.push(0, 2000, &row(&[])); // 2000 - 100 = 1900 > gap 1000 → separate session
        s.push(0, 10_000, &row(&[])); // advance watermark past both
        let mut out = s.advance(0);
        out.sort_by_key(|w| w.window_start);
        assert_eq!(out.len(), 2, "two distinct sessions");
        assert_eq!(out[0].window_start, 100);
        assert_eq!(out[1].window_start, 2000);
    }

    #[test]
    fn a_bridging_event_merges_two_sessions() {
        let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
        s.push(0, 100, &row(&[])); // session A [100]
        s.push(0, 2500, &row(&[])); // session B [2500] (gap from A)
                                    // An event at 1500 is within gap of BOTH (A.last+gap=1100 ≥ 1500? no… ) → check merge when in range.
        s.push(0, 1000, &row(&[])); // within gap of A (100..1100) → extends A to [100,1000]
        s.push(0, 1900, &row(&[])); // within gap of A' (end 2000) AND B (start-gap 1500) → MERGES A'+B
        s.push(0, 10_000, &row(&[])); // advance watermark
        let out = s.advance(0);
        assert_eq!(out.len(), 1, "all merged into one session");
        assert_eq!((out[0].window_start, out[0].window_end), (100, 3500)); // first 100, last 2500 (+gap)
        assert_eq!(num(&out[0], "n"), 4.0, "all four events");
    }

    #[test]
    fn separate_keys_have_separate_sessions() {
        let mut s = SessionAgg::new(1000, 0, vec!["k".into()], vec![Agg::count("n")]);
        s.push(0, 100, &row(&[("k", Value::Str("a".into()))]));
        s.push(0, 200, &row(&[("k", Value::Str("b".into()))]));
        s.push(0, 300, &row(&[("k", Value::Str("a".into()))]));
        s.push(0, 10_000, &row(&[("k", Value::Str("a".into()))])); // advance watermark; also a new 'a' session
        let out = s.advance(0);
        let a = out
            .iter()
            .find(|w| w.key == vec![Value::Str("a".into())] && w.window_start == 100)
            .unwrap();
        let b = out.iter().find(|w| w.key == vec![Value::Str("b".into())]).unwrap();
        assert_eq!(num(a, "n"), 2.0);
        assert_eq!(num(b, "n"), 1.0);
    }

    #[test]
    fn multi_partition_watermark_holds_firing() {
        let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
        s.expect_partitions(&[0, 1], 0);
        s.push(0, 100, &row(&[]));
        s.push(0, 9000, &row(&[])); // partition 0 races ahead; partition 1 unseen
        assert!(s.advance(0).is_empty(), "unseen partition 1 pins the watermark");
        s.push(1, 9000, &row(&[]));
        assert!(!s.advance(0).is_empty(), "both seen → the first session fires");
    }

    #[test]
    fn flush_fires_all_open_sessions() {
        let mut s = SessionAgg::new(1000, 10_000, vec![], vec![Agg::count("n")]);
        s.push(0, 100, &row(&[]));
        s.push(0, 5000, &row(&[]));
        assert!(s.advance(0).is_empty(), "long lateness holds them open");
        assert_eq!(s.flush().len(), 2);
    }

    #[test]
    fn snapshot_restore_survives_a_bridging_merge_across_the_boundary() {
        // The hardest state to survive a crash: TWO open sessions in the snapshot, and the very next
        // event after restore bridges them into one. Restored must equal uninterrupted, byte for byte.
        let mk = || {
            let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
            s.expect_partitions(&[0], 0);
            s.push(0, 100, &row(&[]));
            s.push(0, 200, &row(&[])); // session A [100,200]
            s.push(0, 2000, &row(&[])); // session B [2000,2000] (gap > 1000 from A)
            s
        };
        let drive = |s: &mut SessionAgg| {
            s.push(0, 1100, &row(&[])); // within gap of BOTH A and B → bridges them
            s.push(0, 9000, &row(&[])); // advances the watermark past the merged session
            s.advance(0)
        };
        let mut a = mk();
        let fired_a = drive(&mut a);
        let snap = mk().snapshot();
        let mut b = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
        b.load_snapshot(&snap).expect("restore");
        let fired_b = drive(&mut b);
        assert_eq!(fired_a, fired_b, "restored run must fire byte-identically");
        // And the merge genuinely happened: one session [100, 3000) holding all 4 events.
        let m = fired_a
            .iter()
            .find(|w| w.window_start == 100)
            .expect("merged session fired");
        assert_eq!(m.window_end, 3000);
        assert_eq!(num(m, "n"), 4.0);
    }

    #[test]
    fn bounded_idleness_releases_sessions_held_by_a_silent_partition() {
        // Partition 1 produces once then goes silent; without an idle timeout its stale max pins the
        // watermark so partition 0's first session can't fire. With one, partition 1 goes idle.
        let mk = |idle_ms: i64| {
            let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
            if idle_ms > 0 {
                s = s.with_idle_timeout(idle_ms);
            }
            s.expect_partitions(&[0, 1], 0);
            s.push(0, 100, &row(&[]));
            s.push(1, 200, &row(&[])); // partition 1's only event
            s.advance(0); // stamp both active at processing-time 0
            s.push(0, 5000, &row(&[])); // partition 0 opens a later session; partition 1 stays silent
            s
        };
        assert!(
            mk(0).advance(6000).is_empty(),
            "no idle timeout → silent partition holds the session shut"
        );
        let out = mk(1000).advance(6000); // partition 1 idle since t=0 → partition 0 (max 5000) drives
        assert!(
            out.iter().any(|w| w.window_start == 100),
            "idle partition released → session [100,1100) fires"
        );
    }
}