graphrefly-operators 0.0.7

Built-in operator node types for GraphReFly (map, filter, scan, switchMap, valve, gate, retry, …)
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
//! Integration tests for temporal operators (sample, debounce, throttle,
//! delay, audit, interval).
//!
//! Timer-dependent tests use `tokio::time::pause()` + `advance()` for
//! deterministic control. Multiple `yield_now()` calls ensure spawned
//! tasks get enough poll cycles.

mod common;

use std::time::Duration;

use common::{OpRuntime, RecordedEvent, TestValue};
use graphrefly_operators::temporal::{self, ThrottleOpts};

/// Yield multiple times to let spawned tasks process commands and timers.
async fn multi_yield(n: usize) {
    for _ in 0..n {
        tokio::task::yield_now().await;
    }
}

// =========================================================================
// sample
// =========================================================================

#[tokio::test]
async fn sample_emits_source_latest_on_notifier_data() {
    let rt = OpRuntime::new();
    let source = rt.state_int(None);
    let notifier = rt.state_int(None);

    let sampled = temporal::sample(rt.core(), &rt.producer_binding, source, notifier);
    let rec = rt.subscribe_recorder(sampled);

    // Emit source values.
    rt.emit_int(source, 10);
    rt.emit_int(source, 20);

    // Notifier fires → should emit 20 (latest source value).
    rt.emit_int(notifier, 1);
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    let data = rec.data_values();
    assert_eq!(data, vec![TestValue::Int(20)]);
}

#[tokio::test]
async fn sample_no_emit_if_source_completed() {
    let rt = OpRuntime::new();
    let source = rt.state_int(None);
    let notifier = rt.state_int(None);

    let sampled = temporal::sample(rt.core(), &rt.producer_binding, source, notifier);
    let rec = rt.subscribe_recorder(sampled);

    rt.emit_int(source, 10);
    rt.core().complete(source);

    // Notifier fires after source complete → no emission.
    rt.emit_int(notifier, 1);

    let data = rec.data_values();
    assert!(data.is_empty(), "no data after source complete");
}

#[tokio::test]
async fn sample_completes_on_notifier_complete() {
    let rt = OpRuntime::new();
    let source = rt.state_int(None);
    let notifier = rt.state_int(None);

    let sampled = temporal::sample(rt.core(), &rt.producer_binding, source, notifier);
    let rec = rt.subscribe_recorder(sampled);

    rt.emit_int(source, 10);
    rt.core().complete(notifier);
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert!(
        rec.events().contains(&RecordedEvent::Complete),
        "sample should complete when notifier completes"
    );
}

// =========================================================================
// debounce
// =========================================================================

#[tokio::test]
async fn debounce_emits_after_quiet() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let debounced = temporal::debounce(rt.core(), &rt.producer_binding, source, 50);
    let rec = rt.subscribe_recorder(debounced);

    rt.emit_int(source, 10);
    multi_yield(5).await;

    // Before deadline — nothing emitted.
    tokio::time::advance(Duration::from_millis(30)).await;
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert!(rec.data_values().is_empty(), "nothing before deadline");

    // Past deadline — should emit.
    tokio::time::advance(Duration::from_millis(25)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert_eq!(rec.data_values(), vec![TestValue::Int(10)]);
}

#[tokio::test]
async fn debounce_resets_on_new_data() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let debounced = temporal::debounce(rt.core(), &rt.producer_binding, source, 50);
    let rec = rt.subscribe_recorder(debounced);

    rt.emit_int(source, 10);
    multi_yield(5).await;

    // Advance 30ms, send new data (resets timer).
    tokio::time::advance(Duration::from_millis(30)).await;
    multi_yield(5).await;
    rt.emit_int(source, 20);
    multi_yield(5).await;

    // 30ms more (60ms total, but only 30ms since last data).
    tokio::time::advance(Duration::from_millis(30)).await;
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert!(rec.data_values().is_empty(), "timer reset, not yet fired");

    // 25ms more (55ms since second data).
    tokio::time::advance(Duration::from_millis(25)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert_eq!(rec.data_values(), vec![TestValue::Int(20)], "emits latest");
}

#[tokio::test]
async fn debounce_flushes_on_complete() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let debounced = temporal::debounce(rt.core(), &rt.producer_binding, source, 50);
    let rec = rt.subscribe_recorder(debounced);

    rt.emit_int(source, 10);
    multi_yield(5).await;

    // Complete before timer fires — should flush pending.
    rt.core().complete(source);
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    let events = rec.events();
    assert!(
        events.contains(&RecordedEvent::Data(TestValue::Int(10))),
        "pending value flushed on complete"
    );
    assert!(
        events.contains(&RecordedEvent::Complete),
        "complete propagated"
    );
}

// =========================================================================
// delay
// =========================================================================

#[tokio::test]
async fn delay_emits_after_duration() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let delayed = temporal::delay(rt.core(), &rt.producer_binding, source, 100);
    let rec = rt.subscribe_recorder(delayed);

    rt.emit_int(source, 42);
    multi_yield(5).await;

    // Not yet.
    tokio::time::advance(Duration::from_millis(50)).await;
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert!(rec.data_values().is_empty());

    // Now.
    tokio::time::advance(Duration::from_millis(55)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert_eq!(rec.data_values(), vec![TestValue::Int(42)]);
}

#[tokio::test]
async fn delay_multiple_in_flight() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let delayed = temporal::delay(rt.core(), &rt.producer_binding, source, 100);
    let rec = rt.subscribe_recorder(delayed);

    rt.emit_int(source, 1);
    multi_yield(5).await;

    tokio::time::advance(Duration::from_millis(30)).await;
    multi_yield(5).await;
    rt.emit_int(source, 2);
    multi_yield(5).await;

    // At 105ms: first fires.
    tokio::time::advance(Duration::from_millis(75)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(rec.data_values(), vec![TestValue::Int(1)]);

    // At 135ms: second fires.
    tokio::time::advance(Duration::from_millis(30)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(
        rec.data_values(),
        vec![TestValue::Int(1), TestValue::Int(2)]
    );
}

// =========================================================================
// audit
// =========================================================================

#[tokio::test]
async fn audit_emits_latest_after_window() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let audited = temporal::audit(rt.core(), &rt.producer_binding, source, 50);
    let rec = rt.subscribe_recorder(audited);

    // First DATA starts window.
    rt.emit_int(source, 10);
    multi_yield(5).await;

    // More data during window — updates latest, doesn't restart timer.
    tokio::time::advance(Duration::from_millis(20)).await;
    multi_yield(5).await;
    rt.emit_int(source, 20);
    multi_yield(5).await;

    // At 30ms since first DATA — still within 50ms window.
    tokio::time::advance(Duration::from_millis(10)).await;
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert!(rec.data_values().is_empty(), "window hasn't closed yet");

    // At 55ms — window fires. Should emit 20 (latest).
    tokio::time::advance(Duration::from_millis(25)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert_eq!(rec.data_values(), vec![TestValue::Int(20)]);
}

// =========================================================================
// throttle
// =========================================================================

#[tokio::test]
async fn throttle_leading_emits_first_then_drops() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let throttled = temporal::throttle(
        rt.core(),
        &rt.producer_binding,
        source,
        100,
        ThrottleOpts::default(), // leading: true, trailing: false
    );
    let rec = rt.subscribe_recorder(throttled);

    // First DATA — emitted immediately (leading edge).
    rt.emit_int(source, 1);
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(rec.data_values(), vec![TestValue::Int(1)]);

    // Second DATA within window — dropped (no trailing).
    rt.emit_int(source, 2);
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(
        rec.data_values(),
        vec![TestValue::Int(1)],
        "second value dropped"
    );

    // Window expires.
    tokio::time::advance(Duration::from_millis(105)).await;
    multi_yield(10).await;

    // Third DATA — new window, emitted immediately.
    rt.emit_int(source, 3);
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(
        rec.data_values(),
        vec![TestValue::Int(1), TestValue::Int(3)]
    );
}

#[tokio::test]
async fn throttle_trailing_emits_at_window_end() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let throttled = temporal::throttle(
        rt.core(),
        &rt.producer_binding,
        source,
        100,
        ThrottleOpts {
            leading: true,
            trailing: true,
        },
    );
    let rec = rt.subscribe_recorder(throttled);

    // First DATA — leading.
    rt.emit_int(source, 1);
    multi_yield(5).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.
    assert_eq!(rec.data_values(), vec![TestValue::Int(1)]);

    // More data during window — stored for trailing.
    rt.emit_int(source, 2);
    multi_yield(5).await;
    rt.emit_int(source, 3);
    multi_yield(5).await;

    // Window expires — trailing emits latest (3).
    tokio::time::advance(Duration::from_millis(105)).await;
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    assert_eq!(
        rec.data_values(),
        vec![TestValue::Int(1), TestValue::Int(3)]
    );
}

// =========================================================================
// interval
// =========================================================================

#[tokio::test]
async fn interval_emits_incrementing_counter() {
    tokio::time::pause();

    let rt = OpRuntime::new();

    let iv = temporal::interval(rt.core(), &rt.producer_binding, 50);

    // Use a raw sink because interval emits HandleId::new(counter)
    // which isn't in the test binding's value registry.
    let emitted = std::sync::Arc::new(std::sync::Mutex::new(
        Vec::<graphrefly_core::HandleId>::new(),
    ));
    let em = emitted.clone();
    let _sub = rt.core().subscribe(
        iv,
        std::sync::Arc::new(move |msgs: &[graphrefly_core::Message]| {
            for &m in msgs {
                if let graphrefly_core::Message::Data(h) = m {
                    em.lock().unwrap().push(h);
                }
            }
        }),
    );

    // Let the interval task start and process the immediate first tick (skipped).
    multi_yield(10).await;

    // First real tick at 50ms.
    tokio::time::advance(Duration::from_millis(55)).await;
    multi_yield(20).await;

    // Second real tick at 100ms.
    tokio::time::advance(Duration::from_millis(55)).await;
    multi_yield(20).await;

    // Third real tick at 150ms.
    tokio::time::advance(Duration::from_millis(55)).await;
    multi_yield(20).await;
    rt.settle(); // D246: pump deferred timer-task emits owner-side.

    let handles = emitted.lock().unwrap().clone();
    assert!(
        handles.len() >= 2,
        "expected at least 2 interval ticks, got {}",
        handles.len()
    );
    // Counter should be incrementing (starting at 1 to avoid NO_HANDLE).
    if handles.len() >= 2 {
        assert_ne!(handles[0], handles[1], "handles should be distinct");
    }
}

// =========================================================================
// Error propagation tests (/qa F6)
// =========================================================================

#[tokio::test]
async fn debounce_error_releases_pending() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let debounced = temporal::debounce(rt.core(), &rt.producer_binding, source, 50);
    let rec = rt.subscribe_recorder(debounced);

    rt.emit_int(source, 10);
    multi_yield(5).await;

    // Error before timer fires — pending should be released, error propagated.
    rt.core().error(source, rt.intern_int(99));
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    let events = rec.events();
    assert!(
        events.contains(&RecordedEvent::Error(TestValue::Int(99))),
        "error should propagate"
    );
    // Should NOT have emitted the pending value 10.
    assert!(
        !events.contains(&RecordedEvent::Data(TestValue::Int(10))),
        "pending should not emit on error"
    );
}

#[tokio::test]
async fn delay_error_releases_all_pending() {
    tokio::time::pause();

    let rt = OpRuntime::new();
    let source = rt.state_int(None);

    let delayed = temporal::delay(rt.core(), &rt.producer_binding, source, 100);
    let rec = rt.subscribe_recorder(delayed);

    rt.emit_int(source, 1);
    multi_yield(5).await;
    rt.emit_int(source, 2);
    multi_yield(5).await;

    // Error cancels all pending delays.
    rt.core().error(source, rt.intern_int(99));
    multi_yield(10).await;
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    let events = rec.events();
    assert!(
        events.contains(&RecordedEvent::Error(TestValue::Int(99))),
        "error should propagate"
    );
    assert!(
        events
            .iter()
            .filter(|e| matches!(e, RecordedEvent::Data(_)))
            .count()
            == 0,
        "no data should emit after error"
    );
}

#[tokio::test]
async fn sample_notifier_data_then_complete_in_batch() {
    // Regression test for /qa F4: notifier [Data, Complete] in single batch.
    // The sample must both emit the source value AND complete.
    let rt = OpRuntime::new();
    let source = rt.state_int(None);
    let notifier = rt.state_int(None);

    let sampled = temporal::sample(rt.core(), &rt.producer_binding, source, notifier);
    let rec = rt.subscribe_recorder(sampled);

    rt.emit_int(source, 42);

    // Emit then complete on notifier in one batch.
    rt.core().batch(|| {
        rt.emit_int(notifier, 1);
        rt.core().complete(notifier);
    });
    rt.settle(); // D246: pump deferred producer-sink emits owner-side.

    let events = rec.events();
    assert!(
        events.contains(&RecordedEvent::Data(TestValue::Int(42))),
        "should emit source latest on notifier DATA"
    );
    assert!(
        events.contains(&RecordedEvent::Complete),
        "should complete after notifier completes"
    );
}