fv-streams 0.1.0

The FusionVault Streams standalone runner: run a stream pipeline defined in one TOML file against Kafka or Redpanda with no control plane, including the built-in Nexmark event generator.
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
//! the NEXMARK CONNECTOR, v1: a TOML dataset declaring `connector = "nexmark"` gets a
//! runner-managed generator task that feeds the dataset's topic with the standard Nexmark event
//! model (persons/auctions/bids, 1:3:46 per 50 events) before/while the pipeline runs.
//!
//! Why a connector and not an in-engine source: zero risk to the proven consume loops, and the
//! engine reads real Kafka — the same fairness methodology every bench here uses (an in-engine
//! source is a later option for compute-ceiling numbers, labeled honestly).
//!
//! DETERMINISM: everything derives from `seed` via a fixed LCG — same seed, same events, same keys,
//! same order. The oracle harness still computes expectations FROM THE TOPIC (the events the engine
//! actually saw), so generator evolution can never silently skew an exactness claim.
//!
//! ```toml
//! [datasets.events]
//! connector = "nexmark"
//! topic = "nexmark-events"
//! events = 100000      # total events, then the generator stops (bounded, v1)
//! seed = 42            # deterministic stream (default 42)
//! stepMs = 10          # event-time advance per event (default 10ms)
//! rate = 0             # events/sec pacing; 0 = as fast as the producer goes (default)
//! delayMs = 0          # wait before producing — lets the pipeline's consumer group stabilize
//!                      # first (REQUIRED for exact processing-time queries: replay re-stamps
//!                      # arrival times — see the l6 scoping note's ingest-time caveat)
//! partitions = 4       # topic partitions when the runner creates it (default 4)
//! tailDelayMs = 8000   # quiesce before the sentinels: real events must have DRAINED through the
//!                      # pipeline first — a shuffle merges source partitions into one stream, so a
//!                      # sentinel that overtakes another partition's real rows in consumption
//!                      # order poisons the merged watermark and late-drops them (measured; the
//!                      # scoping note records it). Delay ≈ end-to-end drain time.
//! tail = true          # after the events (and the quiesce), emit far-future SENTINELS of each type to every
//!                      # partition — the bounded-run watermark closure (standard Nexmark drivers
//!                      # do this with watermark ticks). Sentinels use ids BELOW 1000 (person 1,
//!                      # auction 1, bid on auction 1) and dateTime ≈ end + 10^7ms so harnesses
//!                      # exclude them by id/time; without them, tail windows only flush at
//!                      # shutdown and chained stages race their upstream's final flush.
//! ```
//!
//! Event shapes (field names per the standard model; one interleaved stream + a `type` field —
//! queries pre-filter with inline steps, free):
//! - person:  { type, id, name, emailAddress, creditCard, city, state, dateTime }
//! - auction: { type, id, itemName, initialBid, reserve, dateTime, expires, seller, category }
//! - bid:     { type, auction, bidder, price, channel, dateTime }
//!
//! Keys: person `p<id>`, auction `a<id>`, bid `a<auction>` — bids stay ordered per auction.

use rdkafka::config::ClientConfig;
use rdkafka::producer::{BaseProducer, BaseRecord, Producer};
use serde_json::{json, Value as J};
use std::time::Duration;

/// Parsed generator config for one `connector = "nexmark"` dataset.
pub struct NexmarkCfg {
    pub dataset: String,
    pub topic: String,
    pub brokers: String,
    pub events: u64,
    pub seed: u64,
    pub step_ms: i64,
    pub rate: u64,
    pub partitions: i32,
    pub delay_ms: u64,
    pub tail: bool,
    pub tail_delay_ms: u64,
}

/// Recognize a nexmark dataset definition (returns `None` for plain topic-bound datasets).
pub fn parse(dataset: &str, ds: &J, default_brokers: &str) -> Option<Result<NexmarkCfg, String>> {
    if ds["connector"].as_str() != Some("nexmark") {
        return None;
    }
    let Some(topic) = ds["topic"].as_str() else {
        return Some(Err(format!(
            "pipeline.toml: [datasets.{dataset}] connector=\"nexmark\" needs `topic = \"…\"`"
        )));
    };
    Some(Ok(NexmarkCfg {
        dataset: dataset.to_string(),
        topic: topic.to_string(),
        brokers: ds["brokers"].as_str().unwrap_or(default_brokers).to_string(),
        events: ds["events"].as_u64().unwrap_or(100_000),
        seed: ds["seed"].as_u64().unwrap_or(42),
        step_ms: ds["stepMs"].as_i64().unwrap_or(10).max(0),
        rate: ds["rate"].as_u64().unwrap_or(0),
        partitions: ds["partitions"].as_i64().unwrap_or(4).max(1) as i32,
        delay_ms: ds["delayMs"].as_u64().unwrap_or(0),
        tail: ds["tail"].as_bool().unwrap_or(true),
        tail_delay_ms: ds["tailDelayMs"].as_u64().unwrap_or(8_000),
    }))
}

/// The fixed deterministic PRNG (LCG, Knuth MMIX constants). Not cryptographic — reproducible.
struct Lcg(u64);
impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 16 // discard low bits (LCG lows are weak)
    }
    fn below(&mut self, n: u64) -> u64 {
        if n == 0 {
            0
        } else {
            self.next() % n
        }
    }
}

const US_STATES: [&str; 10] = ["OR", "ID", "CA", "WA", "NV", "AZ", "UT", "MT", "WY", "CO"];
const CITIES: [&str; 10] = [
    "Portland",
    "Boise",
    "Sacramento",
    "Seattle",
    "Reno",
    "Phoenix",
    "Provo",
    "Helena",
    "Cheyenne",
    "Denver",
];
const CHANNELS: [&str; 4] = ["Google", "Facebook", "Baidu", "Apple"];
const CATEGORIES: u64 = 5;
const FIRST_ID: u64 = 1000;
const BASE_TIME_MS: i64 = 1_000_000; // event-time origin (arbitrary, deterministic)
/// Sentinel entities use this id (< FIRST_ID — real entities never collide) and a dateTime this far
/// beyond the last real event, so any oracle can exclude them by id or time.
pub const SENTINEL_ID: u64 = 1;
// Sentinel ids must never collide with real entity ids — checked at compile time, so a change to
// either constant fails the build rather than a test.
const _: () = assert!(SENTINEL_ID < FIRST_ID);
pub const SENTINEL_AHEAD_MS: i64 = 10_000_000;

/// Generate event `n` of the stream (0-based). `persons`/`auctions` count entities issued BEFORE
/// this event. Returns `(key, payload, kind)` where kind is 'p'/'a'/'b'.
fn event(n: u64, seed: u64, step_ms: i64, persons: u64, auctions: u64) -> (String, J, char) {
    // Per-event PRNG stream: independent of production batching, stable under any refactor.
    let mut r = Lcg(seed ^ (n.wrapping_mul(0x9E3779B97F4A7C15)));
    r.next();
    let date_time = BASE_TIME_MS + (n as i64) * step_ms;
    match n % 50 {
        0 => {
            let id = FIRST_ID + persons;
            let key = format!("p{id}");
            let payload = json!({
                "type": "person",
                "id": id,
                "name": format!("person-{id}"),
                "emailAddress": format!("person-{id}@example.com"),
                "creditCard": format!("{:04} {:04} {:04} {:04}", r.below(10000), r.below(10000), r.below(10000), r.below(10000)),
                "city": CITIES[r.below(CITIES.len() as u64) as usize],
                "state": US_STATES[r.below(US_STATES.len() as u64) as usize],
                "dateTime": date_time,
            });
            (key, payload, 'p')
        }
        1..=3 => {
            let id = FIRST_ID + auctions;
            let key = format!("a{id}");
            let initial = 1 + r.below(1000);
            // Seller: a person that EXISTS (event 0 is always a person, so persons ≥ 1 here).
            let seller = FIRST_ID + r.below(persons.max(1));
            let payload = json!({
                "type": "auction",
                "id": id,
                "itemName": format!("item-{id}"),
                "initialBid": initial,
                "reserve": initial + r.below(1000),
                "dateTime": date_time,
                "expires": date_time + 10_000 + r.below(100_000) as i64,
                "seller": seller,
                "category": r.below(CATEGORIES),
            });
            (key, payload, 'a')
        }
        _ => {
            // Auction skew (standard nexmark is hot-heavy): half the bids hit the LATEST auction,
            // half spread uniformly. Bidder uniform over issued persons.
            let auction = if r.below(2) == 0 {
                FIRST_ID + auctions.saturating_sub(1)
            } else {
                FIRST_ID + r.below(auctions.max(1))
            };
            let bidder = FIRST_ID + r.below(persons.max(1));
            let key = format!("a{auction}");
            let payload = json!({
                "type": "bid",
                "auction": auction,
                "bidder": bidder,
                "price": 1 + r.below(10_000),
                "channel": CHANNELS[r.below(CHANNELS.len() as u64) as usize],
                "dateTime": date_time,
            });
            (key, payload, 'b')
        }
    }
}

/// Run the generator to completion on a dedicated OS thread (the producer is sync). Prints progress
/// and a final line; production errors retry on a full queue and are otherwise fatal-loud.
pub fn spawn(cfg: NexmarkCfg) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        if cfg.delay_ms > 0 {
            std::thread::sleep(Duration::from_millis(cfg.delay_ms));
        }
        let producer: BaseProducer = match ClientConfig::new()
            .set("bootstrap.servers", &cfg.brokers)
            .set("enable.idempotence", "true")
            .set("queue.buffering.max.messages", "1000000")
            .create()
        {
            Ok(p) => p,
            Err(e) => {
                eprintln!("nexmark[{}]: producer create failed: {e}", cfg.dataset);
                return;
            }
        };
        let started = std::time::Instant::now();
        let (mut persons, mut auctions) = (0u64, 0u64);
        for n in 0..cfg.events {
            let (key, payload, kind) = event(n, cfg.seed, cfg.step_ms, persons, auctions);
            match kind {
                'p' => persons += 1,
                'a' => auctions += 1,
                _ => {}
            }
            let bytes = serde_json::to_vec(&payload).expect("nexmark event serializes");
            let mut rec = BaseRecord::to(&cfg.topic).key(&key).payload(&bytes);
            loop {
                match producer.send(rec) {
                    Ok(()) => break,
                    Err((_, r)) => {
                        producer.poll(Duration::from_millis(2));
                        rec = r;
                    }
                }
            }
            producer.poll(Duration::ZERO);
            // Pacing: hold the emitted count at `rate` events/s (coarse per-500 check is plenty).
            if cfg.rate > 0 && n % 500 == 0 {
                let due = started.elapsed().as_secs_f64() * cfg.rate as f64;
                if (n as f64) > due {
                    std::thread::sleep(Duration::from_millis(
                        (((n as f64 - due) / cfg.rate as f64) * 1000.0) as u64 + 1,
                    ));
                }
            }
        }
        // Report real-event production BEFORE the quiesce (harnesses time the pipeline against
        // this line; the final line below includes the tail delay + sentinels).
        let _ = producer.flush(Duration::from_secs(60));
        println!(
            "nexmark[{}]: produced {} real events in {:.1}s",
            cfg.dataset,
            cfg.events,
            started.elapsed().as_secs_f64()
        );
        // Watermark closure (see the module doc): one sentinel of each type to EVERY partition —
        // after the reals are flushed AND a quiesce, so no sentinel can overtake a real row through
        // a shuffle (consumption order across partitions is not production order).
        if cfg.tail {
            let _ = producer.flush(Duration::from_secs(60));
            std::thread::sleep(Duration::from_millis(cfg.tail_delay_ms));
            let t = BASE_TIME_MS + (cfg.events as i64) * cfg.step_ms + SENTINEL_AHEAD_MS;
            let sentinels = [
                json!({"type": "person", "id": SENTINEL_ID, "name": "sentinel", "emailAddress": "s@s", "creditCard": "0", "city": "Nowhere", "state": "XX", "dateTime": t}),
                json!({"type": "auction", "id": SENTINEL_ID, "itemName": "sentinel", "initialBid": 0, "reserve": 0, "dateTime": t, "expires": t, "seller": SENTINEL_ID, "category": 0}),
                json!({"type": "bid", "auction": SENTINEL_ID, "bidder": SENTINEL_ID, "price": 0, "channel": "sentinel", "dateTime": t}),
            ];
            for p in 0..cfg.partitions {
                for payload in &sentinels {
                    let bytes = serde_json::to_vec(payload).expect("sentinel serializes");
                    let mut rec = BaseRecord::to(&cfg.topic).key("sentinel").payload(&bytes).partition(p);
                    loop {
                        match producer.send(rec) {
                            Ok(()) => break,
                            Err((_, r)) => {
                                producer.poll(Duration::from_millis(2));
                                rec = r;
                            }
                        }
                    }
                }
            }
        }
        let _ = producer.flush(Duration::from_secs(60));
        println!(
            "nexmark[{}]: generated {} events → {} ({} persons, {} auctions, {} bids) in {:.1}s",
            cfg.dataset,
            cfg.events,
            cfg.topic,
            persons,
            auctions,
            cfg.events - persons - auctions,
            started.elapsed().as_secs_f64()
        );
    })
}

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

    /// Replay the entity-issue bookkeeping the way `spawn` does.
    fn run(n_events: u64, seed: u64) -> Vec<(String, J, char)> {
        let (mut persons, mut auctions) = (0u64, 0u64);
        (0..n_events)
            .map(|n| {
                let e = event(n, seed, 10, persons, auctions);
                match e.2 {
                    'p' => persons += 1,
                    'a' => auctions += 1,
                    _ => {}
                }
                e
            })
            .collect()
    }

    #[test]
    fn deterministic_same_seed_same_stream() {
        let a = run(500, 42);
        let b = run(500, 42);
        assert_eq!(format!("{a:?}"), format!("{b:?}"));
        let c = run(500, 43);
        assert_ne!(format!("{a:?}"), format!("{c:?}"), "different seed must differ");
    }

    #[test]
    fn proportions_and_referential_integrity() {
        let evs = run(5000, 42);
        let (mut p, mut a, mut b) = (0u64, 0u64, 0u64);
        let mut person_ids = std::collections::HashSet::new();
        let mut auction_ids = std::collections::HashSet::new();
        for (key, ev, kind) in &evs {
            match kind {
                'p' => {
                    p += 1;
                    person_ids.insert(ev["id"].as_u64().unwrap());
                    assert!(key.starts_with('p'));
                }
                'a' => {
                    a += 1;
                    auction_ids.insert(ev["id"].as_u64().unwrap());
                    // Sellers must reference an ISSUED person.
                    assert!(
                        person_ids.contains(&ev["seller"].as_u64().unwrap()),
                        "auction seller must exist"
                    );
                    assert!(key.starts_with('a'));
                }
                _ => {
                    b += 1;
                    assert!(
                        auction_ids.contains(&ev["auction"].as_u64().unwrap()),
                        "bid auction must exist"
                    );
                    assert!(
                        person_ids.contains(&ev["bidder"].as_u64().unwrap()),
                        "bidder must exist"
                    );
                    assert_eq!(
                        *key,
                        format!("a{}", ev["auction"].as_u64().unwrap()),
                        "bids keyed by auction"
                    );
                }
            }
        }
        // 1 : 3 : 46 per 50 events.
        assert_eq!((p, a, b), (5000 / 50, 3 * 5000 / 50, 46 * 5000 / 50));
    }

    #[test]
    fn event_time_is_monotonic_with_step() {
        let evs = run(200, 7);
        for (i, (_, ev, _)) in evs.iter().enumerate() {
            assert_eq!(ev["dateTime"].as_i64().unwrap(), BASE_TIME_MS + (i as i64) * 10);
        }
    }

    #[test]
    fn golden_values_pin_the_deterministic_stream() {
        // The seed-42 stream is a CONTRACT: recorded oracle results and benchmark numbers reference
        // it. Any change to the LCG, field derivations, or proportions must be deliberate — this
        // test forces that conversation (update the pins ONLY with a version note in the module doc).
        let evs = run(52, 42);
        let pin = |i: usize, key: &str, kind: char, json: &str| {
            assert_eq!(evs[i].0, key, "event {i} key");
            assert_eq!(evs[i].2, kind, "event {i} kind");
            assert_eq!(serde_json::to_string(&evs[i].1).unwrap(), json, "event {i} payload");
        };
        pin(
            0,
            "p1000",
            'p',
            r#"{"city":"Boise","creditCard":"2172 7803 7043 3278","dateTime":1000000,"emailAddress":"person-1000@example.com","id":1000,"name":"person-1000","state":"AZ","type":"person"}"#,
        );
        pin(
            1,
            "a1000",
            'a',
            r#"{"category":3,"dateTime":1000010,"expires":1064796,"id":1000,"initialBid":166,"itemName":"item-1000","reserve":533,"seller":1000,"type":"auction"}"#,
        );
        pin(
            4,
            "a1002",
            'b',
            r#"{"auction":1002,"bidder":1000,"channel":"Facebook","dateTime":1000040,"price":9312,"type":"bid"}"#,
        );
        pin(
            50,
            "p1001",
            'p',
            r#"{"city":"Sacramento","creditCard":"0905 6287 0028 8090","dateTime":1000500,"emailAddress":"person-1001@example.com","id":1001,"name":"person-1001","state":"NV","type":"person"}"#,
        );
    }

    #[test]
    fn pacing_config_defaults_are_safe() {
        // rate=0 (flat out) and delayMs=0 are the defaults — a missing config must never pace/delay.
        let cfg = parse("d", &serde_json::json!({"connector": "nexmark", "topic": "t"}), "b")
            .unwrap()
            .unwrap();
        assert_eq!(
            (cfg.rate, cfg.delay_ms, cfg.events, cfg.seed, cfg.step_ms),
            (0, 0, 100_000, 42, 10)
        );
    }

    #[test]
    fn parse_recognizes_only_nexmark_datasets() {
        assert!(parse("d", &json!({"topic": "t"}), "b:9092").is_none());
        let cfg = parse(
            "d",
            &json!({"connector": "nexmark", "topic": "t", "events": 5, "seed": 9, "rate": 100}),
            "b:9092",
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            (cfg.events, cfg.seed, cfg.rate, cfg.partitions, cfg.delay_ms),
            (5, 9, 100, 4, 0)
        );
        assert!(cfg.tail, "tail sentinels default ON");
        assert_eq!(cfg.tail_delay_ms, 8_000, "quiesce default");
        assert!(
            parse("d", &json!({"connector": "nexmark"}), "b").unwrap().is_err(),
            "topic required"
        );
    }
}