1#[cfg(test)]
25mod tests;
26
27use std::collections::btree_map::Entry;
28use std::collections::{BTreeMap, BTreeSet, HashMap};
29use std::sync::Arc;
30
31use datafusion::error::{DataFusionError, Result};
32use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
33use datatypes::series::{Label, SeriesLabels};
34use regex::Regex;
35
36use crate::grid_series::{
37 GridSample, GridSeriesBuilder, LabelSet, external, label_set, owned, render_label_set,
38};
39use crate::select::MatchOp;
40use crate::vector_match::{Budget, HISTOGRAM_ROW_BYTES, owned_histogram_bytes};
41
42const IDENTIFYING_LABELS: [&str; 2] = ["instance", "job"];
44
45#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
47pub struct InfoSelector {
48 pub name_matchers: Vec<(MatchOp, Arc<str>)>,
50 pub data_labels: Vec<Arc<str>>,
53 pub keep_unmatched: bool,
56}
57
58pub fn info(
70 schema: &Arc<SeriesSchema>,
71 base: &[Series],
72 info: &[Series],
73 selector: &InfoSelector,
74) -> Result<Vec<Series>> {
75 info_inner(schema, base, info, selector, None)
76}
77
78pub(crate) fn info_with_reservation(
84 schema: &Arc<SeriesSchema>,
85 base: &[Series],
86 info: &[Series],
87 selector: &InfoSelector,
88 reserve: &mut dyn FnMut(usize) -> Result<()>,
89) -> Result<Vec<Series>> {
90 let mut budget = Budget::new(reserve);
91 info_inner(schema, base, info, selector, Some(&mut budget))
92}
93
94fn info_inner(
96 schema: &Arc<SeriesSchema>,
97 base: &[Series],
98 info: &[Series],
99 selector: &InfoSelector,
100 mut budget: Option<&mut Budget<'_>>,
101) -> Result<Vec<Series>> {
102 let grid = schema
103 .eval_grid
104 .as_ref()
105 .ok_or_else(|| DataFusionError::Execution("info requires an evaluated grid".into()))?;
106 let points = grid.spec().len as usize;
107 for series in base {
108 if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
109 || series.fields.len() != schema.fields.len()
110 {
111 return Err(DataFusionError::Execution(
112 "info base series does not match its schema".into(),
113 ));
114 }
115 }
116 for series in info {
117 if series.time.grid().map(|grid| grid.spec()) != Some(grid.spec())
118 || series.fields.len() != 1
119 {
120 return Err(DataFusionError::Execution(
121 "info series must be single-field series on the base grid".into(),
122 ));
123 }
124 }
125 let name_matchers = effective_name_matchers(&selector.name_matchers)?;
126 let is_info_metric = |name: &str| name_matchers.iter().all(|matcher| matcher.matches(name));
127 let width = schema.fields.len();
128
129 if let Some(budget) = budget.as_deref_mut() {
132 budget.hold(points.saturating_add(base.len().saturating_mul(PATTERN_BYTES)))?;
133 }
134 let mut base_present = vec![false; points];
135 let mut sampled = vec![false; base.len()];
136 for (series, sampled) in base.iter().zip(&mut sampled) {
137 for field in series.fields.iter() {
138 for ((point, _), sample) in series.time.positions().zip(field.iter()) {
139 if !matches!(sample, SampleRef::Missing) {
140 base_present[point] = true;
141 *sampled = true;
142 }
143 }
144 }
145 }
146
147 let mut error = FirstError::default();
148
149 let mut patterns: HashMap<Vec<bool>, Vec<BTreeSet<Arc<str>>>> = HashMap::new();
156 for (series, _) in base.iter().zip(&sampled).filter(|(_, sampled)| **sampled) {
157 if is_info_metric(series.metric.name().unwrap_or("")) {
158 continue;
159 }
160 let values = identifying_values(&series.metric);
161 let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
162 if !presence.contains(&true) {
163 continue;
164 }
165 let sets = patterns
166 .entry(presence)
167 .or_insert_with(|| vec![BTreeSet::new(); IDENTIFYING_LABELS.len()]);
168 for (set, value) in sets.iter_mut().zip(values) {
169 set.extend(value);
170 }
171 }
172
173 let mut by_signature: HashMap<Signature, BTreeMap<usize, (f64, usize)>> = HashMap::new();
175 let mut info_names: BTreeSet<Arc<str>> = BTreeSet::new();
176 for (index, series) in info.iter().enumerate() {
177 let values = identifying_values(&series.metric);
178 let presence: Vec<bool> = values.iter().map(Option::is_some).collect();
179 let fetched = patterns.get(&presence).is_some_and(|sets| {
180 sets.iter()
181 .zip(&values)
182 .all(|(set, value)| value.as_ref().is_none_or(|value| set.contains(value)))
183 });
184 if !fetched {
185 continue;
186 }
187 if let Some(budget) = budget.as_deref_mut() {
190 budget.hold(
191 series
192 .time
193 .len()
194 .saturating_mul(KEPT_POINT_BYTES)
195 .saturating_add(SIGNATURE_BYTES),
196 )?;
197 }
198 let name: Arc<str> = Arc::from(series.metric.name().unwrap_or(""));
199 info_names.insert(name.clone());
200 let kept = by_signature.entry((name, values)).or_default();
201 let mut cursor = series.fields.as_slice()[0].cursor();
202 for (point, row) in series.time.positions() {
203 let timestamp = match cursor.at(row).expect("the axis and the fields are aligned") {
204 SampleRef::Missing => continue,
205 SampleRef::Float(timestamp) => timestamp,
206 SampleRef::Histogram(_) => {
207 return Err(DataFusionError::Internal(
208 "info series must hold the original sample timestamps as floats".into(),
209 ));
210 }
211 };
212 match kept.entry(point) {
213 Entry::Vacant(entry) => {
214 entry.insert((timestamp, index));
215 }
216 Entry::Occupied(mut entry) => {
217 let (existing, existing_index) = *entry.get();
218 if timestamp > existing {
219 entry.insert((timestamp, index));
220 } else if timestamp == existing && base_present[point] {
221 error.record(point, 0, || {
222 format!(
223 "found duplicate series for info metric: existing {} @ {}, new \
224 {} @ {}",
225 render_label_set(&label_set(&info[existing_index].metric)),
226 existing as i64,
227 render_label_set(&label_set(&series.metric)),
228 timestamp as i64
229 )
230 });
231 }
232 }
233 }
234 }
235 }
236
237 let mut result_index: HashMap<LabelSet, usize> = HashMap::new();
238 let mut results: Vec<(SeriesLabels, Vec<Row>)> = Vec::new();
239 let mut added: Vec<(Arc<str>, Arc<str>)> = Vec::new();
240 let mut chosen: Vec<usize> = Vec::new();
241 for series in base {
242 let ignored = is_info_metric(series.metric.name().unwrap_or(""));
243 let candidates: Vec<&BTreeMap<usize, (f64, usize)>> = if ignored {
246 Vec::new()
247 } else {
248 let values = identifying_values(&series.metric);
249 info_names
250 .iter()
251 .filter_map(|name| by_signature.get(&(name.clone(), values.clone())))
252 .collect()
253 };
254 let mut previous: Option<Choice> = None;
256 if let Some(budget) = budget.as_deref_mut() {
259 budget.hold(series.time.len().saturating_mul(row_bytes(width)))?;
260 }
261 let mut cursors: Vec<_> = series.fields.iter().map(|field| field.cursor()).collect();
262 for (point, row) in series.time.positions() {
263 let mut values = Vec::with_capacity(width);
264 for cursor in &mut cursors {
265 let sample = cursor.at(row).expect("the axis and the fields are aligned");
266 if let (Some(budget), SampleRef::Histogram(view)) = (budget.as_deref_mut(), &sample)
267 {
268 budget.hold(owned_histogram_bytes(view))?;
269 }
270 values.push(owned(sample)?);
271 }
272 if values.iter().all(Option::is_none) {
273 continue;
274 }
275 chosen.clear();
276 chosen.extend(
277 candidates
278 .iter()
279 .filter_map(|kept| kept.get(&point).map(|&(_, index)| index)),
280 );
281 let reuse = previous
282 .as_ref()
283 .is_some_and(|previous| previous.info == chosen);
284 if !reuse {
285 added.clear();
286 let mut conflict = None;
287 for &index in &chosen {
288 if let Err(label) =
289 add_data_labels(&info[index].metric, &series.metric, selector, &mut added)
290 {
291 conflict = Some(label);
292 break;
293 }
294 }
295 let result = if chosen.is_empty() && !selector.keep_unmatched && !ignored {
296 None
297 } else {
298 let mut metric = series.metric.clone();
299 for (name, value) in &added {
300 metric.set(name, value.clone()).map_err(external)?;
301 }
302 Some(match result_index.entry(label_set(&metric)) {
303 std::collections::hash_map::Entry::Occupied(entry) => *entry.get(),
304 std::collections::hash_map::Entry::Vacant(entry) => {
305 if let Some(budget) = budget.as_deref_mut() {
306 budget.hold(result_set_bytes(&metric))?;
307 }
308 results.push((metric, Vec::new()));
309 *entry.insert(results.len() - 1)
310 }
311 })
312 };
313 previous = Some(Choice {
314 info: chosen.clone(),
315 result,
316 conflict,
317 });
318 }
319 let choice = previous.as_ref().expect("set above");
320 if let Some(label) = &choice.conflict {
321 error.record(point, 1, || format!("conflicting label: {label}"));
322 }
323 if let Some(result) = choice.result {
324 results[result].1.push((point, values));
325 }
326 }
327 }
328
329 for (metric, rows) in &mut results {
332 if let Some(budget) = budget.as_deref_mut() {
334 budget.phase(rows.len().saturating_mul(2 * std::mem::size_of::<Row>()))?;
335 }
336 rows.sort_by_key(|(point, _)| *point);
337 let mut merged: Vec<Row> = Vec::with_capacity(rows.len());
338 for (point, values) in rows.drain(..) {
339 match merged.last_mut() {
340 Some((last, slots)) if *last == point => {
341 for (slot, value) in slots.iter_mut().zip(values) {
342 if value.is_none() {
343 continue;
344 }
345 if slot.is_some() {
346 error.record(point, 2, || {
347 format!(
348 "vector cannot contain metrics with the same labelset {}",
349 render_label_set(&label_set(metric))
350 )
351 });
352 }
353 *slot = value;
354 }
355 }
356 _ => merged.push((point, values)),
357 }
358 }
359 *rows = merged;
360 }
361 if let Some((_, _, message)) = error.0 {
362 return Err(DataFusionError::Execution(message));
363 }
364
365 let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
366 let mut output = Vec::with_capacity(results.len());
367 if let Some(budget) = budget.as_deref_mut() {
368 budget.phase(0)?;
369 }
370 for (metric, rows) in results {
371 builder.begin_series();
372 if let Some(budget) = budget.as_deref_mut() {
375 budget.grow(column_bytes(&rows, width))?;
376 }
377 builder.reserve_rows(rows.len())?;
378 for (point, row) in rows {
379 builder.push_samples(point, &row)?;
380 }
381 output.extend(builder.finish(metric)?);
382 }
383 Ok(output)
384}
385
386type Row = (usize, Vec<Option<GridSample>>);
388
389const PATTERN_BYTES: usize = 2 * IDENTIFYING_LABELS.len() * std::mem::size_of::<Arc<str>>();
392
393const SIGNATURE_BYTES: usize = 2
396 * (std::mem::size_of::<(Signature, BTreeMap<usize, (f64, usize)>)>()
397 + IDENTIFYING_LABELS.len() * std::mem::size_of::<Option<Arc<str>>>()
398 + std::mem::size_of::<Arc<str>>());
399
400const KEPT_POINT_BYTES: usize = 2 * std::mem::size_of::<(usize, (f64, usize))>();
402
403fn row_bytes(width: usize) -> usize {
406 (2 * std::mem::size_of::<Row>())
407 .saturating_add(width.saturating_mul(std::mem::size_of::<Option<GridSample>>()))
408}
409
410fn result_set_bytes(metric: &SeriesLabels) -> usize {
414 let labels = metric.tags().len().saturating_add(1);
415 labels
416 .saturating_mul(
417 2 * std::mem::size_of::<Label>() + std::mem::size_of::<(Arc<str>, Arc<str>)>(),
418 )
419 .saturating_add(metric.name().map_or(0, str::len))
420 .saturating_add(
421 metric
422 .tags()
423 .iter()
424 .map(|tag| tag.name.len())
425 .sum::<usize>(),
426 )
427 .saturating_add(2 * std::mem::size_of::<(SeriesLabels, Vec<Row>)>())
428 .saturating_add(2 * std::mem::size_of::<(LabelSet, usize)>())
429}
430
431fn column_bytes(rows: &[Row], width: usize) -> usize {
435 let row = std::mem::size_of::<usize>()
436 + 2 * width.saturating_mul(std::mem::size_of::<f64>() + 1)
437 + width.saturating_mul(std::mem::size_of::<Option<u32>>());
438 rows.iter().flat_map(|(_, values)| values).fold(
439 rows.len().saturating_mul(row),
440 |bytes, value| match value {
441 Some(GridSample::Histogram(histogram)) => bytes
442 .saturating_add(HISTOGRAM_ROW_BYTES)
443 .saturating_add(histogram.heap_bytes()),
444 _ => bytes,
445 },
446 )
447}
448
449struct Choice {
451 info: Vec<usize>,
453 result: Option<usize>,
455 conflict: Option<Arc<str>>,
457}
458
459#[derive(Default)]
462struct FirstError(Option<(usize, u8, String)>);
463
464impl FirstError {
465 fn record(&mut self, point: usize, rank: u8, message: impl FnOnce() -> String) {
467 if self
468 .0
469 .as_ref()
470 .is_none_or(|(first, first_rank, _)| (point, rank) < (*first, *first_rank))
471 {
472 self.0 = Some((point, rank, message()));
473 }
474 }
475}
476
477type Signature = (Arc<str>, Vec<Option<Arc<str>>>);
479
480fn identifying_values(metric: &SeriesLabels) -> Vec<Option<Arc<str>>> {
485 IDENTIFYING_LABELS
486 .iter()
487 .map(|label| {
488 metric
489 .tags()
490 .iter()
491 .find(|tag| tag.name.as_ref() == *label)
492 .filter(|tag| !tag.value.is_empty())
493 .map(|tag| Arc::clone(&tag.value))
494 })
495 .collect()
496}
497
498fn add_data_labels(
501 info: &SeriesLabels,
502 base: &SeriesLabels,
503 selector: &InfoSelector,
504 added: &mut Vec<(Arc<str>, Arc<str>)>,
505) -> std::result::Result<(), Arc<str>> {
506 for tag in info.tags() {
507 if tag.value.is_empty()
508 || (!selector.data_labels.is_empty() && !selector.data_labels.contains(&tag.name))
509 {
510 continue;
511 }
512 if let Some((_, value)) = added.iter().find(|(name, _)| *name == tag.name) {
513 if *value != tag.value {
514 return Err(tag.name.clone());
515 }
516 continue;
517 }
518 if base.get(&tag.name).is_some_and(|value| !value.is_empty()) {
519 continue;
520 }
521 added.push((tag.name.clone(), tag.value.clone()));
522 }
523 Ok(())
524}
525
526struct NameMatcher {
527 op: MatchOp,
528 value: Arc<str>,
529 regex: Option<Regex>,
530}
531
532impl NameMatcher {
533 fn try_new(op: MatchOp, value: Arc<str>) -> Result<Self> {
534 let regex = match op {
535 MatchOp::Regex | MatchOp::NotRegex => {
536 Some(Regex::new(&format!("^(?s:{value})$")).map_err(|error| {
537 DataFusionError::Plan(format!("invalid regular expression {value}: {error}"))
538 })?)
539 }
540 MatchOp::Equal | MatchOp::NotEqual => None,
541 };
542 Ok(Self { op, value, regex })
543 }
544
545 fn matches(&self, name: &str) -> bool {
546 match (self.op, &self.regex) {
547 (MatchOp::Equal, _) => name == &*self.value,
548 (MatchOp::NotEqual, _) => name != &*self.value,
549 (MatchOp::Regex, Some(regex)) => regex.is_match(name),
550 (MatchOp::NotRegex, Some(regex)) => !regex.is_match(name),
551 _ => unreachable!("regex matchers compile their regex"),
552 }
553 }
554}
555
556fn effective_name_matchers(matchers: &[(MatchOp, Arc<str>)]) -> Result<Vec<NameMatcher>> {
559 let mut effective = Vec::with_capacity(matchers.len() + 1);
560 if matchers.is_empty() {
561 effective.push(NameMatcher::try_new(
562 MatchOp::Equal,
563 Arc::from("target_info"),
564 )?);
565 } else if matchers
566 .iter()
567 .all(|(op, _)| matches!(op, MatchOp::NotEqual | MatchOp::NotRegex))
568 {
569 effective.push(NameMatcher::try_new(MatchOp::Regex, Arc::from(".+_info"))?);
570 }
571 for (op, value) in matchers {
572 effective.push(NameMatcher::try_new(*op, value.clone())?);
573 }
574 Ok(effective)
575}