tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Label matchers and the postings plan they compile to.
//!
//! A [`LabelMatcher`] is the low-level matcher type Prometheus uses: a label
//! name, a match type and a value. PromQL AST nodes are *not* represented here —
//! a query layer converts its own matchers into this type.
//!
//! Semantics worth calling out, because they decide which series a matcher
//! selects:
//!
//! - a missing label is treated as the empty string, so `{foo=""}` matches
//!   series without `foo`, and `{foo!=""}` matches only series that have a
//!   non-empty `foo`;
//! - `=~` and `!~` are **fully anchored**, i.e. `=~"a|b"` matches `a` and `b`
//!   but not `ab`. Prometheus does the same;
//! - `=~".*"` matches everything and `=~".+"` matches any non-empty value; both
//!   are special-cased in the planner instead of scanning every value.
//!
//! [`IndexReader::postings_for_matchers`] turns a matcher list into a single
//! lazy postings source, mirroring Prometheus' `PostingsForMatchers`: matchers
//! that must hold are intersected, matchers that exclude are subtracted, and
//! the choice of "start from all series" is made the same way.

use crate::error::{Error, Result};

#[cfg(feature = "regex")]
use regex::Regex;

use super::postings_ops::{difference, intersect_all, BoxPostings};
use super::{IndexReader, PostingsList};

/// How a [`LabelMatcher`] compares a label value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MatchType {
    /// `=`: the label value equals the matcher value.
    Equal,
    /// `!=`: the label value differs from the matcher value.
    NotEqual,
    /// `=~`: the label value matches the (fully anchored) regular expression.
    Regex,
    /// `!~`: the label value does not match the regular expression.
    NotRegex,
}

impl MatchType {
    /// True for the two matcher kinds whose value is a regular expression.
    pub fn is_regex(&self) -> bool {
        matches!(self, MatchType::Regex | MatchType::NotRegex)
    }

    /// True for the negated matcher kinds.
    pub fn is_negative(&self) -> bool {
        matches!(self, MatchType::NotEqual | MatchType::NotRegex)
    }

    /// The matcher kind that selects the opposite *label values*.
    ///
    /// The set-level inverse of a matcher ("series that have this label but do
    /// not match") is computed by the planner, not by flipping this type.
    pub fn inverse(&self) -> MatchType {
        match self {
            MatchType::Equal => MatchType::NotEqual,
            MatchType::NotEqual => MatchType::Equal,
            MatchType::Regex => MatchType::NotRegex,
            MatchType::NotRegex => MatchType::Regex,
        }
    }

    /// The PromQL operator for this match type.
    pub fn operator(&self) -> &'static str {
        match self {
            MatchType::Equal => "=",
            MatchType::NotEqual => "!=",
            MatchType::Regex => "=~",
            MatchType::NotRegex => "!~",
        }
    }
}

/// A compiled matcher, so a plan compiles each regex exactly once.
enum Compiled {
    Equal(String),
    NotEqual(String),
    #[cfg(feature = "regex")]
    Regex(Regex),
    #[cfg(feature = "regex")]
    NotRegex(Regex),
}

impl Compiled {
    fn matches(&self, value: &str) -> bool {
        match self {
            Compiled::Equal(v) => value == v,
            Compiled::NotEqual(v) => value != v,
            #[cfg(feature = "regex")]
            Compiled::Regex(re) => re.is_match(value),
            #[cfg(feature = "regex")]
            Compiled::NotRegex(re) => !re.is_match(value),
        }
    }
}

/// A label matcher: `name <op> value`.
///
/// The fields are public so a caller can build one in a struct literal; the
/// constructors are shorthand. `matches` compiles a regex on every call, so a
/// loop over many values should go through
/// [`IndexReader::postings_for_matchers`], which compiles once.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LabelMatcher {
    /// Label name to test. An empty name with an empty value is the "all
    /// series" key.
    pub name: String,
    /// Comparison to apply.
    pub match_type: MatchType,
    /// Value (or regular expression) to compare against.
    pub value: String,
}

impl LabelMatcher {
    /// Builds a matcher from its parts.
    pub fn new(name: impl Into<String>, match_type: MatchType, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            match_type,
            value: value.into(),
        }
    }

    /// `name="value"`.
    pub fn equal(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(name, MatchType::Equal, value)
    }

    /// `name!="value"`.
    pub fn not_equal(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(name, MatchType::NotEqual, value)
    }

    /// `name=~"regex"`.
    pub fn regex(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(name, MatchType::Regex, value)
    }

    /// `name!~"regex"`.
    pub fn not_regex(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(name, MatchType::NotRegex, value)
    }

    /// True for the "all series" matcher (`{""=""}`, the empty key).
    pub fn is_all_postings_key(&self) -> bool {
        self.name.is_empty() && self.value.is_empty() && self.match_type == MatchType::Equal
    }

    /// The matcher with the opposite match type, same name and value.
    ///
    /// Used by the planner to reuse the positive/inverse postings paths.
    pub fn inverted(&self) -> LabelMatcher {
        LabelMatcher {
            name: self.name.clone(),
            match_type: self.match_type.inverse(),
            value: self.value.clone(),
        }
    }

    /// Tests one label value.
    ///
    /// A missing label must be passed as `""`, which is how Prometheus models
    /// absence. Returns an error for a regex matcher whose expression does not
    /// compile, or when the crate is built without the `regex` feature.
    pub fn matches(&self, value: &str) -> Result<bool> {
        Ok(self.compile()?.matches(value))
    }

    /// Tests the empty string: "would this matcher select a series that does
    /// not have the label?".
    pub fn matches_empty(&self) -> Result<bool> {
        self.matches("")
    }

    /// Compiles the matcher, validating a regular expression once.
    fn compile(&self) -> Result<Compiled> {
        match self.match_type {
            MatchType::Equal => Ok(Compiled::Equal(self.value.clone())),
            MatchType::NotEqual => Ok(Compiled::NotEqual(self.value.clone())),
            MatchType::Regex | MatchType::NotRegex => {
                #[cfg(feature = "regex")]
                {
                    let re = compile_anchored(&self.value)?;
                    Ok(match self.match_type {
                        MatchType::Regex => Compiled::Regex(re),
                        _ => Compiled::NotRegex(re),
                    })
                }
                #[cfg(not(feature = "regex"))]
                {
                    Err(Error::Unsupported(
                        "regex label matchers require the `regex` feature".to_string(),
                    ))
                }
            }
        }
    }
}

impl std::fmt::Display for LabelMatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}{}\"{}\"",
            self.name,
            self.match_type.operator(),
            self.value
        )
    }
}

/// Compiles a Prometheus-style fully anchored regex.
///
/// Prometheus wraps the expression as `^(?s:expr)$`: fully anchored (so
/// `=~"a|b"` does not match `ab`) **and** with the dotall flag, which makes `.`
/// match newlines too. Both details change results, so both are reproduced.
#[cfg(feature = "regex")]
fn compile_anchored(expr: &str) -> Result<Regex> {
    let anchored = format!("^(?s:{expr})$");
    Regex::new(&anchored)
        .map_err(|e| Error::format(format!("invalid regular expression {expr:?}: {e}")))
}

impl IndexReader {
    /// Postings of every series that has `name` set to a non-empty value.
    ///
    /// This is what `name=~".+"` selects.
    pub fn postings_for_all_label_values<'a>(&'a self, name: &str) -> Result<BoxPostings<'a>> {
        self.postings_for_values(name, |value| !value.is_empty())
    }

    /// Turns a matcher list into one lazy postings source.
    ///
    /// The plan follows Prometheus' `PostingsForMatchers`:
    ///
    /// 1. a single `{""=""}` matcher selects all series;
    /// 2. matchers that cannot match `""` prove the label is present, which
    ///    lets negative matchers subtract instead of scan every value;
    /// 3. when only excluding matchers remain, the base is all series;
    /// 4. matchers that must hold are intersected, excluding ones subtracted.
    ///
    /// `=~".*"` is a no-op, `!~".*"` selects nothing, and `=~".+"` selects all
    /// series that have the label — the same special cases Prometheus applies.
    pub fn postings_for_matchers<'a>(
        &'a self,
        matchers: &[LabelMatcher],
    ) -> Result<BoxPostings<'a>> {
        if matchers.is_empty() {
            return Ok(Box::new(self.all_postings()?));
        }
        if matchers.len() == 1 && matchers[0].is_all_postings_key() {
            return Ok(Box::new(self.all_postings()?));
        }

        // Compile once: an invalid regex fails here instead of mid-plan.
        let compiled = matchers
            .iter()
            .map(|m| m.compile())
            .collect::<Result<Vec<_>>>()?;

        // A matcher that cannot match "" proves its label is present.
        let mut must_be_set: Vec<bool> = Vec::with_capacity(matchers.len());
        for c in &compiled {
            must_be_set.push(!c.matches(""));
        }
        let mut label_must_be_set = std::collections::HashMap::<&str, bool>::new();
        for (matcher, set) in matchers.iter().zip(&must_be_set) {
            // Within one label name, "any matcher proves the label is set" is
            // enough; a later matcher that matches "" must not undo it.
            let entry = label_must_be_set
                .entry(matcher.name.as_str())
                .or_insert(false);
            *entry = *entry || *set;
        }

        let is_subtracting = |matcher: &LabelMatcher, c: &Compiled| -> bool {
            if !label_must_be_set
                .get(matcher.name.as_str())
                .copied()
                .unwrap_or(false)
            {
                return true;
            }
            matcher.match_type.is_negative() && c.matches("")
        };

        let has_subtracting = matchers
            .iter()
            .zip(&compiled)
            .any(|(m, c)| is_subtracting(m, c));
        let has_intersecting = matchers
            .iter()
            .zip(&compiled)
            .any(|(m, c)| !is_subtracting(m, c));

        let mut intersecting: Vec<BoxPostings<'a>> = Vec::new();
        let mut subtracting: Vec<BoxPostings<'a>> = Vec::new();

        if has_subtracting && !has_intersecting {
            // Nothing to intersect with, so start from every series and let the
            // excluding matchers remove from it.
            intersecting.push(Box::new(self.all_postings()?));
        }

        for (index, matcher) in matchers.iter().enumerate() {
            if matcher.is_all_postings_key() {
                return Err(Error::format(
                    "the all-postings matcher must be the only matcher",
                ));
            }

            // `.*` matches every value, including the empty one.
            if matcher.match_type == MatchType::Regex && matcher.value == ".*" {
                continue;
            }
            if matcher.match_type == MatchType::NotRegex && matcher.value == ".*" {
                return Ok(Box::new(PostingsList::empty()));
            }

            // `.+` matches every non-empty value.
            if matcher.match_type == MatchType::Regex && matcher.value == ".+" {
                intersecting.push(self.postings_for_all_label_values(&matcher.name)?);
                continue;
            }
            if matcher.match_type == MatchType::NotRegex && matcher.value == ".+" {
                subtracting.push(self.postings_for_all_label_values(&matcher.name)?);
                continue;
            }

            let name_is_set = label_must_be_set
                .get(matcher.name.as_str())
                .copied()
                .unwrap_or(false);
            // `must_be_set[index]` is "this matcher does not accept """, so its
            // negation tells us whether the matcher would select a series that
            // lacks the label.
            let matches_empty = !must_be_set[index];
            let negative = matcher.match_type.is_negative();

            match (name_is_set, negative, matches_empty) {
                // The label is proven present and the matcher is negative but
                // rejects "": subtract the positive counterpart (`l!="foo"`).
                (true, true, true) => {
                    let inverse = matcher.inverted();
                    subtracting.push(self.postings_for_positive(&inverse)?);
                }
                // Negative matcher that accepts "" (`l!=""`): keep the series
                // where the inverse holds, i.e. the label is set.
                (true, true, false) => {
                    let inverse = matcher.inverted();
                    intersecting.push(self.postings_for_inverse(&inverse)?);
                }
                // Positive matcher whose label must be set: intersect.
                (true, false, _) => {
                    intersecting.push(self.postings_for_positive(matcher)?);
                }
                // The matcher accepts "", so it also selects series without the
                // label: subtract the ones that have it and match.
                (false, _, _) => {
                    subtracting.push(self.postings_for_inverse(matcher)?);
                }
            }
        }

        let mut plan = intersect_all(intersecting);
        for subtract in subtracting {
            plan = Box::new(difference(plan, subtract));
        }
        Ok(plan)
    }

    /// Postings for a matcher that must hold (`=`, `=~`).
    fn postings_for_positive<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
        match matcher.match_type {
            MatchType::Equal => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
            MatchType::Regex => {
                let compiled = matcher.compile()?;
                self.postings_for_values(&matcher.name, |value| compiled.matches(value))
            }
            _ => Err(Error::format(format!(
                "postings_for_positive called with {matcher}"
            ))),
        }
    }

    /// Postings of series that have `matcher.name` set but do not match it.
    ///
    /// This is the set-level inverse Prometheus calls
    /// `inversePostingsForMatcher`: the label must be present, and the value
    /// must fail the matcher.
    fn postings_for_inverse<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
        if matcher.name.is_empty() {
            return Ok(Box::new(PostingsList::empty()));
        }
        let compiled = matcher.compile()?;
        match matcher.match_type {
            // The inverse of `!= x` is `= x`.
            MatchType::NotEqual => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
            // The inverse of `!~ re` is `=~ re`; `compiled` holds the negated
            // matcher, so negating its verdict yields "matches re".
            MatchType::NotRegex => {
                self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
            }
            // `=""` and `=~""` invert to "the label is set at all".
            MatchType::Equal | MatchType::Regex if matcher.value.is_empty() => {
                self.postings_for_all_label_values(&matcher.name)
            }
            MatchType::Equal => {
                self.postings_for_values(&matcher.name, |value| value != matcher.value)
            }
            MatchType::Regex => {
                self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn equality_semantics() {
        let m = LabelMatcher::equal("job", "api");
        assert!(m.matches("api").unwrap());
        assert!(!m.matches("api2").unwrap());
        assert!(!m.matches("").unwrap());
        assert_eq!(m.to_string(), "job=\"api\"");
    }

    #[test]
    fn negative_equality_treats_missing_as_empty() {
        let m = LabelMatcher::not_equal("job", "api");
        assert!(!m.matches("api").unwrap());
        assert!(m.matches("web").unwrap());
        // A missing label is the empty string, which differs from "api".
        assert!(m.matches("").unwrap());
    }

    #[cfg(feature = "regex")]
    #[test]
    fn regex_is_fully_anchored() {
        let m = LabelMatcher::regex("job", "a|b");
        assert!(m.matches("a").unwrap());
        assert!(m.matches("b").unwrap());
        assert!(!m.matches("ab").unwrap());
        assert!(!m.matches("").unwrap());
        assert!(!m.matches("xa").unwrap());
    }

    #[cfg(feature = "regex")]
    #[test]
    fn negative_regex_inverts_the_match() {
        let m = LabelMatcher::not_regex("job", "a|b");
        assert!(!m.matches("a").unwrap());
        assert!(m.matches("c").unwrap());
        assert!(m.matches("").unwrap());
    }

    #[cfg(feature = "regex")]
    #[test]
    fn invalid_regex_reports_the_expression() {
        let m = LabelMatcher::regex("job", "a[");
        let error = m.matches("a").unwrap_err();
        assert!(
            error.to_string().contains("invalid regular expression"),
            "{error}"
        );
    }

    #[test]
    fn matcher_kind_helpers() {
        assert!(MatchType::Regex.is_regex());
        assert!(!MatchType::Equal.is_regex());
        assert!(MatchType::NotEqual.is_negative());
        assert_eq!(MatchType::Equal.inverse(), MatchType::NotEqual);
        assert_eq!(MatchType::Regex.inverse(), MatchType::NotRegex);
        assert_eq!(MatchType::NotRegex.operator(), "!~");
    }

    #[test]
    fn the_all_postings_key_is_recognised() {
        assert!(LabelMatcher::equal("", "").is_all_postings_key());
        assert!(!LabelMatcher::equal("a", "").is_all_postings_key());
        assert!(!LabelMatcher::not_equal("", "").is_all_postings_key());
    }
}