1use std::ops::RangeInclusive;
16use std::sync::Arc;
17
18use common_query::prometheus::is_prometheus_stale_nan;
19use datafusion::error::{DataFusionError, Result};
20use datatypes::series::SeriesLabels;
21use datatypes::series::raw::RawTimestamps;
22use datatypes::series::samples::{SampleRef, Series, SeriesFields, SeriesSchema};
23
24use crate::grid_series::{GridSeriesBuilder, label_set, render_label_set};
25use crate::map::drop_metric_name;
26
27#[cfg(test)]
28mod tests;
29
30#[cfg(test)]
37pub(crate) static AXIS_ROWS_READ: std::sync::atomic::AtomicU64 =
38 std::sync::atomic::AtomicU64::new(0);
39
40fn row_read() {
42 #[cfg(test)]
43 AXIS_ROWS_READ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
44}
45
46pub fn select_instant_at(
53 time: &RawTimestamps,
54 fields: &SeriesFields,
55 at_ms: i64,
56 lookback_ms: i64,
57 offset_ms: i64,
58) -> Result<Option<u64>> {
59 let (indices, _) = select_instants(time, fields, at_ms..=at_ms, 1, lookback_ms, offset_ms)?;
63 Ok(indices.into_iter().next())
64}
65
66#[derive(Debug, PartialEq, Eq)]
71pub(crate) struct InstantCandidateSpan {
72 pub(crate) start: i128,
73 pub(crate) end: i128,
74 pub(crate) count: i128,
75}
76
77pub(crate) fn instant_candidate_span(
83 endpoints: Option<(i64, i64)>,
84 range: RangeInclusive<i64>,
85 step_ms: i64,
86 lookback_ms: i64,
87 offset_ms: i64,
88) -> InstantCandidateSpan {
89 let empty = InstantCandidateSpan {
90 start: 1,
91 end: 0,
92 count: 0,
93 };
94 let Some((first, last)) = endpoints else {
95 return empty;
96 };
97 let first = first as i128 + offset_ms as i128;
98 let last = last as i128 + offset_ms as i128;
99 let useful_last = if lookback_ms == 0 {
100 last
101 } else {
102 last + lookback_ms as i128 - 1
103 };
104 let query_start = *range.start() as i128;
105 let query_end = *range.end() as i128;
106 let step = step_ms as i128;
107 let max_start = first.max(query_start);
108 let min_end = useful_last.min(query_end);
109 if max_start > min_end {
110 return empty;
111 }
112 let start = query_start + (max_start - query_start) / step * step;
113 let end = query_end - (query_end - min_end) / step * step;
114 let count = (end - start) / step + 1;
115 InstantCandidateSpan { start, end, count }
116}
117
118pub fn select_instants(
133 time: &RawTimestamps,
134 fields: &SeriesFields,
135 range: RangeInclusive<i64>,
136 step_ms: i64,
137 lookback_ms: i64,
138 offset_ms: i64,
139) -> Result<(Vec<u64>, Vec<i64>)> {
140 let start = *range.start();
141 let end = *range.end();
142 if step_ms <= 0 {
143 return Err(DataFusionError::Execution(
144 "InstantManipulate interval must be positive".into(),
145 ));
146 }
147 if start > end {
148 return Err(DataFusionError::Execution(
149 "InstantManipulate start must not exceed end".into(),
150 ));
151 }
152 if lookback_ms < 0 {
153 return Err(DataFusionError::Execution(
154 "InstantManipulate lookback must be non-negative".into(),
155 ));
156 }
157 let timestamps = time.as_buffer();
158 if fields
159 .as_slice()
160 .iter()
161 .any(|field| field.len() != timestamps.len())
162 {
163 return Err(DataFusionError::Execution(
164 "series fields and time axis have unequal lengths".into(),
165 ));
166 }
167 if timestamps.is_empty() {
168 return Ok((Vec::new(), Vec::new()));
169 }
170
171 let span = instant_candidate_span(
172 Some((timestamps[0], timestamps[timestamps.len() - 1])),
173 range,
174 step_ms,
175 lookback_ms,
176 offset_ms,
177 );
178 let mut indices = Vec::with_capacity(span.count as usize);
179 let mut evaluation_timestamps = Vec::with_capacity(span.count as usize);
180 let mut sample_iters: Vec<_> = fields.iter().map(|field| field.iter()).collect();
181 let mut current_stale = false;
182 let mut cursor = 0usize;
183 for expected in (span.start..=span.end).step_by(step_ms as usize) {
184 let source_expected = expected - offset_ms as i128;
185 while cursor < timestamps.len() && timestamps[cursor] as i128 <= source_expected {
186 current_stale = false;
187 for samples in &mut sample_iters {
188 let sample = samples.next().ok_or_else(|| {
189 DataFusionError::Execution(
190 "series sample iterator ended before the time axis".into(),
191 )
192 })?;
193 let stale = match sample {
194 SampleRef::Float(value) => is_prometheus_stale_nan(value),
195 SampleRef::Histogram(histogram) => is_prometheus_stale_nan(histogram.sum),
196 SampleRef::Missing => false,
197 };
198 current_stale |= stale;
199 }
200 row_read();
201 cursor += 1;
202 }
203 let Some(candidate) = cursor.checked_sub(1) else {
204 continue;
205 };
206 let candidate_ts = timestamps[candidate] as i128 + offset_ms as i128;
207 let lower = expected - lookback_ms as i128;
208 if (candidate_ts == expected || candidate_ts > lower)
209 && candidate_ts <= expected
210 && !current_stale
211 {
212 indices.push(candidate as u64);
213 evaluation_timestamps.push(expected as i64);
214 }
215 }
216 Ok((indices, evaluation_timestamps))
217}
218
219pub fn timestamp_of_selection(
235 schema: &Arc<SeriesSchema>,
236 metric: &SeriesLabels,
237 time: &RawTimestamps,
238 fields: &SeriesFields,
239 indices: &[u64],
240 evaluation_timestamps: &[i64],
241) -> Result<Option<Series>> {
242 project_selection(
243 schema,
244 drop_metric_name(metric)?,
245 time,
246 fields,
247 indices,
248 evaluation_timestamps,
249 |_, time| Ok(time as f64 / 1000.0),
250 )
251}
252
253pub fn info_sample_times(
259 schema: &Arc<SeriesSchema>,
260 metric: &SeriesLabels,
261 time: &RawTimestamps,
262 fields: &SeriesFields,
263 indices: &[u64],
264 evaluation_timestamps: &[i64],
265) -> Result<Option<Series>> {
266 project_selection(
267 schema,
268 metric.clone(),
269 time,
270 fields,
271 indices,
272 evaluation_timestamps,
273 |sample, time| match sample {
274 SampleRef::Histogram(_) => Err(DataFusionError::Execution(format!(
275 "this should be an info metric, with float samples: {}",
276 render_label_set(&label_set(metric))
277 ))),
278 _ => Ok(time as f64),
279 },
280 )
281}
282
283pub fn timestamp_of_evaluated(
287 schema: &Arc<SeriesSchema>,
288 series: &Series,
289) -> Result<Option<Series>> {
290 let grid = schema.eval_grid.as_ref().ok_or_else(|| {
291 DataFusionError::Execution("timestamp requires an evaluation grid".into())
292 })?;
293 if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
294 || series.fields.len() != schema.fields.len()
295 {
296 return Err(DataFusionError::Execution(
297 "timestamp input does not match its schema".into(),
298 ));
299 }
300 let timestamps = grid.timestamps().map_err(crate::grid_series::external)?;
301 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
302 let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
303 let mut row = Vec::with_capacity(cursors.len());
304 for (point, index) in series.time.positions() {
305 let seconds = timestamps[point] as f64 / 1000.0;
306 row.clear();
307 for cursor in &mut cursors {
308 let sample = cursor
309 .at(index)
310 .expect("the axis and the fields are aligned");
311 row.push((!matches!(sample, SampleRef::Missing)).then_some(seconds));
312 }
313 builder.push(point, &row)?;
314 }
315 builder.finish(drop_metric_name(&series.metric)?)
316}
317
318fn project_selection(
327 schema: &Arc<SeriesSchema>,
328 metric: SeriesLabels,
329 time: &RawTimestamps,
330 fields: &SeriesFields,
331 indices: &[u64],
332 evaluation_timestamps: &[i64],
333 value: impl Fn(SampleRef<'_>, i64) -> Result<f64>,
334) -> Result<Option<Series>> {
335 let grid = schema.eval_grid.as_ref().ok_or_else(|| {
336 DataFusionError::Execution("an instant selection requires an evaluation grid".into())
337 })?;
338 if indices.len() != evaluation_timestamps.len()
339 || fields.len() != schema.fields.len()
340 || fields.iter().any(|field| field.len() != time.len())
341 {
342 return Err(DataFusionError::Execution(
343 "instant selection does not match its series or schema".into(),
344 ));
345 }
346 let spec = grid.spec();
347 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
348 let mut cursors: Vec<_> = fields.iter().map(|field| field.cursor()).collect();
349 let mut row: Vec<Option<f64>> = Vec::with_capacity(fields.len());
351 let mut last: Option<(i128, usize)> = None;
352 for (&index, ×tamp) in indices.iter().zip(evaluation_timestamps) {
353 let offset = timestamp as i128 - spec.start_ms as i128;
354 let position = offset / spec.step_ms as i128;
355 let index = usize::try_from(index)
356 .ok()
357 .filter(|index| *index < time.len());
358 let (Some(index), true) = (
359 index,
360 offset % spec.step_ms as i128 == 0
361 && (0..spec.len as i128).contains(&position)
362 && last.is_none_or(|(last_position, _)| last_position < position),
363 ) else {
364 return Err(DataFusionError::Execution(
365 "instant selection points off the grid or out of the series".into(),
366 ));
367 };
368 match last {
369 Some((_, last_index)) if last_index == index => {}
370 Some((_, last_index)) if last_index > index => {
371 return Err(DataFusionError::Execution(
372 "instant selection rows must not go back".into(),
373 ));
374 }
375 _ => {
376 let time = time.timestamp(index).expect("checked against the axis");
377 row.clear();
378 for cursor in &mut cursors {
379 let sample = cursor
380 .at(index)
381 .expect("rows increase and lie in fields as long as the axis");
382 row.push(match sample {
383 SampleRef::Missing => None,
384 sample => Some(value(sample, time)?),
385 });
386 }
387 }
388 }
389 last = Some((position, index));
390 builder.push(position as usize, &row)?;
391 }
392 builder.finish(metric)
393}