reifydb-sub-flow 0.10.2

Flow subsystem for stream processing and data flows
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

//! A custom operator arms a timer and is called back when the flow watermark passes it. The
//! operator never reads a clock and is never handed a timestamp on apply: it arms off the row's own
//! #time, and the due timer fires inside the flow transaction that carried the watermark past it.

use reifydb::{
	ConfigKey, SqliteConfig, Value, WithSubsystem, embedded,
	testing::db::{TempDbPath, TestDb},
};
use reifydb_codec::key::encoded::EncodedKey;
use reifydb_core::{
	common::{WindowRequirements, WindowSizeDomain},
	interface::{catalog::flow::OperatorId, flow::OperatorCapability},
	key::operator::state::{GroupId, unmanaged_key_in},
	operator_with::ApplyWith,
	state::timer::TimerKind,
};
use reifydb_sdk::{
	error::Result as SdkResult,
	flow::operator::{
		OperatorMetadata, UnmanagedOperator,
		column::operator::OperatorColumn,
		context::{ClassState, GuestContext, Unmanaged},
		timer::Timer,
		view::{ChangeView, ColumnsView, DiffView, RowView},
	},
	row,
};
use reifydb_value::{
	config::ExtensionParams,
	params::Params,
	value::{
		constraint::TypeConstraint, datetime::DateTime, diff_type::DiffType, duration::Duration,
		frame::frame::Frame, identity::IdentityId, system_columns::time, value_type::ValueType,
	},
};

const TIMEOUT: Duration = Duration::from_seconds_const(20);

// How long after a row's own event time the operator asks to be woken.
const DELAY_MS: i64 = 1_000;

struct AlarmRow {
	g: i32,
	fired_at: i64,
}

row!(AlarmRow {
	g: i32,
	fired_at: i64
});

const ALARM_COLUMNS: &[OperatorColumn] = &[
	OperatorColumn {
		name: "g",
		type_constraint: TypeConstraint::unconstrained(ValueType::Int4),
		description: "group key carried through the timer key",
	},
	OperatorColumn {
		name: "fired_at",
		type_constraint: TypeConstraint::unconstrained(ValueType::Int8),
		description: "the instant the timer was armed for, as handed back on the callback",
	},
];

struct Alarm;

impl OperatorMetadata for Alarm {
	const NAME: &'static str = "alarm";
	const VERSION: &'static str = "0.0.1";
	const DESCRIPTION: &'static str = "test-only operator that emits solely from timer callbacks";
	const INPUT_COLUMNS: &'static [OperatorColumn] = ALARM_COLUMNS;
	const OUTPUT_COLUMNS: &'static [OperatorColumn] = ALARM_COLUMNS;
	const CAPABILITIES: &'static [OperatorCapability] = OperatorCapability::STANDARD;
}

fn group_key(g: i32) -> EncodedKey {
	EncodedKey::new(g.to_be_bytes())
}

impl UnmanagedOperator for Alarm {
	const UNMANAGED_BECAUSE: &'static str = "test operator";
	const WINDOW: WindowRequirements = WindowRequirements {
		takes_window: false,
		kinds: &[],
		domain: WindowSizeDomain::Time,
		needs_pane: false,
	};

	fn create(_operator_id: OperatorId, _params: &ExtensionParams, _with: &ApplyWith) -> SdkResult<Self> {
		Ok(Alarm)
	}

	fn apply(&mut self, ctx: &mut impl GuestContext<Unmanaged>, change: impl ChangeView) -> SdkResult<()> {
		// Emits nothing. Every row this operator produces comes out of on_timer, so a view row is
		// proof that a callback ran - not that a change passed through.
		for i in 0..change.diff_count() {
			let Some(diff) = change.diff(i) else {
				continue;
			};
			if !matches!(diff.kind(), DiffType::Insert) {
				continue;
			}
			let Some(post) = diff.post() else {
				continue;
			};
			for r in 0..post.row_count() {
				let row = post.row(r).expect("row");
				let g = row.i32("g").unwrap().expect("g");
				// The row's own event time; the operator is never told "now".
				let at = row
					.row_time()
					.expect("the substrate must populate #time on an event-time source");
				let key = group_key(g);
				let wake = DateTime::from_millis(at.to_millis() + DELAY_MS);
				ctx.arm_timer(wake, TimerKind::Seal, &key)?;
			}
		}
		Ok(())
	}

	fn on_timer(&mut self, ctx: &mut impl GuestContext<Unmanaged>, timer: Timer<'_>) -> SdkResult<()> {
		let g = i32::from_be_bytes(timer.key.try_into().expect("the timer key round-trips the group key"));
		let key = group_key(g);
		let group = GroupId::of(&key);

		// Per-group state, so the group has something for the retention pass to erase once it ages
		// past its horizon. Without it a group is nothing but an identity and reclaim has no work.
		let fired_at = timer.due.to_millis();
		ctx.state().set(&[(unmanaged_key_in(group, &[]).expect("an empty id fits the keyspace"), fired_at)])?;

		let (row_number, _is_new) = ctx.get_or_create_row_numbers(group, &[key])?.remove(0);
		ctx.emit_insert(
			&[AlarmRow {
				g,
				fired_at,
			}],
			&[row_number],
			&vec![ctx.batch_time(); (&[row_number]).len()],
		)?;
		Ok(())
	}
}

fn setup() -> TestDb {
	TestDb::from(
		embedded::memory()
			.with_flow(|f| f.register_unmanaged_operator::<Alarm>())
			// The retention ledger is the only surface that reports what the reclaim pass
			// actually erased; a short sample cadence keeps the polls inside their timeouts.
			.with_config(ConfigKey::MetricsSampleInterval, Value::duration_milliseconds(20))
			.build()
			.expect("build memory db with flow"),
	)
}

fn query_internal(db: &TestDb, rql: &str) -> Vec<Frame> {
	let result = db.engine().begin_query(IdentityId::root()).expect("begin query").rql(rql, Params::None);
	if let Some(e) = result.error {
		panic!("internal query failed: {e:?}\nrql: {rql}")
	}
	result.frames
}

fn declare(db: &TestDb) {
	db.admin("CREATE NAMESPACE app");
	db.admin("CREATE TABLE app::t { id: int4, g: int4, ts: datetime } with { time: event(ts) }");
	db.admin(
		"CREATE DEFERRED VIEW app::v { g: int4, fired_at: int8 } AS { FROM app::t APPLY alarm{} WITH { lateness: 1h } }",
	);
}

#[test]
fn an_armed_timer_fires_only_once_the_event_watermark_passes_it() {
	// A timer armed for event instant T must stay silent while the flow's event watermark sits
	// below T, however much real time passes or however many other rows arrive. Arriving rows are
	// the only thing that moves time forward.
	let db = setup();
	declare(&db);

	// Arms a callback for event instant 1000. The watermark is 0, so nothing is due.
	db.command(r#"INSERT app::t [{ id: 1, g: 1, ts: "1970-01-01T00:00:00Z" }]"#);

	// Advances the watermark to 500, still under 1000, separating "the watermark passed it" from
	// "another change came through".
	db.command(r#"INSERT app::t [{ id: 2, g: 2, ts: "1970-01-01T00:00:00.500Z" }]"#);
	assert!(db.await_all_flows(TIMEOUT), "the flow must drain before the view can be judged empty");

	assert_eq!(db.row_count("FROM app::v"), 0, "no timer is due at watermark 500; the view must still be empty");

	// Crosses both armed instants (1000 and 1500) at once.
	db.command(r#"INSERT app::t [{ id: 3, g: 3, ts: "1970-01-01T00:01:00Z" }]"#);

	db.await_row_count("FROM app::v", 2, TIMEOUT);
}

#[test]
fn a_fired_timer_hands_back_the_instant_and_key_it_was_armed_with() {
	// The callback is the only channel through which an operator learns anything about time, so the
	// (at, key) pair must come back byte for byte as armed - operators key state by the instant, so
	// a truncation or rescale anywhere on the wire corrupts it silently.
	let db = setup();
	declare(&db);

	db.command(r#"INSERT app::t [{ id: 1, g: 7, ts: "1970-01-01T00:00:02.250Z" }]"#);
	// Carries the watermark past group 7's armed instant, and arms its own for 601000.
	db.command(r#"INSERT app::t [{ id: 2, g: 9, ts: "1970-01-01T00:10:00Z" }]"#);
	// Carries the watermark past group 9's. Its own timer (661000) stays armed and unfired, which
	// is what holds the view at exactly two rows.
	db.command(r#"INSERT app::t [{ id: 3, g: 11, ts: "1970-01-01T00:11:00Z" }]"#);

	db.await_row_count("FROM app::v", 2, TIMEOUT);

	let armed = |g: i32, fired_at: i64| {
		let rql = format!("FROM app::v filter {{ g == {g} and fired_at == {fired_at} }}");
		assert_eq!(
			db.row_count(&rql),
			1,
			"group {g} must be called back at exactly {fired_at}; view now: {:?}",
			db.query_as_root("FROM app::v", ())
		);
	};

	// 2250 + 1000, sub-second precision intact: a millisecond lost anywhere on the wire shows here.
	armed(7, 3_250);
	armed(9, 601_000);

	assert_eq!(
		db.row_count("FROM app::v"),
		2,
		"only timers the watermark has passed may fire; group 11's is still armed"
	);
}

#[test]
fn a_row_emitted_from_a_timer_carries_the_firing_instant_as_its_event_time() {
	// A timer emission is an event-time fact: it happened at the instant armed for, not at the
	// wall-clock moment the callback ran. Stamping from the clock yanks every downstream
	// event-time consumer's watermark to the present, invisibly in the view's own columns.
	let db = setup();
	declare(&db);

	db.command(r#"INSERT app::t [{ id: 1, g: 7, ts: "1970-01-01T00:00:02.250Z" }]"#);
	db.command(r#"INSERT app::t [{ id: 2, g: 9, ts: "1970-01-01T00:10:00Z" }]"#);

	db.await_row_count("FROM app::v", 1, TIMEOUT);

	let frames = query_internal(&db, "FROM app::v filter { g == 7 }");
	let stamps: Vec<DateTime> =
		frames.iter().flat_map(|frame| time(&frame.batch).expect("#time").iter().copied()).collect();

	assert_eq!(
		stamps,
		vec![DateTime::from_millis(3_250)],
		"the emitted row's #time must be the instant the timer fired for, not the wall clock"
	);
}

#[test]
fn interning_inside_a_callback_stamps_the_firing_instant_not_the_change_that_woke_it() {
	// A group with no further input of its own must still fire on another group's watermark.
	let db = setup();
	db.admin("CREATE NAMESPACE app");
	db.admin("CREATE TABLE app::t { id: int4, g: int4, ts: datetime } with { time: event(ts) }");
	db.admin(
		"CREATE DEFERRED VIEW app::v { g: int4, fired_at: int8 } AS { FROM app::t APPLY alarm{} WITH { lateness: 1s } }",
	);

	db.command(r#"INSERT app::t [{ id: 1, g: 1, ts: "2026-01-01T00:00:00Z" }]"#);
	// Releases group 1's timer, which re-interns group 1 from inside the callback.
	db.command(r#"INSERT app::t [{ id: 2, g: 2, ts: "2026-01-01T00:10:00Z" }]"#);

	assert_eq!(
		db.await_row_count("FROM app::v filter { g == 1 }", 1, TIMEOUT),
		1,
		"group 1's timer must be released by the second insert's watermark and re-intern from inside \
		 the callback"
	);
}

struct Snooze {
	disarm_offset_ms: i64,
}

impl OperatorMetadata for Snooze {
	const NAME: &'static str = "snooze";
	const VERSION: &'static str = "0.0.1";
	const DESCRIPTION: &'static str =
		"test-only operator that re-arms one timer per group, cancelling the instant it armed before";
	const INPUT_COLUMNS: &'static [OperatorColumn] = ALARM_COLUMNS;
	const OUTPUT_COLUMNS: &'static [OperatorColumn] = ALARM_COLUMNS;
	const CAPABILITIES: &'static [OperatorCapability] = OperatorCapability::STANDARD;
}

impl UnmanagedOperator for Snooze {
	const UNMANAGED_BECAUSE: &'static str = "test operator";
	const WINDOW: WindowRequirements = WindowRequirements {
		takes_window: false,
		kinds: &[],
		domain: WindowSizeDomain::Time,
		needs_pane: false,
	};

	fn create(_operator_id: OperatorId, params: &ExtensionParams, _with: &ApplyWith) -> SdkResult<Self> {
		Ok(Snooze {
			disarm_offset_ms: params.i64_or("disarm_offset", 0),
		})
	}

	fn apply(&mut self, ctx: &mut impl GuestContext<Unmanaged>, change: impl ChangeView) -> SdkResult<()> {
		// The session-window shape reduced to essentials: every row pushes the group's wake-up
		// later, so the instant armed a moment ago must be cancelled rather than left to fire.
		for i in 0..change.diff_count() {
			let Some(diff) = change.diff(i) else {
				continue;
			};
			if !matches!(diff.kind(), DiffType::Insert) {
				continue;
			}
			let Some(post) = diff.post() else {
				continue;
			};
			for r in 0..post.row_count() {
				let row = post.row(r).expect("row");
				let g = row.i32("g").unwrap().expect("g");
				let at = row
					.row_time()
					.expect("the substrate must populate #time on an event-time source");
				let key = group_key(g);
				let group = GroupId::of(&key);
				let armed_key = unmanaged_key_in(group, &[]).expect("an empty id fits the keyspace");

				let prior = ctx.state().get::<i64>(std::slice::from_ref(&armed_key))?.pop().flatten();
				if let Some(prior) = prior {
					// Zero in the honest case; non-zero aims the disarm past what
					// was armed, which is how the control test proves the wheel
					// matches on the exact instant.
					let target = prior + self.disarm_offset_ms;
					ctx.disarm_timer(DateTime::from_millis(target), TimerKind::Seal, &key)?;
				}

				let wake = at.to_millis() + DELAY_MS;
				ctx.arm_timer(DateTime::from_millis(wake), TimerKind::Seal, &key)?;
				ctx.state().set(&[(armed_key.clone(), wake)])?;
			}
		}
		Ok(())
	}

	fn on_timer(&mut self, ctx: &mut impl GuestContext<Unmanaged>, timer: Timer<'_>) -> SdkResult<()> {
		let g = i32::from_be_bytes(timer.key.try_into().expect("the timer key round-trips the group key"));
		let group = GroupId::of(&group_key(g));
		let fired_at = timer.due.to_millis();

		// Keyed by the firing instant, not the group, so a timer that should have been cancelled
		// surfaces as an extra row instead of overwriting the surviving timer's.
		let row_key = EncodedKey::new(timer.due.to_millis().to_be_bytes());
		let (row_number, _is_new) = ctx.get_or_create_row_numbers(group, &[row_key])?.remove(0);
		ctx.emit_insert(
			&[AlarmRow {
				g,
				fired_at,
			}],
			&[row_number],
			&vec![ctx.batch_time(); (&[row_number]).len()],
		)?;
		Ok(())
	}
}

fn setup_snooze() -> TestDb {
	TestDb::from(
		embedded::memory()
			.with_flow(|f| f.register_unmanaged_operator::<Snooze>())
			.build()
			.expect("build memory db with flow"),
	)
}

fn declare_snooze(db: &TestDb, config: &str) {
	db.admin("CREATE NAMESPACE app");
	db.admin("CREATE TABLE app::t { id: int4, g: int4, ts: datetime } with { time: event(ts) }");
	db.admin(&format!(
		"CREATE DEFERRED VIEW app::v {{ g: int4, fired_at: int8 }} AS {{ FROM app::t APPLY snooze{{{}}} WITH {{ lateness: 1h }} }}",
		config
	));
}

fn feed_snooze(db: &TestDb) {
	// Group 1 arms at 1000, then re-arms at 1500 and cancels the 1000. Group 99 exists only to
	// carry the watermark past both instants without touching group 1's armed timer.
	db.command(r#"INSERT app::t [{ id: 1, g: 1, ts: "1970-01-01T00:00:00Z" }]"#);
	db.command(r#"INSERT app::t [{ id: 2, g: 1, ts: "1970-01-01T00:00:00.500Z" }]"#);
	db.command(r#"INSERT app::t [{ id: 3, g: 99, ts: "1970-01-01T00:01:00Z" }]"#);
}

#[test]
fn a_guest_can_disarm_a_timer_it_armed() {
	// Every window kind re-arms as its last event time rises, and session windows re-arm on every
	// row, so without disarm the wheel accumulates one stale timer per row and each fires a seal
	// for a window that has already moved on. Driven through the FFI callback, not the wheel.
	let db = setup_snooze();
	declare_snooze(&db, "");
	feed_snooze(&db);

	db.await_row_count("FROM app::v", 1, TIMEOUT);

	assert_eq!(
		db.row_count("FROM app::v filter { fired_at == 1500 }"),
		1,
		"the surviving re-armed timer must fire at the instant the last row pushed it to"
	);
	assert_eq!(
		db.row_count("FROM app::v filter { fired_at == 1000 }"),
		0,
		"the instant the operator cancelled must never fire"
	);
}

#[test]
fn a_guest_disarm_must_match_the_exact_instant_it_armed() {
	// The control for the test above. A disarm carries its instant across the FFI boundary as
	// millis; rounded, rescaled or ignored, a disarm aimed anywhere near would still cancel and
	// the test above stays green over a blunt wheel. One millisecond off must miss.
	let db = setup_snooze();
	declare_snooze(&db, " disarm_offset: 1 ");
	feed_snooze(&db);

	db.await_row_count("FROM app::v", 2, TIMEOUT);

	assert_eq!(
		db.row_count("FROM app::v filter { fired_at == 1000 }"),
		1,
		"a disarm aimed one millisecond off must leave the armed timer alone"
	);
	assert_eq!(db.row_count("FROM app::v filter { fired_at == 1500 }"), 1, "the re-armed timer fires regardless");
}

fn open_with_alarm(path: &TempDbPath) -> TestDb {
	TestDb::from(
		embedded::sqlite(SqliteConfig::new(path))
			.with_flow(|f| f.register_unmanaged_operator::<Alarm>())
			.build()
			.expect("open the sqlite db"),
	)
}

#[test]
fn a_parent_timer_emission_reaches_its_fused_child() {
	// A fused child sees its parent only through what the parent emitted in the unit's txn, timer callbacks
	// included.
	let path = TempDbPath::new("custom_operator_timer_fused_child");
	{
		let mut db = open_with_alarm(&path);
		declare(&db);
		db.admin(
			"CREATE DEFERRED VIEW app::c { g: int4, fired_at: int8 } AS { FROM app::v | filter { g != 9 } }",
		);
		assert!(db.await_all_flows(TIMEOUT), "the creates must settle before the stop");
		db.stop();
	}
	let mut db = open_with_alarm(&path);
	assert!(db.await_all_flows(TIMEOUT), "the bootstrap must settle before the first write");

	db.command(r#"INSERT app::t [{ id: 1, g: 1, ts: "1970-01-01T00:00:00Z" }]"#);
	db.command(r#"INSERT app::t [{ id: 2, g: 2, ts: "1970-01-01T00:01:00Z" }]"#);
	db.await_row_count("FROM app::v", 1, TIMEOUT);
	assert_eq!(db.await_exact_row_count("FROM app::c", 1, TIMEOUT), 1, "a timer fired by a step must reach app::c");

	db.admin("call storage::advance(app::t, cast('1970-01-01T01:00:00Z', datetime))");
	db.await_row_count("FROM app::v", 2, TIMEOUT);
	assert_eq!(
		db.await_exact_row_count("FROM app::c", 2, TIMEOUT),
		2,
		"a timer fired with no data behind it must reach app::c too; app::v now: {:?}",
		db.query("FROM app::v")
	);
	db.stop();
}