Merge branch 'feat/narthex-unified-exec' into feat/narthex-native-binary-runtime

Bring in the clipped instant reservation and the start-timestamp assertions.

Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com>
This commit is contained in:
discord9
2026-10-21 17:20:57 +08:00
4 changed files with 347 additions and 16 deletions
+67 -10
View File
@@ -959,9 +959,9 @@ impl InstantRuntime {
/// The bytes gathering the series `closing` ends is about to allocate beside its chunks.
///
/// An upper bound derived from what the selection has in hand rather than a measurement: the
/// rows the series holds once `closing` has joined it, the fields it carries, the points its
/// bound grid decides, and, per field, the largest histogram a row of it can carry. Each term
/// is one thing the gather allocates:
/// rows the series holds once `closing` has joined it, the fields it carries, the points the
/// selection can decide for it, and, per field, the largest histogram a row of it can carry.
/// Each term is one thing the gather allocates:
///
/// - The concatenated axis ([`buffered_time`]): one `i64` per row, reserved by the row count.
/// - The descriptors that read it ([`buffered_fields`]): one [`Samples`] per (chunk, field) for
@@ -974,7 +974,7 @@ impl InstantRuntime {
/// validity byte per (row, field). A field of native histograms adds one `Option<u32>` index
/// per row and the payload of the histogram that index names, charged at the largest one the
/// field holds and per *point* rather than per row: one source row can be selected by every
/// point of the grid, so the point count is what that payload is multiplied by.
/// point the selection decides, so the point count is what that payload is multiplied by.
/// - The row the selection fills, one [`GridSample`] slot per field, and one [`RowCursor`] per
/// field to read the axis with.
/// - Doubling: every column the builder keeps is a `Vec` that grows by doubling, so each is
@@ -985,16 +985,18 @@ impl InstantRuntime {
/// gather drops before it returns, `Series`' own header and the runs [`GridSeriesBuilder`]
/// hands the output over with, which the output chunk is charged for by whoever reads it, and
/// the temporaries [`FloatHistogram::push_to`] builds for one row. None of those is
/// proportional to the points the grid decides, which is the amplification the pool has to be
/// asked for, and all of them are constant per gather or already counted row by row.
/// proportional to the points the selection decides, which is the amplification the pool has to
/// be asked for, and all of them are constant per gather or already counted row by row.
///
/// The estimate applies to every gather: nothing refuses one before it allocates, so the points
/// a grid decides are reserved for whatever their number is.
/// the series can be decided at are reserved for whatever their number is.
///
/// [`FloatHistogram::push_to`]: crate::histogram_eval::float_histogram::FloatHistogram::push_to
fn gather_bytes(&self, closing: &RawSeriesChunk) -> usize {
// The bound grid validated that its length fits a `usize`.
let points = usize::try_from(self.selection.output_grid.spec().len).unwrap_or(usize::MAX);
// The points the selection decides, not the points the grid plans: the gather clips its
// scan to the series it holds, so a figure over the whole grid would charge the pool for
// rows this series can never produce.
let points = self.selected_points(closing);
let chunks = self.chunks.len().saturating_add(1);
let rows = self
.chunks
@@ -1036,11 +1038,66 @@ impl InstantRuntime {
.saturating_add(rows_of_points.saturating_mul(2))
}
/// The number of grid points [`select_instants`] clips the buffered series to.
///
/// The gather clips its scan to the series it holds instead of reading the whole planned grid:
/// the candidate points run from the first sample's instant to the last sample's plus the
/// lookback, aligned to the grid and held inside the query range. A workspace is charged per
/// point, so the count has to be the clipped one -- charging the planned grid charges the pool
/// for rows a short series can never produce, and a pool sized for what the series costs then
/// refuses the gather. The clipping below is [`select_instants`]' own, repeated rather than
/// approximated: an estimate that disagrees with the kernel is a bug here rather than a
/// conservative bound. It is the kernel's own candidate count -- the one it sizes its arrays
/// with and refuses against a point limit -- so it bounds the rows it can report even though a
/// candidate at the lookback edge itself selects nothing. Both ends come from chunks the node
/// already holds, so the count reads two timestamps rather than the rows.
fn selected_points(&self, closing: &RawSeriesChunk) -> usize {
let spec = self.selection.output_grid.spec();
// The selection refuses these itself, before it can decide anything.
if spec.step_ms <= 0 || self.selection.lookback_ms < 0 {
return 0;
}
let query_start = i128::from(spec.start_ms);
let query_end = i128::from(grid_end_ms(spec));
if query_end < query_start {
return 0;
}
let series = || self.chunks.iter().chain(std::iter::once(closing));
let (Some(first), Some(last)) = (
series().find_map(|chunk| chunk.time.as_buffer().first().copied()),
series()
.rev()
.find_map(|chunk| chunk.time.as_buffer().last().copied()),
) else {
// A series of no sample decides no point.
return 0;
};
let offset = i128::from(self.selection.offset_ms);
let lookback = i128::from(self.selection.lookback_ms);
let first = i128::from(first) + offset;
let last = i128::from(last) + offset;
let useful_last = if lookback == 0 {
last
} else {
last + lookback - 1
};
let max_start = first.max(query_start);
let min_end = useful_last.min(query_end);
if max_start > min_end {
return 0;
}
let step = i128::from(spec.step_ms);
let aligned_start = query_start + (max_start - query_start) / step * step;
let aligned_end = query_end - (query_end - min_end) / step * step;
let points = (aligned_end - aligned_start) / step + 1;
usize::try_from(points).unwrap_or(usize::MAX)
}
/// The largest histogram a row of each field can carry, `None` for a field of floats.
///
/// A row of native histograms is copied into the builder once per grid point that selects it,
/// so what such a field costs is one histogram per point: the largest row is the one to charge,
/// because any row can be the one every point of the grid picks.
/// because any row can be the one every decided point picks.
fn largest_histograms(&self, closing: &RawSeriesChunk) -> Vec<Option<usize>> {
let mut largest = vec![None; self.schema.fields.len()];
for chunk in self.chunks.iter().chain(std::iter::once(closing)) {
+95 -6
View File
@@ -35,10 +35,12 @@ use datatypes::series::{Label, MetricName, SeriesOrdering};
use super::{
BinaryRuntime, Emitted, NativeChunk, NativeExecutionState, NativeExecutor, NodeBuffer,
NodeRuntime, absorb_rebuilds, evaluated_bytes, map_chunk, operand_chunk_bytes, raw_bytes,
NodeRuntime, absorb_rebuilds, evaluated_bytes, grid_end_ms, map_chunk, operand_chunk_bytes,
raw_bytes,
};
use crate::evaluated::EvaluatedChunk;
use crate::grid_series::merge_same_labelset;
use crate::instant_eval::select_instants;
use crate::map::MathOp;
use crate::native::metrics::{NodeMetric, NodeMetrics, NodePath};
use crate::native::plan::{
@@ -3843,11 +3845,15 @@ fn an_instant_selection_reserves_the_series_it_buffers() {
/// The workspace the gather allocates is reserved for before it exists.
///
/// A selection decides its whole grid at once, so its workspace is proportional to the points of
/// the grid rather than to the samples of the series: the axis it concatenates, the source row and
/// evaluation timestamp it reports per point, and the rows the builder keeps. One sample selected
/// by a million points is the review's case: the two selection arrays alone are 16 MB and the built
/// rows are more, while the series the node holds is one sample of a few hundred bytes.
/// A selection decides the points of the grid it can be selected at, so its workspace is
/// proportional to those points rather than to the samples of the series: the axis it concatenates,
/// the source row and evaluation timestamp it reports per point, and the rows the builder keeps.
/// The lookback here reaches from the sample to the last point, so this series is decididable at
/// every one of the million points -- the clipped count equals the grid's -- and the two selection
/// arrays alone are 16 MB while the built rows are more, against a series the node holds of one
/// sample of a few hundred bytes. [`a_selection_reserves_the_points_it_decides`] is the other side
/// of the same figure: a series whose samples cover only the start of a long grid reserves for the
/// few points it can decide and is admitted by a pool this one is refused by.
///
/// The pool here holds 8 KiB, which is enough for the buffered chunk and nothing near the
/// workspace, so the gather is refused instead of being performed. Nothing else refuses a million
@@ -3896,6 +3902,89 @@ fn an_instant_selection_reserves_the_workspace_it_gathers() {
);
}
/// A selection reserves the points it can decide, not the points the grid plans.
///
/// The review's shape: a seven-day grid at a one-minute step is 10,081 points, and one sample at
/// the start of the series read with a five-minute lookback is decided at five of them. The
/// grid-scaled terms of `InstantRuntime::gather_bytes` at the planned grid -- the selection's two
/// arrays and the doubled builder columns -- are about 504 KB, which the 64 KiB pool here is far
/// below; the handful of points really decided need a few hundred bytes, so this gather has to be
/// admitted. What it hands out is the rows `select_instants` reports for the same series, which is
/// the count the reservation has to agree with.
///
/// The second half is the other direction: the same grid, the same pool, and a series that spans
/// the grid with a lookback long enough to cover it, so all 10,081 points can be decided. The
/// figure then exceeds the pool and the gather is refused, which is what keeps this from being a
/// reservation of nothing.
#[test]
fn a_selection_reserves_the_points_it_decides() {
let out_grid = grid(0, 60_000, 10_081);
let schema = raw_schema();
let budget = 64 << 10;
// The two grid-scaled terms of `gather_bytes` at the planned grid: 10,081 points x 16 bytes for
// the selection's arrays, and 10,081 points x (8 + 8 + 1) x 2 for the doubled builder columns.
let full_grid = 10_081 * (8 + 8) + 10_081 * (8 + 8 + 1) * 2;
assert!(
full_grid > budget,
"the pool is not below what the full grid would be reserved: {full_grid} bytes"
);
// One sample at the start, read within five minutes: the kernel reports 0s..240s, and the
// candidate bound it sizes its arrays with is 0s..300s.
let tree = NativeTree::try_new(instant(input(), 300_000, 0, Arc::clone(&out_grid))).unwrap();
let chunk = raw_chunk(&schema, &[0], &[1.0], true);
let (_, timestamps) = select_instants(
&chunk.time,
&chunk.fields,
out_grid.spec().start_ms..=grid_end_ms(out_grid.spec()),
out_grid.spec().step_ms,
300_000,
0,
)
.unwrap();
assert_eq!(
timestamps.len(),
5,
"the clipping kernel decides another count"
);
let mut execution = executor(&tree, bounded_pool(budget), &ExecutionPlanMetricsSet::new());
execution.push_raw(chunk).unwrap();
let out = run(&mut execution);
assert_eq!(out.len(), 1);
let expected: Vec<(usize, Option<f64>)> = timestamps
.iter()
.map(|timestamp| {
(
usize::try_from((timestamp - out_grid.spec().start_ms) / out_grid.spec().step_ms)
.unwrap(),
Some(1.0),
)
})
.collect();
assert_eq!(
decided(&out),
expected,
"the gather handed out another set of points than the clipping decides"
);
// The same series spans the grid with a lookback that covers it, so every point can be decided
// and the workspace no longer fits the same pool.
let tree =
NativeTree::try_new(instant(input(), 604_800_001, 0, Arc::clone(&out_grid))).unwrap();
let pool = bounded_pool(budget);
let mut execution = executor(&tree, Arc::clone(&pool), &ExecutionPlanMetricsSet::new());
execution
.push_raw(raw_chunk(&schema, &[0, 604_800_000], &[1.0, 2.0], true))
.unwrap();
let error = execution.next_chunk().unwrap_err();
assert!(
matches!(error, DataFusionError::ResourcesExhausted(_)),
"a series covering the grid was gathered without asking the pool: {error}"
);
assert_eq!(pool.reserved(), 0);
assert_eq!(execution.state().reserved_bytes(), 0);
}
/// A grid longer than any point limit is charged for, and the pool is what refuses it.
///
/// `gather_bytes` used to return zero for a grid this long, so that a point limit inside the
+123
View File
@@ -831,6 +831,129 @@ fn histogram_chunk(schema: &SeriesSchema, buckets: i32, ts: i64) -> RawSeriesChu
.unwrap()
}
/// The single histogram sample of [`histogram_chunk`], read with `start_timestamp`.
///
/// A sample carries the start timestamp a scan read it with, and it is payload rather than a
/// property of the value: a reader detects a counter reset from a start timestamp falling inside
/// the range it reads, so a selected sample handed on without one hides that reset.
fn histogram_chunk_from(
schema: &SeriesSchema,
buckets: i32,
ts: i64,
start_timestamp: Option<i64>,
is_last: bool,
) -> RawSeriesChunk {
let offsets = [0];
let lengths = [buckets];
let counts = vec![1.0; usize::try_from(buckets).unwrap()];
let mut builder = HistogramBatchBuilder::new();
let index = builder
.push(HistogramView {
schema: 0,
zero_threshold: 0.0,
zero_count: 0.0,
count: f64::from(buckets),
sum: f64::from(buckets),
reset_hint: CounterResetHint::Unknown,
start_timestamp,
custom_values: &[],
positive: BucketSideView {
span_offsets: &offsets,
span_lengths: &lengths,
buckets: &counts,
},
negative: BucketSideView {
span_offsets: &[],
span_lengths: &[],
buckets: &[],
},
})
.unwrap();
let samples = Samples::try_from_histogram(
UInt32Array::from(vec![Some(index)]),
builder.finish().unwrap(),
)
.unwrap();
RawSeriesChunk::try_new(
schema,
Buffer::from(0u64.to_le_bytes().to_vec()),
Some(metric(0)),
RawTimestamps::try_new(ScalarBuffer::from(vec![ts])).unwrap(),
SeriesFields::try_from_vec(vec![samples]).unwrap(),
is_last,
)
.unwrap()
}
/// A function that hands back the sample it selected hands back that sample's payload.
///
/// `last_over_time` and `first_over_time` select a sample instead of computing one, so the
/// histogram that leaves them is the histogram that arrived, start timestamp included. The window
/// here holds two samples that differ in bucket count and in start timestamp, so the count and the
/// timestamp together say which one was selected rather than only that some timestamp survived:
/// the last sample for `last_over_time`, the first one for `first_over_time`. A selected sample
/// that lost its timestamp looks like one whose counter reset cannot be placed, which is what an
/// extrapolated rate downstream reads it for; a histogram computed from samples carries none, as
/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one`
/// pins for the operations that build one.
#[test]
fn a_selected_histogram_keeps_its_start_timestamp() {
let schema = raw_schema(1);
let (first_start, last_start): (i64, i64) = (1_500, 2_500);
// One bucket at 0ms and two at 5000ms, each read with its own start timestamp. Both samples
// are inside the window of the second grid point; the first point is decided on the first
// chunk alone, before the second sample has arrived.
let chunks = [
histogram_chunk_from(&schema, 1, 0, Some(first_start), false),
histogram_chunk_from(&schema, 2, 5_000, Some(last_start), true),
];
// The histogram of every row the function hands out, read off the output's own views: the
// bucket count tells the selected sample apart from any other, the start timestamp is the
// payload this test is about.
let selected = |function: RangeFunction| -> Vec<(usize, f64, Option<i64>)> {
let mut evaluator = RangeEvaluator::try_new(
&schema,
grid(0, 10_000, 2),
RangeWindow {
range_ms: 20_000,
offset_ms: 0,
anchor_ms: None,
},
function,
)
.unwrap();
let out = collect_chunks(&mut evaluator, &chunks);
assert!(!out.is_empty(), "{function:?} answered no chunk");
let mut picked = Vec::new();
for chunk in &out {
let mut cursor = chunk.series.fields.as_slice()[0].cursor();
for (position, row) in chunk.series.time.positions() {
match cursor.at(row).expect("the axis and the fields are aligned") {
SampleRef::Histogram(view) => {
picked.push((position, view.count, view.start_timestamp));
}
SampleRef::Float(_) => panic!("{function:?} answered a float for a histogram"),
SampleRef::Missing => {
panic!("{function:?} handed out a row of its own axis without a sample")
}
}
}
}
picked
};
assert_eq!(
selected(RangeFunction::LastOverTime),
[(0, 1.0, Some(first_start)), (1, 2.0, Some(last_start))],
"last_over_time did not hand back the sample it selected"
);
assert_eq!(
selected(RangeFunction::FirstOverTime),
[(0, 1.0, Some(first_start)), (1, 1.0, Some(first_start))],
"first_over_time did not hand back the sample it selected"
);
}
/// A window retaining a native histogram is charged for the payload it owns, not only the slot.
///
/// The histogram sample below stays ahead of the second grid point's window, so the evaluator keeps
+62
View File
@@ -269,6 +269,68 @@ fn limit_operators_keep_histogram_samples() {
assert_eq!(kinds(&kept[0], 0), [(1, "histogram")]);
}
/// A selection hands back the sample it selected, start timestamp included.
///
/// `limitk` and `limit_ratio` choose samples rather than compute them, so a histogram that arrives
/// with a start timestamp leaves with it. The count and the sum are compared too, so a computed
/// value that happened to carry a timestamp would not pass for the sample selected. The timestamp
/// is read downstream -- an extrapolated rate uses it to find where a counter reset fell -- so a
/// selected sample that lost it would look like one whose reset cannot be placed. A histogram
/// computed from samples carries none, as
/// `histogram_eval::tests::a_start_timestamp_belongs_to_a_read_histogram_and_not_to_a_computed_one`
/// pins for the operations that build one.
#[test]
fn limit_operators_keep_the_start_timestamp_of_a_selected_sample() {
let histogram =
OwnedHistogram::parse("0/0/0/3ff0000000000000/3ff0000000000000/0/1_1/3ff0000000000000///");
let start = 1_500;
// The sample a scan read, which is what a selection hands on.
let stamped = || {
let mut read = FloatHistogram::try_from_view(&histogram.view()).unwrap();
read.start_timestamp = Some(start);
GridSample::Histogram(Box::new(read))
};
// What a limit operator keeps out of one series: the count and sum of the histogram it kept,
// so the sample selected is named, and the start timestamp it kept with it.
let kept = |series: &Series| -> Vec<(usize, f64, f64, Option<i64>)> {
let samples = &series.fields.as_slice()[0];
series
.time
.positions()
.filter_map(|(point, row)| match samples.sample(row) {
SampleRef::Histogram(view) => {
Some((point, view.count, view.sum, view.start_timestamp))
}
_ => None,
})
.collect()
};
let source = histogram.view();
let expected = |point: usize| (point, source.count, source.sum, Some(start));
let schema = schema(3, 1);
let mut builder = GridSeriesBuilder::try_new(Arc::new(schema.clone())).unwrap();
builder.push_samples(0, &[Some(stamped())]).unwrap();
builder.push_samples(2, &[Some(stamped())]).unwrap();
let series = builder.finish(metric("__name__=a")).unwrap().unwrap();
let by_ratio = limit_ratio(1.0, &schema, std::slice::from_ref(&series)).unwrap();
assert_eq!(by_ratio.len(), 1);
assert_eq!(
kept(&by_ratio[0]),
[expected(0), expected(2)],
"limit_ratio did not hand back the samples it selected"
);
let by_count = limitk(1.0, &Grouping::By(Vec::new()), &schema, &[series]).unwrap();
assert_eq!(by_count.len(), 1);
assert_eq!(
kept(&by_count[0]),
[expected(0), expected(2)],
"limitk did not hand back the samples it selected"
);
}
fn grouping(kind: &str, labels: &str) -> Grouping {
match kind {
"without" => Grouping::Without(names(labels)),