test(flow): trim eval offset edge coverage

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
discord9
2026-09-01 17:00:12 +08:00
parent 1f81fa7aa7
commit 10efae9c97
7 changed files with 8 additions and 458 deletions
+2 -118
View File
@@ -25,8 +25,8 @@ use table::table_name::TableName;
use crate::ddl::DdlContext;
use crate::ddl::create_flow::{
CreateFlowData, CreateFlowProcedure, CreateFlowState, DEFER_ON_MISSING_SOURCE_KEY,
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType, ceil_to_boundary, ceil_to_whole_sec,
ceil_whole_sec_from_parts, defer_on_missing_source, effective_eval_schedule_from_flow_info,
FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType, ceil_to_whole_sec,
defer_on_missing_source, effective_eval_schedule_from_flow_info,
resolve_schedule_defaults_into_task, validate_flow_options,
};
use crate::ddl::test_util::create_table::test_create_table_task;
@@ -619,101 +619,6 @@ fn test_resolve_schedule_with_eval_offset_uses_epoch_phase() {
);
}
#[test]
fn test_resolve_schedule_prepare_instant_ceils_to_whole_sec() {
// A prepare instant with a sub-second fraction must round UP: the first
// boundary must be >= ceil(instant), never before it.
let instant = chrono::DateTime::from_timestamp(1_700_000_000, 500_000_000).unwrap();
// ceil = 1_700_000_001
let ceil = ceil_to_whole_sec(instant).unwrap();
assert_eq!(ceil, 1_700_000_001);
// exact whole second stays unchanged
let exact = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
assert_eq!(ceil_to_whole_sec(exact).unwrap(), 1_700_000_000);
// just before a boundary with an interval of 60s and anchor 0
// instant = 1_700_000_059.9 -> ceil = 1_700_000_060 -> boundary 1_700_000_060
let instant = chrono::DateTime::from_timestamp(1_700_000_059, 999_000_000).unwrap();
assert_eq!(ceil_to_whole_sec(instant).unwrap(), 1_700_000_060);
// Simulate resolution with a fixed "now": not directly injectable, so
// verify the ceil helper's contract used by resolve_schedule_defaults_into_task.
let anchor = 120;
let interval = 3600;
let boundary = ceil_to_boundary(ceil, anchor, interval).unwrap();
assert!(boundary >= ceil);
assert_eq!((boundary - anchor) % interval, 0);
// ceil((1_700_000_001 - 120) / 3600) computed with plain integer arithmetic
let diff = 1_700_000_001_i64 - 120;
let k = (diff + 3599) / 3600;
assert_eq!(boundary, 120_i64 + 3600 * k);
}
#[test]
fn test_ceil_to_whole_sec_nanosecond_precision_and_overflow() {
// Exact whole second: unchanged.
let exact = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
assert_eq!(ceil_to_whole_sec(exact).unwrap(), 1_700_000_000);
// +1ns must round up to the next second.
let plus_1ns = chrono::DateTime::from_timestamp(1_700_000_000, 1).unwrap();
assert_eq!(ceil_to_whole_sec(plus_1ns).unwrap(), 1_700_000_001);
// +999_999ns must round up.
let plus_999_999 = chrono::DateTime::from_timestamp(1_700_000_000, 999_999).unwrap();
assert_eq!(ceil_to_whole_sec(plus_999_999).unwrap(), 1_700_000_001);
// +500ms must round up.
let plus_500ms = chrono::DateTime::from_timestamp(1_700_000_000, 500_000_000).unwrap();
assert_eq!(ceil_to_whole_sec(plus_500ms).unwrap(), 1_700_000_001);
// Overflow path: an instant whose whole-second part is already i64::MAX
// with a sub-second fraction cannot be rounded up. chrono cannot represent
// such an instant, so the pure helper is exercised directly.
let err = ceil_whole_sec_from_parts(i64::MAX, true).unwrap_err();
assert!(err.to_string().contains("timestamp overflow"), "{err}");
assert_eq!(
ceil_whole_sec_from_parts(i64::MAX, false).unwrap(),
i64::MAX
);
assert_eq!(
ceil_whole_sec_from_parts(1_700_000_000, true).unwrap(),
1_700_000_001
);
}
#[test]
fn test_ceil_to_boundary_is_fallible_near_i64_bounds() {
// Normal cases still work.
assert_eq!(ceil_to_boundary(-10, 0, 60).unwrap(), 0);
assert_eq!(ceil_to_boundary(0, 0, 60).unwrap(), 0);
assert_eq!(ceil_to_boundary(1, 0, 60).unwrap(), 60);
assert_eq!(ceil_to_boundary(60, 0, 60).unwrap(), 60);
assert_eq!(ceil_to_boundary(101, 100, 60).unwrap(), 160);
assert_eq!(ceil_to_boundary(50, 0, 0).unwrap(), 50);
// The next boundary after i64::MAX cannot fit in i64: must error, never
// clamp to the non-phase i64::MAX.
assert!(ceil_to_boundary(i64::MAX, 0, 60).is_err());
assert!(ceil_to_boundary(i64::MAX - 1, i64::MIN, 60).is_err());
// A boundary that *is* representable near the top succeeds and stays on
// the phase.
// ceil(9223372036854775800, 0, 60) = 9223372036854775800 (a multiple of 60).
assert_eq!(
ceil_to_boundary(9_223_372_036_854_775_800_i64, 0, 60).unwrap(),
9_223_372_036_854_775_800_i64
);
// And one that needs rounding up past the representable range errors.
assert!(ceil_to_boundary(9_223_372_036_854_775_800_i64 + 1, 0, 60).is_err());
// With a larger interval a boundary just under i64::MAX is representable.
// ceil(1, 0, 9223372036854775800) = 9223372036854775800.
let big_interval = 9_223_372_036_854_775_800_i64;
assert_eq!(ceil_to_boundary(1, 0, big_interval).unwrap(), big_interval);
// But the next boundary (2 * interval) overflows.
assert!(ceil_to_boundary(big_interval + 1, 0, big_interval).is_err());
}
#[test]
fn test_resolve_schedule_or_replace_preserves_and_recomputes() {
let sink = TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table");
@@ -877,27 +782,6 @@ fn test_create_flow_task_proto_roundtrip_preserves_offset_key() {
assert_eq!(reparsed.flow_options, typed.flow_options);
}
#[test]
fn test_create_flow_task_proto_rejects_malformed_offset_key() {
let mut task = test_create_flow_task(
"my_flow",
vec![],
TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "my_sink_table"),
false,
);
task.flow_options.insert(
"__greptime_internal_eval_offset_secs".to_string(),
"abc".to_string(),
);
let pb: api::v1::meta::CreateFlowTask = task.into();
let err = CreateFlowTask::try_from(pb).unwrap_err();
assert!(
err.to_string()
.contains("Invalid internal eval offset payload"),
"unexpected error: {err}"
);
}
#[test]
fn test_effective_eval_schedule_prefers_typed_config() {
let typed = FlowScheduleConfig {
@@ -403,32 +403,6 @@ mod test {
assert!(EvalSchedule::from_config(Some(300), Some(&c)).is_err());
}
#[test]
fn from_config_rejects_invalid_anchor_and_start_phase() {
// Negative anchor.
let mut c = config(FlowMissedTickPolicy::BoundedCatchUp);
c.anchor_secs = -1;
let err = EvalSchedule::from_config(Some(300), Some(&c)).unwrap_err();
assert!(err.to_string().contains("anchor_secs"));
// Anchor not less than interval.
let mut c = config(FlowMissedTickPolicy::BoundedCatchUp);
c.anchor_secs = 300;
assert!(EvalSchedule::from_config(Some(300), Some(&c)).is_err());
// Start before anchor.
let mut c = config(FlowMissedTickPolicy::BoundedCatchUp);
c.start_secs = 5;
let err = EvalSchedule::from_config(Some(300), Some(&c)).unwrap_err();
assert!(err.to_string().contains("start_secs"));
// Start not phase-consistent with anchor.
let mut c = config(FlowMissedTickPolicy::BoundedCatchUp);
c.start_secs = 70; // (70 - 10) % 300 != 0
let err = EvalSchedule::from_config(Some(300), Some(&c)).unwrap_err();
assert!(err.to_string().contains("start_secs"));
}
#[test]
fn nonzero_anchor_due_selection_follows_phase() {
// anchor=120 (i.e. `EVAL OFFSET '2 minutes'`), interval=3600:
@@ -499,72 +473,6 @@ mod test {
assert!(invalid.next_scheduled_time_after(0).is_err());
}
#[test]
fn extreme_cursor_and_start_do_not_overflow_subtraction() {
// cursor < start: the next scheduled time is `start` itself. The
// `cursor - start` subtraction would overflow i64, but the i128 path
// returns the exact `start` without panicking or wrapping.
let s = EvalSchedule {
interval_secs: 60,
anchor_secs: 0,
start_secs: i64::MAX,
missed_tick_policy: FlowMissedTickPolicy::Skip,
max_runs: 3,
max_lag_secs: 900,
};
assert_eq!(s.next_scheduled_time_after(i64::MIN).unwrap(), i64::MAX);
// cursor >= start with `cursor - start` overflowing i64: the next
// boundary computed in i128 exceeds i64 and must be an explicit error,
// never a wrapped or saturated value.
let s = EvalSchedule {
interval_secs: 60,
anchor_secs: 0,
start_secs: i64::MIN,
missed_tick_policy: FlowMissedTickPolicy::Skip,
max_runs: 3,
max_lag_secs: 900,
};
let err = s.next_scheduled_time_after(i64::MAX).unwrap_err();
assert!(err.to_string().contains("does not fit in i64"));
}
#[test]
fn near_i64_max_due_selection_stays_on_lattice() {
// anchor=0, start=0, interval=60, wall_now = i64::MAX: every selected
// scheduled time must be an exact multiple of 60, and the latest kept
// time must be `<= wall_now`.
let s = EvalSchedule {
interval_secs: 60,
anchor_secs: 0,
start_secs: 0,
missed_tick_policy: FlowMissedTickPolicy::BoundedCatchUp,
max_runs: 3,
max_lag_secs: 86400,
};
let due = select_due_scheduled_times(&s, 0, i64::MAX).unwrap();
assert_eq!(due.scheduled_times_secs.len(), 3);
for t in &due.scheduled_times_secs {
assert_eq!(t % 60, 0);
}
// skipped = total_count - keep_count with total_count =
// (i64::MAX / 60) + 1 and keep_count = max_runs = 3.
assert_eq!(due.skipped, 153722867280912927);
// Skip policy keeps only the latest due time, also on-lattice.
let s = EvalSchedule {
interval_secs: 60,
anchor_secs: 0,
start_secs: 0,
missed_tick_policy: FlowMissedTickPolicy::Skip,
max_runs: 3,
max_lag_secs: 86400,
};
let due = select_due_scheduled_times(&s, 0, i64::MAX).unwrap();
assert_eq!(due.scheduled_times_secs, vec![9223372036854775800]);
assert_eq!(due.skipped, 153722867280912929);
}
#[test]
fn due_scheduled_time_selection_handles_empty_and_start_boundary() {
let s = schedule(120, FlowMissedTickPolicy::BoundedCatchUp, 10, 3600);
-56
View File
@@ -888,62 +888,6 @@ fn test_scheduled_loop_arithmetic_near_i64_boundary() {
assert!(sleep_delta_secs(100, 200).is_err());
}
/// A scheduled time whose millisecond product exceeds `i64` must fail as an
/// explicit error before any execution — never run with a saturated
/// `i64::MAX` millis value — and must not leak the extension into the task
/// state.
#[tokio::test]
async fn test_scheduled_time_millis_overflow_is_explicit_error() {
let TestTaskParts {
task, query_engine, ..
} = new_test_task_engine_and_plan_with_query(
"SELECT number, ts FROM numbers_with_ts",
"missing_sink",
)
.await;
let (frontend_client, _handler) =
FrontendClient::from_empty_grpc_handler(QueryOptions::default());
let frontend_client = Arc::new(frontend_client);
for scheduled_time_secs in [i64::MAX, i64::MAX / 1000 + 1] {
let outcome = task
.execute_once_serialized_at_scheduled_time(
&query_engine,
&frontend_client,
scheduled_time_secs,
)
.await;
let err = outcome.result.expect_err(
"unrepresentable scheduled time must be an explicit error, not a clamped run",
);
assert!(
err.to_string().contains("milliseconds"),
"unexpected error for {scheduled_time_secs}: {err}"
);
assert!(
outcome.new_query.is_none(),
"no query should be generated for an unrepresentable scheduled time"
);
// The extension must never have been installed (nothing to leak).
assert_eq!(
task.state
.read()
.unwrap()
.query_ctx
.extension(FLOW_SCHEDULED_TIME_MILLIS),
None,
"FLOW_SCHEDULED_TIME_MILLIS must not be set for an unrepresentable scheduled time"
);
assert!(
!task
.frontend_extensions()
.contains_key(FLOW_SCHEDULED_TIME_MILLIS)
);
}
}
fn output_with_region_watermarks(
watermarks: impl IntoIterator<Item = (u64, Option<u64>)>,
) -> OutputWithMetrics {
-28
View File
@@ -3459,34 +3459,6 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;";
assert!(reject_spoofed_internal_flow_transport_keys(&HashMap::new()).is_ok());
}
#[test]
fn test_validate_eval_offset_operator_boundary() {
// offset without interval
let err = validate_eval_offset(Some(60), None).unwrap_err();
assert!(
err.to_string()
.contains("EVAL OFFSET requires EVAL INTERVAL"),
"unexpected error: {err}"
);
// negative / equal / greater than interval
for offset_secs in [-1, 300, 301] {
let err = validate_eval_offset(Some(offset_secs), Some(300)).unwrap_err();
assert!(
err.to_string()
.contains("EVAL OFFSET must be in range [0, EVAL INTERVAL)"),
"unexpected error for offset {offset_secs}: {err}"
);
}
// valid offsets (including zero) are accepted
for offset_secs in [0, 1, 299] {
validate_eval_offset(Some(offset_secs), Some(300)).unwrap();
}
validate_eval_offset(None, None).unwrap();
validate_eval_offset(None, Some(300)).unwrap();
}
#[test]
fn test_name_is_match() {
assert!(!NAME_PATTERN_REG.is_match("/adaf"));
-38
View File
@@ -2174,44 +2174,6 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"#;
err.contains("EVAL INTERVAL must be a whole number of seconds"),
"unexpected error: {err}"
);
// fractional-second interval without offset is still allowed (truncated
// as before for backward compatibility)
let sql = r#"
CREATE FLOW task_fractional_interval_only
SINK TO schema_1.table_1
EVAL INTERVAL '1.5 seconds'
AS
SELECT max(c1), min(c2) FROM schema_2.table_2;"#;
let create_task = parse_create_flow(sql);
assert_eq!(create_task.eval_interval, Some(1));
assert_eq!(create_task.eval_offset, None);
// month-bearing interval/offset is rejected
for clause in [
"EVAL INTERVAL '1 month'",
"EVAL INTERVAL '1 hour'\nEVAL OFFSET '1 month'",
] {
let sql = format!(
r#"
CREATE FLOW task_month
SINK TO schema_1.table_1
{clause}
AS
SELECT max(c1), min(c2) FROM schema_2.table_2;"#
);
let err = ParserContext::create_with_dialect(
&sql,
&GreptimeDbDialect {},
ParseOptions::default(),
)
.unwrap_err()
.to_string();
assert!(
err.contains("Interval with months is not allowed"),
"unexpected error for clause {clause}: {err}"
);
}
}
#[test]
@@ -20,17 +20,6 @@ GROUP BY date_trunc('second', now());
Affected Rows: 0
-- EVAL INTERVAL without an offset is epoch-anchored: even seconds (2k).
CREATE FLOW eval_zero_offset_phase_flow
SINK TO eval_zero_offset_phase_sink
EVAL INTERVAL '2s'
AS
SELECT date_trunc('second', now()) AS ts, count(v) AS c
FROM eval_offset_input
GROUP BY date_trunc('second', now());
Affected Rows: 0
SHOW CREATE FLOW eval_offset_phase_flow;
+------------------------+------------------------------------------------------------------------------------------------------------------------+
@@ -55,52 +44,17 @@ SELECT flow_definition FROM information_schema.flows WHERE flow_name = 'eval_off
| AS SELECT date_trunc('second', now()) AS ts, count(v) AS c FROM eval_offset_input GROUP BY date_trunc('second', now()) |
+------------------------------------------------------------------------------------------------------------------------+
-- A zero offset is canonicalized away: SHOW CREATE omits EVAL OFFSET.
CREATE FLOW eval_zero_offset_canonical_flow
SINK TO eval_zero_offset_canonical_sink
EVAL INTERVAL '2s'
EVAL OFFSET '0s'
AS
SELECT date_trunc('second', now()) AS ts, count(v) AS c
FROM eval_offset_input
GROUP BY date_trunc('second', now());
Affected Rows: 0
SHOW CREATE FLOW eval_zero_offset_canonical_flow;
+---------------------------------+------------------------------------------------------------------------------------------------------------------------+
| Flow | Create Flow |
+---------------------------------+------------------------------------------------------------------------------------------------------------------------+
| eval_zero_offset_canonical_flow | CREATE FLOW IF NOT EXISTS eval_zero_offset_canonical_flow |
| | SINK TO public.eval_zero_offset_canonical_sink |
| | EVAL INTERVAL '2 s' |
| | AS SELECT date_trunc('second', now()) AS ts, count(v) AS c FROM eval_offset_input GROUP BY date_trunc('second', now()) |
+---------------------------------+------------------------------------------------------------------------------------------------------------------------+
SELECT flow_definition FROM information_schema.flows WHERE flow_name = 'eval_zero_offset_canonical_flow';
+------------------------------------------------------------------------------------------------------------------------+
| flow_definition |
+------------------------------------------------------------------------------------------------------------------------+
| CREATE FLOW IF NOT EXISTS eval_zero_offset_canonical_flow |
| SINK TO public.eval_zero_offset_canonical_sink |
| EVAL INTERVAL '2 s' |
| AS SELECT date_trunc('second', now()) AS ts, count(v) AS c FROM eval_offset_input GROUP BY date_trunc('second', now()) |
+------------------------------------------------------------------------------------------------------------------------+
INSERT INTO eval_offset_input VALUES
(now(), 'a', 1.0),
(now(), 'b', 2.0);
Affected Rows: 2
-- Let both scheduled flows evaluate at least once.
-- Let the scheduled flow evaluate at least once.
-- SQLNESS SLEEP 5s
-- Prove the offset phase: every row the offset flow wrote has an odd
-- second-of-minute (1 + 2k is always odd), while the zero-offset flow wrote
-- even seconds (2k is always even). This is deterministic regardless of the
-- exact wall-clock alignment of the evaluations.
-- second-of-minute (1 + 2k is always odd). This is deterministic regardless
-- of the exact wall-clock alignment of the evaluations.
SELECT
count(*) > 0 AS offset_flow_ran,
bool_and(date_part('second', ts)::BIGINT % 2 = 1) AS offset_flow_at_odd_seconds
@@ -112,17 +66,6 @@ FROM eval_offset_phase_sink;
| true | true |
+-----------------+----------------------------+
SELECT
count(*) > 0 AS zero_offset_flow_ran,
bool_and(date_part('second', ts)::BIGINT % 2 = 0) AS zero_offset_flow_at_even_seconds
FROM eval_zero_offset_phase_sink;
+----------------------+----------------------------------+
| zero_offset_flow_ran | zero_offset_flow_at_even_seconds |
+----------------------+----------------------------------+
| true | true |
+----------------------+----------------------------------+
-- Invalid syntax / validation cases.
CREATE FLOW invalid_eval_offset_no_interval
SINK TO invalid_eval_offset_sink
@@ -155,38 +98,14 @@ AS SELECT 1;
Error: 1004(InvalidArguments), Invalid interval provided: EVAL INTERVAL must be a whole number of seconds when EVAL OFFSET is specified
CREATE FLOW invalid_eval_offset_month
SINK TO invalid_eval_offset_sink
EVAL INTERVAL '1 hour'
EVAL OFFSET '1 month'
AS SELECT 1;
Error: 1004(InvalidArguments), Invalid interval provided: Interval with months is not allowed in EVAL OFFSET
DROP FLOW eval_offset_phase_flow;
Affected Rows: 0
DROP FLOW eval_zero_offset_phase_flow;
Affected Rows: 0
DROP FLOW eval_zero_offset_canonical_flow;
Affected Rows: 0
DROP TABLE eval_offset_phase_sink;
Affected Rows: 0
DROP TABLE eval_zero_offset_phase_sink;
Affected Rows: 0
DROP TABLE eval_zero_offset_canonical_sink;
Affected Rows: 0
DROP TABLE eval_offset_input;
Affected Rows: 0
@@ -17,54 +17,25 @@ SELECT date_trunc('second', now()) AS ts, count(v) AS c
FROM eval_offset_input
GROUP BY date_trunc('second', now());
-- EVAL INTERVAL without an offset is epoch-anchored: even seconds (2k).
CREATE FLOW eval_zero_offset_phase_flow
SINK TO eval_zero_offset_phase_sink
EVAL INTERVAL '2s'
AS
SELECT date_trunc('second', now()) AS ts, count(v) AS c
FROM eval_offset_input
GROUP BY date_trunc('second', now());
SHOW CREATE FLOW eval_offset_phase_flow;
SELECT flow_definition FROM information_schema.flows WHERE flow_name = 'eval_offset_phase_flow';
-- A zero offset is canonicalized away: SHOW CREATE omits EVAL OFFSET.
CREATE FLOW eval_zero_offset_canonical_flow
SINK TO eval_zero_offset_canonical_sink
EVAL INTERVAL '2s'
EVAL OFFSET '0s'
AS
SELECT date_trunc('second', now()) AS ts, count(v) AS c
FROM eval_offset_input
GROUP BY date_trunc('second', now());
SHOW CREATE FLOW eval_zero_offset_canonical_flow;
SELECT flow_definition FROM information_schema.flows WHERE flow_name = 'eval_zero_offset_canonical_flow';
INSERT INTO eval_offset_input VALUES
(now(), 'a', 1.0),
(now(), 'b', 2.0);
-- Let both scheduled flows evaluate at least once.
-- Let the scheduled flow evaluate at least once.
-- SQLNESS SLEEP 5s
-- Prove the offset phase: every row the offset flow wrote has an odd
-- second-of-minute (1 + 2k is always odd), while the zero-offset flow wrote
-- even seconds (2k is always even). This is deterministic regardless of the
-- exact wall-clock alignment of the evaluations.
-- second-of-minute (1 + 2k is always odd). This is deterministic regardless
-- of the exact wall-clock alignment of the evaluations.
SELECT
count(*) > 0 AS offset_flow_ran,
bool_and(date_part('second', ts)::BIGINT % 2 = 1) AS offset_flow_at_odd_seconds
FROM eval_offset_phase_sink;
SELECT
count(*) > 0 AS zero_offset_flow_ran,
bool_and(date_part('second', ts)::BIGINT % 2 = 0) AS zero_offset_flow_at_even_seconds
FROM eval_zero_offset_phase_sink;
-- Invalid syntax / validation cases.
CREATE FLOW invalid_eval_offset_no_interval
SINK TO invalid_eval_offset_sink
@@ -89,16 +60,6 @@ EVAL INTERVAL '1.5s'
EVAL OFFSET '1s'
AS SELECT 1;
CREATE FLOW invalid_eval_offset_month
SINK TO invalid_eval_offset_sink
EVAL INTERVAL '1 hour'
EVAL OFFSET '1 month'
AS SELECT 1;
DROP FLOW eval_offset_phase_flow;
DROP FLOW eval_zero_offset_phase_flow;
DROP FLOW eval_zero_offset_canonical_flow;
DROP TABLE eval_offset_phase_sink;
DROP TABLE eval_zero_offset_phase_sink;
DROP TABLE eval_zero_offset_canonical_sink;
DROP TABLE eval_offset_input;