fv-streams-ops 0.3.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Shared keyed-aggregation accumulator — the running state every windowing operator keeps per
//! `(bucket, group-key)`. Tumbling/sliding ([`WindowAgg`](crate::WindowAgg)) and session
//! ([`SessionAgg`](crate::SessionAgg)) windows differ in how buckets are *bounded* (fixed vs dynamic),
//! but the aggregation itself — count, and one running scalar slot per agg — is identical, so it lives
//! here once. An operator owns a map of `Acc`s and drives [`add`](Acc::add) per event,
//! [`merge`](Acc::merge) when two buckets combine (session bridging), and
//! [`finalize_aggs`](Acc::finalize_aggs) when a bucket fires.

use fv_value::Value;

use crate::{Agg, AggOp};

/// Per `(bucket, group-key)` running state: the event count and one running scalar slot per
/// configured aggregation (sum for Sum/Avg, running min/max for Min/Max; `None` until the first
/// numeric value; unused for Count, which reads `count`).
///
/// T2 (memory diet): the group-key VALUES no longer live here — operators store them once per
/// distinct key (interned/bucketed), not once per open window. `slots` is a single exact-size
/// allocation, and `sets` (countDistinct only) allocates NOTHING unless the agg list needs it —
/// the common all-scalar accumulator is one heap block.
#[derive(Debug, Clone)]
pub(crate) struct Acc {
    pub count: u64,
    pub slots: Box<[Option<f64>]>,
    /// Per-agg distinct-value sets — `Some` only when the agg list contains `CountDistinct`
    /// (stable-keyed strings, `BTreeSet` so snapshots serialize deterministically).
    pub sets: Option<Box<[Option<std::collections::BTreeSet<String>>]>>,
    /// Per-agg Welford state `(n, mean, M2)` — `Some` only when the agg list contains a
    /// variance/stddev op (FUNC-2). O(1)/event, numerically stable, parallel-mergeable.
    pub welford: Option<Box<[Welford]>>,
}

/// Welford online moments for one variance/stddev slot: count of non-null numeric values, running
/// mean, and M2 (sum of squared deviations). `n == 0` = untouched.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct Welford {
    pub n: u64,
    pub mean: f64,
    pub m2: f64,
}
impl Welford {
    fn add(&mut self, x: f64) {
        self.n += 1;
        let delta = x - self.mean;
        self.mean += delta / self.n as f64;
        self.m2 += delta * (x - self.mean);
    }
    /// Parallel merge (Chan et al.) — combines two independently-accumulated states exactly.
    fn merge(&mut self, o: &Welford) {
        if o.n == 0 {
            return;
        }
        if self.n == 0 {
            *self = *o;
            return;
        }
        let (na, nb) = (self.n as f64, o.n as f64);
        let delta = o.mean - self.mean;
        let total = na + nb;
        self.m2 += o.m2 + delta * delta * na * nb / total;
        self.mean += delta * nb / total;
        self.n += o.n;
    }
}

/// Whether an agg list needs the distinct-set side table (decides `Acc.sets` allocation).
pub(crate) fn needs_sets(aggs: &[Agg]) -> bool {
    aggs.iter().any(|a| a.op == AggOp::CountDistinct)
}

/// Whether an agg list needs the Welford side table (decides `Acc.welford` allocation).
pub(crate) fn needs_welford(aggs: &[Agg]) -> bool {
    aggs.iter().any(|a| a.op.is_variance())
}

impl Acc {
    /// A fresh accumulator with one empty slot per agg. `with_sets`/`with_welford` are precomputed
    /// (`needs_sets`/`needs_welford`) so per-key creation never rescans the agg list, and the common
    /// all-scalar accumulator allocates neither side table.
    pub fn new(n_aggs: usize, with_sets: bool, with_welford: bool) -> Self {
        Self {
            count: 0,
            slots: vec![None; n_aggs].into_boxed_slice(),
            sets: if with_sets {
                Some(vec![None; n_aggs].into_boxed_slice())
            } else {
                None
            },
            welford: if with_welford {
                Some(vec![Welford::default(); n_aggs].into_boxed_slice())
            } else {
                None
            },
        }
    }

    /// Fold one event's row in: bump the count and update each agg's running slot.
    pub fn add(&mut self, aggs: &[Agg], row: &[(String, Value)]) {
        self.count += 1;
        for (i, a) in aggs.iter().enumerate() {
            match a.op {
                AggOp::Count => {}
                AggOp::CountDistinct => {
                    // SQL semantics: COUNT(DISTINCT x) ignores NULL/missing. `sets` exists whenever
                    // the agg list contains CountDistinct (see `needs_sets`).
                    let v = row.iter().find(|(k, _)| k == &a.column).map(|(_, v)| v);
                    if let (Some(v), Some(sets)) = (v, self.sets.as_mut()) {
                        if !matches!(v, Value::Null) {
                            sets[i].get_or_insert_with(Default::default).insert(value_key(Some(v)));
                        }
                    }
                }
                op if op.is_variance() => {
                    let Some(v) = row.iter().find(|(k, _)| k == &a.column).and_then(|(_, v)| as_num(v)) else {
                        continue;
                    };
                    if let Some(w) = self.welford.as_mut() {
                        w[i].add(v);
                    }
                }
                AggOp::BoolAnd | AggOp::BoolOr => {
                    let Some(b) = row
                        .iter()
                        .find(|(k, _)| k == &a.column)
                        .and_then(|(_, v)| as_bool_num(v))
                    else {
                        continue;
                    };
                    self.slots[i] = Some(combine_scalar(a.op, self.slots[i], b));
                }
                AggOp::BitAnd | AggOp::BitOr | AggOp::BitXor => {
                    let Some(n) = row.iter().find(|(k, _)| k == &a.column).and_then(|(_, v)| as_int(v)) else {
                        continue;
                    };
                    self.slots[i] = Some(combine_scalar(a.op, self.slots[i], n));
                }
                _ => {
                    let Some(v) = row.iter().find(|(k, _)| k == &a.column).and_then(|(_, v)| as_num(v)) else {
                        continue;
                    };
                    self.slots[i] = Some(combine_scalar(a.op, self.slots[i], v));
                }
            }
        }
    }

    /// Fold another accumulator (same key + agg layout) into this one — used when two sessions bridge.
    pub fn merge(&mut self, aggs: &[Agg], other: &Acc) {
        self.count += other.count;
        for (i, a) in aggs.iter().enumerate() {
            if a.op == AggOp::CountDistinct {
                if let (Some(mine), Some(theirs)) = (self.sets.as_mut(), other.sets.as_ref()) {
                    if let Some(t) = &theirs[i] {
                        mine[i].get_or_insert_with(Default::default).extend(t.iter().cloned());
                    }
                }
                continue;
            }
            if a.op.is_variance() {
                if let (Some(mine), Some(theirs)) = (self.welford.as_mut(), other.welford.as_ref()) {
                    let o = theirs[i];
                    mine[i].merge(&o);
                }
                continue;
            }
            self.slots[i] = match (self.slots[i], other.slots[i]) {
                (x, None) => x,
                (None, y) => y,
                (Some(x), Some(y)) => Some(combine_scalar(a.op, Some(x), y)),
            };
        }
    }

    /// The fired output: `(alias, value)` per agg, in `aggs` order.
    pub fn finalize_aggs(&self, aggs: &[Agg]) -> Vec<(String, Value)> {
        aggs.iter()
            .enumerate()
            .map(|(i, a)| {
                (
                    a.alias.clone(),
                    finalize(
                        a.op,
                        self.count,
                        self.slots[i],
                        self.sets.as_ref().and_then(|s| s[i].as_ref()),
                        self.welford.as_ref().map(|w| w[i]),
                    ),
                )
            })
            .collect()
    }
}

/// Combine a running slot (`cur`, `None` if unset) with a fresh scalar `v` under `op`. `None` cur ⇒ the
/// first value seeds the slot. Count never reaches here (its slot is unused).
fn combine_scalar(op: AggOp, cur: Option<f64>, v: f64) -> f64 {
    match (op, cur) {
        (AggOp::Sum | AggOp::Avg, Some(s)) => s + v,
        (AggOp::Min, Some(m)) => m.min(v),
        (AggOp::Max, Some(m)) => m.max(v),
        // FUNC-2 folds (v is 0/1 for bool, a whole number for bit). None ⇒ first value seeds.
        (AggOp::BoolAnd, Some(a)) => ((a != 0.0) && (v != 0.0)) as i64 as f64,
        (AggOp::BoolOr, Some(a)) => ((a != 0.0) || (v != 0.0)) as i64 as f64,
        (AggOp::BitAnd, Some(a)) => ((a as i64) & (v as i64)) as f64,
        (AggOp::BitOr, Some(a)) => ((a as i64) | (v as i64)) as f64,
        (AggOp::BitXor, Some(a)) => ((a as i64) ^ (v as i64)) as f64,
        _ => v, // first value for any op (Count is skipped by the caller)
    }
}

/// Produce the final aggregated value from accumulator state.
pub(crate) fn finalize(
    op: AggOp,
    count: u64,
    slot: Option<f64>,
    set: Option<&std::collections::BTreeSet<String>>,
    w: Option<Welford>,
) -> Value {
    match op {
        AggOp::Count => Value::Num(count as f64),
        AggOp::CountDistinct => Value::Num(set.map(|s| s.len()).unwrap_or(0) as f64),
        AggOp::Sum => Value::Num(slot.unwrap_or(0.0)),
        AggOp::Avg => Value::Num(
            slot.map(|s| if count > 0 { s / count as f64 } else { 0.0 })
                .unwrap_or(0.0),
        ),
        AggOp::Min | AggOp::Max => slot.map(Value::Num).unwrap_or(Value::Null),
        // Bool/bit: the fold lives in `slot`; no values seen ⇒ null (SQL: aggregate of no rows).
        AggOp::BoolAnd | AggOp::BoolOr => slot.map(|x| Value::Bool(x != 0.0)).unwrap_or(Value::Null),
        AggOp::BitAnd | AggOp::BitOr | AggOp::BitXor => {
            slot.map(|x| Value::Num((x as i64) as f64)).unwrap_or(Value::Null)
        }
        // Variance/stddev from Welford. pop needs ≥1, samp needs ≥2 (else null, SQL semantics).
        AggOp::VarPop | AggOp::VarSamp | AggOp::StddevPop | AggOp::StddevSamp => {
            let w = w.unwrap_or_default();
            let var = match op {
                _ if w.n == 0 => return Value::Null,
                AggOp::VarPop | AggOp::StddevPop => w.m2 / w.n as f64,
                _ if w.n < 2 => return Value::Null, // samp of <2 values
                _ => w.m2 / (w.n - 1) as f64,
            };
            Value::Num(if matches!(op, AggOp::StddevPop | AggOp::StddevSamp) {
                var.sqrt()
            } else {
                var
            })
        }
    }
}

/// Extract a boolean column as 0.0/1.0 (bool aggs). Non-bool/null ⇒ None (skipped).
pub(crate) fn as_bool_num(v: &Value) -> Option<f64> {
    match v {
        Value::Bool(b) => Some(*b as i64 as f64),
        _ => None,
    }
}

/// Extract a whole-number integer column (bit aggs). Non-integer/null ⇒ None (skipped).
pub(crate) fn as_int(v: &Value) -> Option<f64> {
    match v {
        Value::Num(n) if n.fract() == 0.0 => Some(*n),
        _ => None,
    }
}

/// Coerce a value to f64 for aggregation (numbers only; others don't aggregate).
pub(crate) fn as_num(v: &Value) -> Option<f64> {
    match v {
        Value::Num(n) => Some(*n),
        _ => None,
    }
}

/// Build a row's COMPOSITE group-key string: `value_key` per column, joined by `\u{1}` — the intern
/// key both window and session operators hash on (T2). Matches the historical per-column layout
/// (`Vec<String>` of `value_key`s), so v1 snapshots re-intern by simple join.
pub(crate) fn composite_of(row: &[(String, Value)], group_by: &[String]) -> String {
    let mut s = String::new();
    for (i, g) in group_by.iter().enumerate() {
        if i > 0 {
            s.push('\u{1}');
        }
        s.push_str(&value_key(row.iter().find(|(k, _)| k == g).map(|(_, v)| v)));
    }
    s
}

/// The group-by column VALUES for emission — built only when a key is first seen (stored once per
/// distinct key, never per open window).
pub(crate) fn vals_of(row: &[(String, Value)], group_by: &[String]) -> Vec<Value> {
    group_by
        .iter()
        .map(|g| {
            row.iter()
                .find(|(k, _)| k == g)
                .map(|(_, v)| v.clone())
                .unwrap_or(Value::Null)
        })
        .collect()
}

/// A stable string form of a group-by column value, for hashing the composite key (`f64` isn't `Hash`).
pub(crate) fn value_key(v: Option<&Value>) -> String {
    match v {
        None | Some(Value::Null) => "\u{0}null".into(),
        Some(Value::Bool(b)) => format!("b{b}"),
        Some(Value::Num(n)) => format!("n{n}"),
        Some(Value::Str(s)) => format!("s{s}"),
        Some(other) => format!("x{other:?}"),
    }
}

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

    fn row(pairs: &[(&str, Value)]) -> Vec<(String, Value)> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }
    fn aggs() -> Vec<Agg> {
        vec![
            Agg::count("n"),
            Agg::of(AggOp::Sum, "amount", "total"),
            Agg::of(AggOp::Avg, "amount", "mean"),
            Agg::of(AggOp::Min, "amount", "lo"),
            Agg::of(AggOp::Max, "amount", "hi"),
        ]
    }
    fn val(out: &[(String, Value)], alias: &str) -> Value {
        out.iter().find(|(a, _)| a == alias).unwrap().1.clone()
    }

    #[test]
    fn add_accumulates_every_op() {
        let ag = aggs();
        let mut acc = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        for a in [2.0, 4.0, 6.0] {
            acc.add(&ag, &row(&[("amount", Value::Num(a))]));
        }
        let out = acc.finalize_aggs(&ag);
        assert_eq!(val(&out, "n"), Value::Num(3.0));
        assert_eq!(val(&out, "total"), Value::Num(12.0));
        assert_eq!(val(&out, "mean"), Value::Num(4.0));
        assert_eq!(val(&out, "lo"), Value::Num(2.0));
        assert_eq!(val(&out, "hi"), Value::Num(6.0));
    }

    #[test]
    fn merge_combines_two_accumulators() {
        let ag = aggs();
        let mut a = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        let mut b = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        a.add(&ag, &row(&[("amount", Value::Num(2.0))])); // a: n1 sum2 min2 max2
        a.add(&ag, &row(&[("amount", Value::Num(10.0))])); // a: n2 sum12 min2 max10
        b.add(&ag, &row(&[("amount", Value::Num(1.0))])); // b: n1 sum1 min1 max1
        a.merge(&ag, &b);
        let out = a.finalize_aggs(&ag);
        assert_eq!(val(&out, "n"), Value::Num(3.0));
        assert_eq!(val(&out, "total"), Value::Num(13.0));
        assert_eq!(val(&out, "mean"), Value::Num(13.0 / 3.0));
        assert_eq!(val(&out, "lo"), Value::Num(1.0));
        assert_eq!(val(&out, "hi"), Value::Num(10.0));
    }

    #[test]
    fn merge_with_empty_slot_is_a_no_op_side() {
        let ag = vec![Agg::of(AggOp::Max, "amount", "hi")];
        let mut a = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        let b = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag)); // b saw no numeric events → slot None
        a.add(&ag, &row(&[("amount", Value::Num(5.0))]));
        a.merge(&ag, &b);
        assert_eq!(val(&a.finalize_aggs(&ag), "hi"), Value::Num(5.0));
        // and the reverse: merging a populated side into an empty one adopts its slot.
        let mut c = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        c.merge(&ag, &a);
        assert_eq!(val(&c.finalize_aggs(&ag), "hi"), Value::Num(5.0));
    }

    #[test]
    fn finalize_of_no_events() {
        assert_eq!(finalize(AggOp::Count, 0, None, None, None), Value::Num(0.0));
        assert_eq!(finalize(AggOp::Sum, 0, None, None, None), Value::Num(0.0));
        assert_eq!(finalize(AggOp::Avg, 0, None, None, None), Value::Num(0.0));
        assert_eq!(finalize(AggOp::Min, 0, None, None, None), Value::Null);
        assert_eq!(finalize(AggOp::Max, 0, None, None, None), Value::Null);
        assert_eq!(finalize(AggOp::CountDistinct, 0, None, None, None), Value::Num(0.0));
    }

    #[test]
    fn non_numeric_values_do_not_aggregate() {
        let ag = vec![Agg::count("n"), Agg::of(AggOp::Sum, "amount", "total")];
        let mut acc = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        acc.add(&ag, &row(&[("amount", Value::Str("nope".into()))])); // counts, but no sum contribution
        acc.add(&ag, &row(&[("amount", Value::Num(3.0))]));
        let out = acc.finalize_aggs(&ag);
        assert_eq!(val(&out, "n"), Value::Num(2.0));
        assert_eq!(val(&out, "total"), Value::Num(3.0));
    }

    #[test]
    fn count_distinct_counts_unique_non_null_values_and_merges_as_union() {
        let ag = vec![Agg::of(AggOp::CountDistinct, "bidder", "uniq"), Agg::count("n")];
        let mut a = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        for b in ["b1", "b2", "b1"] {
            a.add(&ag, &row(&[("bidder", Value::Str(b.into()))]));
        }
        a.add(&ag, &row(&[("bidder", Value::Null)])); // NULL is ignored (SQL COUNT(DISTINCT))
        a.add(&ag, &row(&[("other", Value::Num(1.0))])); // missing column is ignored
        let out = a.finalize_aggs(&ag);
        assert_eq!(val(&out, "uniq"), Value::Num(2.0));
        assert_eq!(val(&out, "n"), Value::Num(5.0)); // count still counts every event
                                                     // Type-tagged: Num(1) and Str("1") are DISTINCT values.
        a.add(&ag, &row(&[("bidder", Value::Num(1.0))]));
        a.add(&ag, &row(&[("bidder", Value::Str("1".into()))]));
        assert_eq!(val(&a.finalize_aggs(&ag), "uniq"), Value::Num(4.0));
        // Merge = set union (session bridging).
        let mut b = Acc::new(ag.len(), needs_sets(&ag), needs_welford(&ag));
        b.add(&ag, &row(&[("bidder", Value::Str("b2".into()))])); // overlaps a
        b.add(&ag, &row(&[("bidder", Value::Str("b9".into()))])); // new
        a.merge(&ag, &b);
        assert_eq!(val(&a.finalize_aggs(&ag), "uniq"), Value::Num(5.0));
    }

    #[test]
    fn value_key_distinguishes_types_and_null() {
        assert_eq!(value_key(None), value_key(Some(&Value::Null)));
        assert_ne!(
            value_key(Some(&Value::Num(1.0))),
            value_key(Some(&Value::Str("1".into())))
        );
        assert_ne!(
            value_key(Some(&Value::Bool(true))),
            value_key(Some(&Value::Str("true".into())))
        );
    }
}

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

    fn agg(op: AggOp, col: &str) -> Agg {
        Agg::of(op, col, "r")
    }
    fn feed(aggs: &[Agg], col: &str, vals: &[Value]) -> Acc {
        let mut a = Acc::new(aggs.len(), needs_sets(aggs), needs_welford(aggs));
        for v in vals {
            a.add(aggs, &[(col.to_string(), v.clone())]);
        }
        a
    }
    fn out(a: &Acc, aggs: &[Agg]) -> Value {
        a.finalize_aggs(aggs)[0].1.clone()
    }
    fn n(v: Value) -> f64 {
        match v {
            Value::Num(x) => x,
            o => panic!("not num: {o:?}"),
        }
    }

    #[test]
    fn variance_and_stddev_match_known_values() {
        // Data {2,4,4,4,5,5,7,9}: pop var 4, pop stddev 2 (the textbook example).
        let d: Vec<Value> = [2., 4., 4., 4., 5., 5., 7., 9.]
            .iter()
            .map(|x| Value::Num(*x))
            .collect();
        for (op, expect) in [
            (AggOp::VarPop, 4.0),
            (AggOp::StddevPop, 2.0),
            (AggOp::VarSamp, 32.0 / 7.0), // M2=32, n-1=7
            (AggOp::StddevSamp, (32.0f64 / 7.0).sqrt()),
        ] {
            let ag = vec![agg(op, "x")];
            assert!((n(out(&feed(&ag, "x", &d), &ag)) - expect).abs() < 1e-9, "{op:?}");
        }
    }

    #[test]
    fn samp_needs_two_values_pop_needs_one() {
        let one = vec![Value::Num(5.0)];
        assert_eq!(
            out(&feed(&[agg(AggOp::VarPop, "x")], "x", &one), &[agg(AggOp::VarPop, "x")]),
            Value::Num(0.0)
        );
        assert_eq!(
            out(
                &feed(&[agg(AggOp::VarSamp, "x")], "x", &one),
                &[agg(AggOp::VarSamp, "x")]
            ),
            Value::Null
        );
        // No values at all → null for both.
        assert_eq!(
            out(&feed(&[agg(AggOp::VarPop, "x")], "x", &[]), &[agg(AggOp::VarPop, "x")]),
            Value::Null
        );
        // Non-numeric values are skipped (not counted).
        let mixed = vec![Value::Num(1.0), Value::Str("nope".into()), Value::Num(3.0)];
        assert_eq!(
            n(out(
                &feed(&[agg(AggOp::VarPop, "x")], "x", &mixed),
                &[agg(AggOp::VarPop, "x")]
            )),
            1.0
        ); // var{1,3}=1
    }

    #[test]
    fn welford_merge_equals_single_pass() {
        // Split a dataset, accumulate halves, merge — must equal one-pass (session bridging path).
        let ag = vec![agg(AggOp::VarPop, "x")];
        let all: Vec<Value> = (1..=10).map(|i| Value::Num(i as f64)).collect();
        let single = feed(&ag, "x", &all);
        let mut left = feed(&ag, "x", &all[..3]);
        let right = feed(&ag, "x", &all[3..]);
        left.merge(&ag, &right);
        assert!(
            (n(out(&left, &ag)) - n(out(&single, &ag))).abs() < 1e-9,
            "merge != single-pass"
        );
    }

    #[test]
    fn bool_and_or_fold() {
        let t = Value::Bool(true);
        let f = Value::Bool(false);
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BoolAnd, "b")], "b", &[t.clone(), t.clone()]),
                &[agg(AggOp::BoolAnd, "b")]
            ),
            Value::Bool(true)
        );
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BoolAnd, "b")], "b", &[t.clone(), f.clone()]),
                &[agg(AggOp::BoolAnd, "b")]
            ),
            Value::Bool(false)
        );
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BoolOr, "b")], "b", &[f.clone(), t.clone()]),
                &[agg(AggOp::BoolOr, "b")]
            ),
            Value::Bool(true)
        );
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BoolOr, "b")], "b", &[f.clone(), f.clone()]),
                &[agg(AggOp::BoolOr, "b")]
            ),
            Value::Bool(false)
        );
        // No booleans seen → null; non-bool values skipped.
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BoolAnd, "b")], "b", &[Value::Num(1.0)]),
                &[agg(AggOp::BoolAnd, "b")]
            ),
            Value::Null
        );
    }

    #[test]
    fn bit_and_or_xor_fold() {
        let v: Vec<Value> = [12.0, 10.0, 6.0].iter().map(|x| Value::Num(*x)).collect();
        assert_eq!(
            out(&feed(&[agg(AggOp::BitAnd, "n")], "n", &v), &[agg(AggOp::BitAnd, "n")]),
            Value::Num((12 & 10 & 6) as f64)
        );
        assert_eq!(
            out(&feed(&[agg(AggOp::BitOr, "n")], "n", &v), &[agg(AggOp::BitOr, "n")]),
            Value::Num((12 | 10 | 6) as f64)
        );
        assert_eq!(
            out(&feed(&[agg(AggOp::BitXor, "n")], "n", &v), &[agg(AggOp::BitXor, "n")]),
            Value::Num((12 ^ 10 ^ 6) as f64)
        );
        // Non-integer values skipped.
        assert_eq!(
            out(
                &feed(&[agg(AggOp::BitAnd, "n")], "n", &[Value::Num(1.5)]),
                &[agg(AggOp::BitAnd, "n")]
            ),
            Value::Null
        );
    }

    #[test]
    fn welford_survives_snapshot_round_trip() {
        let ag = vec![agg(AggOp::VarSamp, "x")];
        let a = feed(&ag, "x", &[Value::Num(2.0), Value::Num(4.0), Value::Num(6.0)]);
        let j = crate::snapshot::acc_to_json_v2(&a);
        let b = crate::snapshot::acc_from_json_v2(&j).unwrap();
        assert_eq!(a.welford, b.welford);
        assert_eq!(out(&a, &ag), out(&b, &ag));
    }
}