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
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
//! — RANK operators: **top-N per key** ([`TopN`]) and **last-N per key** ([`LastN`]).
//!
//! Both are UNBOUNDED emit-on-change operators — the Nexmark q9/q18/q19 (rank) and q6 (ring) shapes —
//! equivalent to Flink's append-mode `ROW_NUMBER` under this engine's upsert model: instead of
//! retractions, a key's current results are re-emitted under DETERMINISTIC keys whenever its set
//! changes, and downstream last-wins converges. No watermark is involved: state per key is bounded
//! (n rows), so nothing ever needs time-based eviction for correctness.
//!
//! Both implement [`WindowOperator`](crate::WindowOperator) so the stream worker's entire plumbing —
//! per-partition instances, checkpoint/restore, keyBy, exactly-once — drives them unchanged:
//! `push` updates per-key state and queues changed keys; `advance` drains the queue (the `now_ms`
//! is ignored — there are no timers); `flush` drains it on shutdown. Emissions ride [`WindowRow`]
//! with `window_start`/`window_end` = 0 (unused; the worker lays rank rows out without window
//! columns).
//!
//! Determinism on replay: a key's rows arrive from ONE partition (co-partitioned input or keyBy), so
//! arrival order — the final tie-breaker — is the partition's log order, which replay reproduces.

use std::collections::{BTreeSet, HashMap, VecDeque};

use fv_value::Value;

use crate::acc::{as_num, value_key, Acc};
use crate::{snapshot, Agg, WindowOperator, WindowRow};

/// `true` if `a` outranks `b`. Total and deterministic: order column (desc/asc), then tie column
/// ascending, then arrival sequence ascending (first-seen wins among full ties).
fn outranks(descending: bool, a: &Ranked, b: &Ranked) -> bool {
    if a.order != b.order {
        return if descending {
            a.order > b.order
        } else {
            a.order < b.order
        };
    }
    if a.tie != b.tie {
        return a.tie < b.tie;
    }
    a.seq < b.seq
}

/// Extract a row's group-key: the stable composite string (map key) + the values (for emission).
fn group_key(row: &[(String, Value)], group_by: &[String]) -> (String, Vec<Value>) {
    let mut ks = String::new();
    let mut vals = Vec::with_capacity(group_by.len());
    for (i, g) in group_by.iter().enumerate() {
        let v = row.iter().find(|(k, _)| k == g).map(|(_, v)| v);
        if i > 0 {
            ks.push('\u{1}');
        }
        ks.push_str(&value_key(v));
        vals.push(v.cloned().unwrap_or(Value::Null));
    }
    (ks, vals)
}

// ── TopN ─────────────────────────────────────────────────────────────────────────────────────────

/// One buffered contender: its order/tie scalars (extracted once at push) + arrival sequence + row.
#[derive(Debug, Clone)]
struct Ranked {
    order: f64,
    tie: f64,
    seq: u64,
    row: Vec<(String, Value)>,
}

#[derive(Debug, Default)]
struct TopEntry {
    key: Vec<Value>,
    rows: Vec<Ranked>, // sorted best-first, len ≤ n
}

/// Top-N rows per group key, ordered by a numeric column (`descending` = biggest first — q9/q19), tie
/// broken by `tie_by` ascending (e.g. earliest wins — q9's dateTime) then by arrival order. Emits, on
/// every change to a key's set, that key's CURRENT rows 1..len with a 1-based `rank` (appended to the
/// emission key vector), as idempotent upserts.
pub struct TopN {
    group_by: Vec<String>,
    order_by: String,
    descending: bool,
    n: usize,
    tie_by: Option<String>,
    state: HashMap<String, TopEntry>,
    pending: BTreeSet<String>, // changed keys, drained in sorted order (deterministic emission order)
    seq: u64,
}

impl TopN {
    pub fn new(
        group_by: Vec<String>,
        order_by: impl Into<String>,
        descending: bool,
        n: usize,
        tie_by: Option<String>,
    ) -> Self {
        Self {
            group_by,
            order_by: order_by.into(),
            descending,
            n: n.max(1),
            tie_by,
            state: HashMap::new(),
            pending: BTreeSet::new(),
            seq: 0,
        }
    }

    fn cfg_fingerprint(&self) -> String {
        format!(
            "group_by={:?};order_by={};desc={};n={};tie_by={:?}",
            self.group_by, self.order_by, self.descending, self.n, self.tie_by
        )
    }

    fn push_row(&mut self, row: &[(String, Value)]) -> bool {
        let Some(order) = row
            .iter()
            .find(|(k, _)| k == &self.order_by)
            .and_then(|(_, v)| as_num(v))
        else {
            return false; // no numeric order value → cannot rank (caller counts the drop)
        };
        let tie = self
            .tie_by
            .as_ref()
            .and_then(|c| row.iter().find(|(k, _)| k == c).and_then(|(_, v)| as_num(v)))
            .unwrap_or(0.0);
        let cand = Ranked {
            order,
            tie,
            seq: self.seq,
            row: row.to_vec(),
        };
        self.seq += 1;
        let (ks, key_vals) = group_key(row, &self.group_by);
        let entry = self.state.entry(ks.clone()).or_insert_with(|| TopEntry {
            key: key_vals,
            rows: Vec::new(),
        });
        if entry.rows.len() >= self.n {
            let worst = entry.rows.last().expect("n >= 1");
            if !outranks(self.descending, &cand, worst) {
                return true; // consumed, but doesn't enter the top-n → nothing changes, no emission
            }
        }
        let pos = entry
            .rows
            .iter()
            .position(|r| outranks(self.descending, &cand, r))
            .unwrap_or(entry.rows.len());
        entry.rows.insert(pos, cand);
        entry.rows.truncate(self.n);
        self.pending.insert(ks);
        true
    }

    /// Emit every pending key's CURRENT ranks (1-based, appended to the key vector). Row columns
    /// exclude the group-by columns — the worker re-adds those from the key vector by name.
    fn drain(&mut self) -> Vec<WindowRow> {
        let mut out = Vec::new();
        for ks in std::mem::take(&mut self.pending) {
            let Some(entry) = self.state.get(&ks) else { continue };
            for (i, r) in entry.rows.iter().enumerate() {
                let mut key = entry.key.clone();
                key.push(Value::Num((i + 1) as f64));
                let aggs: Vec<(String, Value)> = r
                    .row
                    .iter()
                    .filter(|(k, _)| !self.group_by.contains(k))
                    .cloned()
                    .collect();
                out.push(WindowRow {
                    window_start: 0,
                    window_end: 0,
                    key,
                    aggs,
                });
            }
        }
        out
    }
}

impl WindowOperator for TopN {
    fn expect_partitions(&mut self, _partitions: &[i32], _now_ms: i64) {} // no timers, no watermark

    fn push(&mut self, _partition: i32, _event_ms: i64, row: &[(String, Value)]) -> bool {
        self.push_row(row)
    }

    fn advance(&mut self, _now_ms: i64) -> Vec<WindowRow> {
        self.drain()
    }

    fn advance_to(&mut self, _watermark_ms: i64) -> Vec<WindowRow> {
        self.drain()
    }

    fn flush(&mut self) -> Vec<WindowRow> {
        self.drain()
    }

    fn snapshot(&mut self) -> Vec<u8> {
        use serde_json::json;
        let entries: Vec<serde_json::Value> = self
            .state
            .iter()
            .map(|(ks, e)| {
                json!([
                    ks,
                    e.key.iter().map(fv_value::value_to_json).collect::<Vec<_>>(),
                    e.rows
                        .iter()
                        .map(|r| json!([r.order, r.tie, r.seq, snapshot::row_to_json(&r.row)]))
                        .collect::<Vec<_>>(),
                ])
            })
            .collect();
        let pending: Vec<&String> = self.pending.iter().collect();
        snapshot::envelope(
            "topn",
            &self.cfg_fingerprint(),
            json!({ "seq": self.seq, "entries": entries, "pending": pending }),
        )
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        let st = snapshot::open_envelope("topn", &self.cfg_fingerprint(), bytes)?;
        self.seq = st["seq"].as_u64().ok_or("topn: missing seq")?;
        self.state.clear();
        for e in st["entries"].as_array().ok_or("topn: missing entries")? {
            let t = e.as_array().filter(|a| a.len() == 3).ok_or("topn: bad entry")?;
            let ks = t[0].as_str().ok_or("topn: bad entry key")?.to_string();
            let key: Vec<Value> = t[1]
                .as_array()
                .ok_or("topn: bad key vals")?
                .iter()
                .map(fv_value::json_to_value)
                .collect();
            let mut rows = Vec::new();
            for r in t[2].as_array().ok_or("topn: bad rows")? {
                let q = r.as_array().filter(|a| a.len() == 4).ok_or("topn: bad ranked row")?;
                rows.push(Ranked {
                    order: q[0].as_f64().ok_or("topn: bad order")?,
                    tie: q[1].as_f64().ok_or("topn: bad tie")?,
                    seq: q[2].as_u64().ok_or("topn: bad seq")?,
                    row: snapshot::row_from_json(&q[3])?,
                });
            }
            self.state.insert(ks, TopEntry { key, rows });
        }
        self.pending = st["pending"]
            .as_array()
            .ok_or("topn: missing pending")?
            .iter()
            .map(|p| p.as_str().map(String::from).ok_or("topn: bad pending key".to_string()))
            .collect::<Result<_, _>>()?;
        Ok(())
    }
}

// ── LastN ────────────────────────────────────────────────────────────────────────────────────────

#[derive(Debug, Default)]
struct RingEntry {
    key: Vec<Value>,
    rows: VecDeque<Vec<(String, Value)>>, // arrival order, len ≤ n
}

/// The last n rows per group key (arrival order — q6's "last 10 closed auctions"), re-emitting the
/// standard Agg vocabulary computed over the ring on every update (key `l|<group>` worker-side).
pub struct LastN {
    group_by: Vec<String>,
    n: usize,
    aggs: Vec<Agg>,
    state: HashMap<String, RingEntry>,
    pending: BTreeSet<String>,
}

impl LastN {
    pub fn new(group_by: Vec<String>, n: usize, aggs: Vec<Agg>) -> Self {
        Self {
            group_by,
            n: n.max(1),
            aggs,
            state: HashMap::new(),
            pending: BTreeSet::new(),
        }
    }

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

    fn drain(&mut self) -> Vec<WindowRow> {
        let mut out = Vec::new();
        for ks in std::mem::take(&mut self.pending) {
            let Some(entry) = self.state.get(&ks) else { continue };
            // Recompute over the ring (≤ n rows) — simpler and exactly as correct as incremental
            // update-with-retraction, and n is small by construction.
            let mut acc = Acc::new(
                self.aggs.len(),
                crate::acc::needs_sets(&self.aggs),
                crate::acc::needs_welford(&self.aggs),
            );
            for r in &entry.rows {
                acc.add(&self.aggs, r);
            }
            out.push(WindowRow {
                window_start: 0,
                window_end: 0,
                key: entry.key.clone(),
                aggs: acc.finalize_aggs(&self.aggs),
            });
        }
        out
    }
}

impl WindowOperator for LastN {
    fn expect_partitions(&mut self, _partitions: &[i32], _now_ms: i64) {}

    fn push(&mut self, _partition: i32, _event_ms: i64, row: &[(String, Value)]) -> bool {
        let (ks, key_vals) = group_key(row, &self.group_by);
        let entry = self.state.entry(ks.clone()).or_insert_with(|| RingEntry {
            key: key_vals,
            rows: VecDeque::new(),
        });
        entry.rows.push_back(row.to_vec());
        while entry.rows.len() > self.n {
            entry.rows.pop_front();
        }
        self.pending.insert(ks);
        true
    }

    fn advance(&mut self, _now_ms: i64) -> Vec<WindowRow> {
        self.drain()
    }

    fn advance_to(&mut self, _watermark_ms: i64) -> Vec<WindowRow> {
        self.drain()
    }

    fn flush(&mut self) -> Vec<WindowRow> {
        self.drain()
    }

    fn snapshot(&mut self) -> Vec<u8> {
        use serde_json::json;
        let entries: Vec<serde_json::Value> = self
            .state
            .iter()
            .map(|(ks, e)| {
                json!([
                    ks,
                    e.key.iter().map(fv_value::value_to_json).collect::<Vec<_>>(),
                    e.rows.iter().map(|r| snapshot::row_to_json(r)).collect::<Vec<_>>(),
                ])
            })
            .collect();
        let pending: Vec<&String> = self.pending.iter().collect();
        snapshot::envelope(
            "lastn",
            &self.cfg_fingerprint(),
            json!({ "entries": entries, "pending": pending }),
        )
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        let st = snapshot::open_envelope("lastn", &self.cfg_fingerprint(), bytes)?;
        self.state.clear();
        for e in st["entries"].as_array().ok_or("lastn: missing entries")? {
            let t = e.as_array().filter(|a| a.len() == 3).ok_or("lastn: bad entry")?;
            let ks = t[0].as_str().ok_or("lastn: bad entry key")?.to_string();
            let key: Vec<Value> = t[1]
                .as_array()
                .ok_or("lastn: bad key vals")?
                .iter()
                .map(fv_value::json_to_value)
                .collect();
            let rows: VecDeque<Vec<(String, Value)>> = t[2]
                .as_array()
                .ok_or("lastn: bad rows")?
                .iter()
                .map(snapshot::row_from_json)
                .collect::<Result<_, _>>()?;
            self.state.insert(ks, RingEntry { key, rows });
        }
        self.pending = st["pending"]
            .as_array()
            .ok_or("lastn: missing pending")?
            .iter()
            .map(|p| p.as_str().map(String::from).ok_or("lastn: bad pending key".to_string()))
            .collect::<Result<_, _>>()?;
        Ok(())
    }
}

#[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 bid(auction: &str, price: f64, ts: f64) -> Vec<(String, Value)> {
        row(&[
            ("auction", Value::Str(auction.into())),
            ("price", Value::Num(price)),
            ("ts", Value::Num(ts)),
        ])
    }
    /// (rank, price) pairs for one auction from a drain, in emission order.
    fn ranks(fired: &[WindowRow], auction: &str) -> Vec<(f64, f64)> {
        fired
            .iter()
            .filter(|w| w.key.first() == Some(&Value::Str(auction.into())))
            .map(|w| {
                let rank = match w.key.last() {
                    Some(Value::Num(r)) => *r,
                    _ => panic!("no rank"),
                };
                let price = w
                    .aggs
                    .iter()
                    .find(|(k, _)| k == "price")
                    .map(|(_, v)| match v {
                        Value::Num(p) => *p,
                        _ => 0.0,
                    })
                    .unwrap();
                (rank, price)
            })
            .collect()
    }

    #[test]
    fn topn_keeps_best_n_and_emits_on_change_only() {
        let mut op = TopN::new(vec!["auction".into()], "price", true, 2, Some("ts".into()));
        assert!(op.push(0, 0, &bid("a1", 10.0, 1.0)));
        assert!(op.push(0, 0, &bid("a1", 30.0, 2.0)));
        let fired = op.advance(0);
        assert_eq!(ranks(&fired, "a1"), vec![(1.0, 30.0), (2.0, 10.0)]);
        // A bid below the current top-2 changes nothing → no emission.
        assert!(op.push(0, 0, &bid("a1", 5.0, 3.0)));
        assert!(op.advance(0).is_empty());
        // A new best re-emits the key's current ranks (upsert convergence).
        assert!(op.push(0, 0, &bid("a1", 40.0, 4.0)));
        assert_eq!(ranks(&op.advance(0), "a1"), vec![(1.0, 40.0), (2.0, 30.0)]);
    }

    #[test]
    fn topn_tie_breaks_by_tie_column_then_arrival() {
        // Same price: the EARLIER ts wins (q9 semantics); same price+ts: first-seen wins.
        let mut op = TopN::new(vec!["auction".into()], "price", true, 1, Some("ts".into()));
        op.push(0, 0, &bid("a1", 10.0, 5.0));
        op.advance(0);
        op.push(0, 0, &bid("a1", 10.0, 3.0)); // earlier ts → outranks
        let fired = op.advance(0);
        let ts = fired[0].aggs.iter().find(|(k, _)| k == "ts").map(|(_, v)| v.clone());
        assert_eq!(ts, Some(Value::Num(3.0)));
        op.push(0, 0, &bid("a1", 10.0, 3.0)); // full tie → the incumbent (earlier seq) stays, no change
        assert!(op.advance(0).is_empty());
    }

    #[test]
    fn topn_non_numeric_order_is_rejected() {
        let mut op = TopN::new(vec!["auction".into()], "price", true, 1, None);
        assert!(!op.push(
            0,
            0,
            &row(&[
                ("auction", Value::Str("a1".into())),
                ("price", Value::Str("high".into()))
            ])
        ));
        assert!(op.advance(0).is_empty());
    }

    #[test]
    fn topn_keys_are_independent_and_drained_deterministically() {
        let mut op = TopN::new(vec!["auction".into()], "price", true, 1, None);
        op.push(0, 0, &bid("a2", 7.0, 1.0));
        op.push(0, 0, &bid("a1", 9.0, 1.0));
        let fired = op.advance(0);
        assert_eq!(fired.len(), 2);
        // Pending drains in sorted key order — a1 before a2 — regardless of arrival order.
        assert_eq!(ranks(&fired, "a1"), vec![(1.0, 9.0)]);
        assert_eq!(ranks(&fired, "a2"), vec![(1.0, 7.0)]);
    }

    #[test]
    fn topn_snapshot_restore_fires_identically_to_uninterrupted() {
        let head = [bid("a1", 10.0, 1.0), bid("a1", 30.0, 2.0), bid("a2", 5.0, 1.0)];
        let tail = [bid("a1", 20.0, 3.0), bid("a2", 50.0, 2.0)];
        let mk = || TopN::new(vec!["auction".into()], "price", true, 2, Some("ts".into()));

        let mut uninterrupted = mk();
        for r in head.iter().chain(tail.iter()) {
            uninterrupted.push(0, 0, r);
        }
        let expected = uninterrupted.advance(0);

        let mut original = mk();
        for r in &head {
            original.push(0, 0, r);
        }
        original.advance(0); // checkpoint happens after a drain — pending is empty
        let snap = original.snapshot();
        let mut restored = mk();
        restored.load_snapshot(&snap).unwrap();
        for r in &tail {
            restored.push(0, 0, r);
        }
        let got = restored.advance(0);
        // Same keys+content for every changed key. (The uninterrupted run also has a1/a2 pending.)
        assert_eq!(format!("{expected:?}"), format!("{got:?}"));
    }

    #[test]
    fn topn_snapshot_refuses_config_change() {
        let mut op = TopN::new(vec!["auction".into()], "price", true, 2, None);
        let snap = op.snapshot();
        let mut other = TopN::new(vec!["auction".into()], "price", true, 3, None);
        assert!(other.load_snapshot(&snap).unwrap_err().contains("config changed"));
    }

    #[test]
    fn lastn_ring_evicts_oldest_and_aggregates_over_the_window_of_n() {
        let mut op = LastN::new(
            vec!["seller".into()],
            3,
            vec![Agg::of(AggOp::Avg, "price", "avgPrice"), Agg::count("n")],
        );
        for p in [10.0, 20.0, 30.0, 40.0] {
            op.push(
                0,
                0,
                &row(&[("seller", Value::Str("s1".into())), ("price", Value::Num(p))]),
            );
        }
        let fired = op.advance(0);
        assert_eq!(fired.len(), 1); // one upsert per changed key per drain
        let avg = fired[0]
            .aggs
            .iter()
            .find(|(k, _)| k == "avgPrice")
            .map(|(_, v)| v.clone());
        assert_eq!(avg, Some(Value::Num(30.0))); // (20+30+40)/3 — the 10 was evicted
        let n = fired[0].aggs.iter().find(|(k, _)| k == "n").map(|(_, v)| v.clone());
        assert_eq!(n, Some(Value::Num(3.0)));
    }

    #[test]
    fn lastn_snapshot_restore_fires_identically() {
        let mk = || LastN::new(vec!["seller".into()], 2, vec![Agg::of(AggOp::Sum, "price", "total")]);
        let head = [row(&[("seller", Value::Str("s1".into())), ("price", Value::Num(5.0))])];
        let tail = [row(&[("seller", Value::Str("s1".into())), ("price", Value::Num(7.0))])];

        let mut uninterrupted = mk();
        for r in head.iter().chain(tail.iter()) {
            uninterrupted.push(0, 0, r);
        }
        let expected = uninterrupted.advance(0);

        let mut original = mk();
        for r in &head {
            original.push(0, 0, r);
        }
        original.advance(0);
        let snap = original.snapshot();
        let mut restored = mk();
        restored.load_snapshot(&snap).unwrap();
        for r in &tail {
            restored.push(0, 0, r);
        }
        assert_eq!(format!("{expected:?}"), format!("{:?}", restored.advance(0)));
    }
}