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);
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<()> {
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 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);
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>())
.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() {
let db = setup();
declare(&db);
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: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");
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() {
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.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", ())
);
};
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() {
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() {
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" }]"#);
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<()> {
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 {
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();
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) {
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() {
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() {
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() {
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();
}