mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-01 07:04:09 +00:00
fix(promql): widen the regression intercept so a far horizon stops overflowing (#10724)
* fix(promql): widen the regression intercept so a far horizon stops overflowing predict_linear added the fold offset to the evaluation time in i64; both are legal and their sum is not, so a statement anchored far in the past was refused even though it answers an empty matrix elsewhere. The intercept is i128 now and the kernel adds there; the admission guard keeps only the fold offset, which is a per-sample shift that has nowhere to live outside i64. Signed-off-by: discord9 <discord9@163.com> * docs(promql): cut the window-overflow comments to the non-obvious why The added commentary restated code and existing invariants: native_tree_supported grew a second copy of its own refusal list plus a section on what the runtime still decides, and each test carried a paragraph narrating reasoning its name and assertion messages already state. Keep one sentence per non-obvious fact and narrow the stale predict_linear half of the admission list to what the predicate now refuses. Added comment lines: 122 -> 15. Signed-off-by: discord9 <discord9@163.com> --------- Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -618,6 +618,29 @@ fn timestamp_instant_rejects_negative_lookback() {
|
||||
assert_eq!(pool.reserved(), 0);
|
||||
}
|
||||
|
||||
/// Prometheus answers an `@`-anchored `predict_linear` horizon past `i64` with an empty matrix: the
|
||||
/// anchored window reads the epoch, and the source holds no sample there.
|
||||
#[test]
|
||||
fn an_anchored_predict_linear_past_i64_answers_an_empty_matrix() {
|
||||
let far = grid(5_000_000_000_000_000_000, 5_000, 3);
|
||||
let mut root = window_with(
|
||||
input(),
|
||||
RangeFunction::PredictLinear(60.0),
|
||||
60_000,
|
||||
None,
|
||||
Arc::clone(&far),
|
||||
);
|
||||
let NativeExpr::Window { op, .. } = &mut root.expr else {
|
||||
unreachable!();
|
||||
};
|
||||
op.window.anchor_ms = Some(0);
|
||||
let tree = NativeTree::try_new(root).unwrap();
|
||||
let pool = pool();
|
||||
let mut execution = executor(&tree, Arc::clone(&pool));
|
||||
assert!(run(&mut execution).is_empty());
|
||||
assert_eq!(pool.reserved(), 0);
|
||||
}
|
||||
|
||||
fn merge(inner: NativeNode) -> NativeNode {
|
||||
let output = inner.output.clone();
|
||||
NativeNode {
|
||||
|
||||
@@ -40,7 +40,7 @@ use crate::info::InfoSelector;
|
||||
use crate::map::MathOp;
|
||||
use crate::map_label::LabelRewrite;
|
||||
use crate::map_time::DateFunction;
|
||||
use crate::range_eval::{RangeFunction, RangeWindow, fold_offset, predict_linear_instants};
|
||||
use crate::range_eval::{RangeFunction, RangeWindow, fold_offset};
|
||||
use crate::select::SortOrder;
|
||||
use crate::vector_match::{
|
||||
BinaryMatching, BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp,
|
||||
@@ -1598,7 +1598,7 @@ impl<'de> serde::Deserialize<'de> for NativeTree {
|
||||
/// a value field, and a `count_values` with an empty label;
|
||||
/// - an `anchored` or `smoothed` window over evaluated input, over a function its kernel does not
|
||||
/// correct, or with a negative lookback;
|
||||
/// - a window whose `@` fold offset or `predict_linear` instants overflow `i64`.
|
||||
/// - a window whose `@` fold offset overflows `i64`.
|
||||
///
|
||||
/// A memory reservation refusal is left to the runtime.
|
||||
pub fn native_tree_supported(tree: &NativeTree) -> bool {
|
||||
@@ -1627,7 +1627,7 @@ fn native_node_supported_within_stack(node: &NativeNode) -> bool {
|
||||
NativeExpr::Window { input, op } => {
|
||||
native_node_supported(input)
|
||||
&& window_modifier_supported(input, op)
|
||||
&& window_instants_fit(op)
|
||||
&& window_fold_offset_fits(op)
|
||||
}
|
||||
NativeExpr::ParameterizedMap {
|
||||
input, parameters, ..
|
||||
@@ -1788,17 +1788,11 @@ fn window_modifier_supported(input: &NativeNode, op: &BoundWindow) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `@` fold offset and `predict_linear` instants fit in `i64`, asked through the same
|
||||
/// functions the runtime calls.
|
||||
fn window_instants_fit(op: &BoundWindow) -> bool {
|
||||
let grid = op.output_grid.spec();
|
||||
let Ok(fold_offset) = fold_offset(grid, op.window) else {
|
||||
return false;
|
||||
};
|
||||
match op.function {
|
||||
RangeFunction::PredictLinear(_) => predict_linear_instants(grid, fold_offset).is_ok(),
|
||||
_ => true,
|
||||
}
|
||||
/// Whether the window's fold offset fits in `i64`: the shift every sample it reads takes, asked
|
||||
/// through [`fold_offset`] so a query refused here keeps the plan it had instead of failing while
|
||||
/// the runtime is built.
|
||||
fn window_fold_offset_fits(op: &BoundWindow) -> bool {
|
||||
fold_offset(op.output_grid.spec(), op.window).is_ok()
|
||||
}
|
||||
|
||||
/// Stack reserve before a tree walk grows its stack. Trees have no depth limit, and in a debug build
|
||||
|
||||
@@ -3437,9 +3437,10 @@ fn native_tree_supported_declines_a_refused_shape_nested_under_another() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Not shapes: the `@` fold offset or the `predict_linear` instants overflow `i64`.
|
||||
/// A window whose fold offset does not fit in `i64` is refused by admission as well as the runtime;
|
||||
/// a horizon merely wider than `i64` is admitted, since only differences from it are read.
|
||||
#[test]
|
||||
fn native_tree_supported_declines_the_instants_that_overflow() {
|
||||
fn native_tree_supported_declines_the_fold_offsets_that_overflow() {
|
||||
// `predict_linear(some_metric[1m] @ 0, 60)` over a grid starting at 5e18 ms.
|
||||
let far = grid(5_000_000_000_000_000_000, 5_000, 3);
|
||||
let window = |function: RangeFunction, anchor_ms: Option<i64>, out: Arc<EvalGrid>| NativeNode {
|
||||
@@ -3459,7 +3460,6 @@ fn native_tree_supported_declines_the_instants_that_overflow() {
|
||||
},
|
||||
output: evaluated(Arc::new([]), out),
|
||||
};
|
||||
// Fold offset 5e18 ms plus a grid point of 5e18 ms overflows `i64`.
|
||||
let horizon = window(
|
||||
RangeFunction::PredictLinear(60.0),
|
||||
Some(0),
|
||||
@@ -3467,16 +3467,26 @@ fn native_tree_supported_declines_the_instants_that_overflow() {
|
||||
);
|
||||
assert_admission(
|
||||
horizon,
|
||||
false,
|
||||
"a predict_linear horizon over the grid that overflows",
|
||||
true,
|
||||
"a predict_linear horizon past i64 over a fitting fold offset",
|
||||
);
|
||||
// `@ -5e18` over that grid is a 1e19 ms fold offset on its own.
|
||||
// `@ -5e18` over that grid is a 1e19 ms fold offset on its own, so even `rate` refuses it.
|
||||
let anchored = window(
|
||||
RangeFunction::Rate,
|
||||
Some(-5_000_000_000_000_000_000),
|
||||
Arc::clone(&far),
|
||||
);
|
||||
assert_admission(anchored, false, "an `@` anchor whose fold offset overflows");
|
||||
let anchored_horizon = window(
|
||||
RangeFunction::PredictLinear(60.0),
|
||||
Some(-5_000_000_000_000_000_000),
|
||||
Arc::clone(&far),
|
||||
);
|
||||
assert_admission(
|
||||
anchored_horizon,
|
||||
false,
|
||||
"a predict_linear horizon whose fold offset overflows",
|
||||
);
|
||||
let fitting = window(
|
||||
RangeFunction::PredictLinear(60.0),
|
||||
Some(0),
|
||||
|
||||
@@ -602,9 +602,6 @@ impl RangeEvaluator {
|
||||
}
|
||||
let fold_offset = fold_offset(grid.spec(), window)?;
|
||||
let step_invariant = !matches!(function, RangeFunction::PredictLinear(_));
|
||||
if !step_invariant {
|
||||
predict_linear_instants(grid.spec(), fold_offset)?;
|
||||
}
|
||||
// A modified window corrects counters over the samples it holds rather than through the
|
||||
// reset index, and has no batch form.
|
||||
let (kernel, index_resets) = match window.modifier {
|
||||
@@ -1568,21 +1565,6 @@ pub(crate) fn fold_offset(grid: GridSpec, window: RangeWindow) -> Result<i64> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks that every evaluation instant of `grid`, shifted by `fold_offset`, fits in i64;
|
||||
/// `predict_linear` reads it. Checking both ends suffices. Shared with the native admission
|
||||
/// predicate, so a query refused here keeps its legacy plan instead of failing at runtime.
|
||||
pub(crate) fn predict_linear_instants(grid: GridSpec, fold_offset: i64) -> Result<()> {
|
||||
let last = i128::from(grid.start_ms) + i128::from(grid.step_ms) * (i128::from(grid.len) - 1);
|
||||
for eval_ts in [i128::from(grid.start_ms), last] {
|
||||
if i64::try_from(eval_ts + i128::from(fold_offset)).is_err() {
|
||||
return Err(DataFusionError::Plan(format!(
|
||||
"predict_linear evaluation time {eval_ts} overflows with offset {fold_offset} ms"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The inner grid of a subquery read by `window` from the outer grid `outer`: the multiples of
|
||||
/// `step_ms` after `start - F - range` up to the last window end, where `F` is the fold offset
|
||||
/// of `window`; with `@`, the only window end is `start - F`. `None` when no multiple falls in
|
||||
|
||||
@@ -209,16 +209,16 @@ impl RangeFunction {
|
||||
}
|
||||
Self::Deriv => Box::new(|window| {
|
||||
(window.values.len() >= 2)
|
||||
.then(|| linear_regression(&window, window.timestamps[0]).0)
|
||||
.then(|| linear_regression(&window, i128::from(window.timestamps[0])).0)
|
||||
}),
|
||||
// Prometheus regresses the unshifted samples around the evaluation time, which on the
|
||||
// shifted timeline is `eval_ts + offset`; `RangeEvaluator::try_new` checks it fits.
|
||||
// shifted timeline is `eval_ts + offset`, taken widened: only differences are read.
|
||||
Self::PredictLinear(duration) => Box::new(move |window| {
|
||||
if window.values.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let (slope, intercept) =
|
||||
linear_regression(&window, window.eval_ts.checked_add(offset_ms)?);
|
||||
let intercept_time = i128::from(window.eval_ts) + i128::from(offset_ms);
|
||||
let (slope, intercept) = linear_regression(&window, intercept_time);
|
||||
Some(slope * duration + intercept)
|
||||
}),
|
||||
Self::DoubleExponentialSmoothing { smoothing, trend } => Box::new(move |window| {
|
||||
@@ -603,7 +603,7 @@ fn last_two<const IS_RATE: bool>(window: FloatWindow<'_>) -> Option<f64> {
|
||||
|
||||
/// Prometheus `linearRegression`: `(slope, intercept)` with `x` in seconds from
|
||||
/// `intercept_time`. Needs at least two samples.
|
||||
fn linear_regression(window: &FloatWindow<'_>, intercept_time: i64) -> (f64, f64) {
|
||||
fn linear_regression(window: &FloatWindow<'_>, intercept_time: i128) -> (f64, f64) {
|
||||
let init_y = window.values[0];
|
||||
let mut const_y = true;
|
||||
let mut n = 0.0;
|
||||
@@ -616,7 +616,7 @@ fn linear_regression(window: &FloatWindow<'_>, intercept_time: i64) -> (f64, f64
|
||||
const_y = false;
|
||||
}
|
||||
n += 1.0;
|
||||
let x = (i128::from(t) - i128::from(intercept_time)) as f64 / 1e3;
|
||||
let x = (i128::from(t) - intercept_time) as f64 / 1e3;
|
||||
(sum_x, c_x) = kahan_inc(x, sum_x, c_x);
|
||||
(sum_y, c_y) = kahan_inc(y, sum_y, c_y);
|
||||
(sum_xy, c_xy) = kahan_inc(x * y, sum_xy, c_xy);
|
||||
|
||||
@@ -2323,15 +2323,16 @@ fn rejects_invalid_parameters() {
|
||||
anchor_ms: None,
|
||||
modifier: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
assert!(
|
||||
RangeEvaluator::try_new(
|
||||
&raw_schema(1),
|
||||
grid(0, 10, 4),
|
||||
far_offset,
|
||||
RangeFunction::PredictLinear(0.0)
|
||||
),
|
||||
Err(DataFusionError::Plan(_))
|
||||
));
|
||||
)
|
||||
.is_ok(),
|
||||
"a predict_linear horizon past i64 is read widened, not refused"
|
||||
);
|
||||
|
||||
let unrepresentable_anchor = RangeWindow {
|
||||
range_ms: 10,
|
||||
|
||||
@@ -4386,30 +4386,16 @@ async fn native_fused_partitioned_table_label_rewrite_plans_a_canonical_boundary
|
||||
);
|
||||
}
|
||||
|
||||
/// A `predict_linear` horizon whose instants do not fit keeps the existing plan.
|
||||
///
|
||||
/// A window folds its `@` anchor into an offset from the grid's first point, and `predict_linear`
|
||||
/// is the one range function that adds that offset to a point of the grid as well. `@` is the epoch
|
||||
/// and the statement starts 5e18 ms later, so the fold offset is that same 5e18 ms and the sum the
|
||||
/// horizon reads is 1e19 ms - not an instant an `i64` holds. The runtime refuses the window while
|
||||
/// it builds it.
|
||||
/// A `predict_linear` horizon whose instant leaves `i64` keeps the native route: the regression
|
||||
/// reads only how far each sample is from it, so the kernel takes the shift widened.
|
||||
///
|
||||
/// The window is wrapped in `topk`, a whole-vector consumer: it makes the route cut the window as a
|
||||
/// segment and decide the statement's plan from that segment while planning, which is the moment
|
||||
/// the refusal cannot be left to the executor - a native plan that fails while its physical plan is
|
||||
/// built has none to fall back to. Deciding this during planning is what the route did while it
|
||||
/// decided admission by building the runtime and dropping it, and it is what the admission
|
||||
/// predicate decides now: every site that commits to a tree asks `native_tree_supported` and builds
|
||||
/// no runtime, so `window_instants_fit` is the only thing that keeps this query off the native
|
||||
/// route, and dropping it from the predicate makes this test fail. (The `@` half of the same
|
||||
/// arithmetic is pinned one level down, in `native::plan::tests`, because a statement whose anchor
|
||||
/// and start are that far apart is refused by the planner's own at-modifier rewrite first.)
|
||||
/// segment and decide the statement's plan while planning.
|
||||
///
|
||||
/// A platform whose `SystemTime` cannot represent the `5e18 ms` start skips the high-level
|
||||
/// shape; the platform-independent `native_tree_supported_declines_the_instants_that_overflow`
|
||||
/// still covers the admission predicate there.
|
||||
/// A platform whose `SystemTime` cannot represent the `5e18 ms` start skips the shape;
|
||||
/// `native_tree_supported_declines_the_fold_offsets_that_overflow` covers admission there.
|
||||
#[tokio::test]
|
||||
async fn native_fused_windows_whose_instants_overflow_fall_back() {
|
||||
async fn native_fused_predict_linear_horizon_past_i64_keeps_the_native_route() {
|
||||
// The far end of the `i64` millisecond range, one step apart. Windows' `SystemTime` and
|
||||
// 32-bit `time_t` targets cannot represent it, so they cannot build this statement.
|
||||
let Some(far_start) = UNIX_EPOCH.checked_add(Duration::from_millis(5_000_000_000_000_000_000))
|
||||
@@ -4450,16 +4436,16 @@ async fn native_fused_windows_whose_instants_overflow_fall_back() {
|
||||
// `@ 0` folds to the grid's own start, which the horizon then adds to a point of the grid.
|
||||
let query = "topk(1, predict_linear(some_metric[1m] @ 0, 60))";
|
||||
let native = plan_for(query, true).await;
|
||||
let fallback = plan_for(query, false).await;
|
||||
assert!(
|
||||
find_fused_series(&native).is_none(),
|
||||
"{query} reads an instant the runtime cannot compute and must keep the existing plan: {}",
|
||||
find_fused_series(&native).is_some(),
|
||||
"{query} reads an instant the runtime computes and must take the native route: {}",
|
||||
native.display_indent()
|
||||
);
|
||||
assert_eq!(
|
||||
native.display_indent().to_string(),
|
||||
fallback.display_indent().to_string(),
|
||||
"{query}: the native setting must plan exactly what the existing planner plans"
|
||||
let fallback = plan_for(query, false).await;
|
||||
assert!(
|
||||
find_fused_series(&fallback).is_none(),
|
||||
"{query}: the existing planner reads no native tree: {}",
|
||||
fallback.display_indent()
|
||||
);
|
||||
// The same shape over a statement near the epoch fits, so the route is not narrowed.
|
||||
let near = plan_for("topk(1, rate(some_metric[5m]))", true).await;
|
||||
|
||||
Reference in New Issue
Block a user