Skip to main content

tsdb_reader/index/
matcher.rs

1//! Label matchers and the postings plan they compile to.
2//!
3//! A [`LabelMatcher`] is the low-level matcher type Prometheus uses: a label
4//! name, a match type and a value. PromQL AST nodes are *not* represented here —
5//! a query layer converts its own matchers into this type.
6//!
7//! Semantics worth calling out, because they decide which series a matcher
8//! selects:
9//!
10//! - a missing label is treated as the empty string, so `{foo=""}` matches
11//!   series without `foo`, and `{foo!=""}` matches only series that have a
12//!   non-empty `foo`;
13//! - `=~` and `!~` are **fully anchored**, i.e. `=~"a|b"` matches `a` and `b`
14//!   but not `ab`. Prometheus does the same;
15//! - `=~".*"` matches everything and `=~".+"` matches any non-empty value; both
16//!   are special-cased in the planner instead of scanning every value.
17//!
18//! [`IndexReader::postings_for_matchers`] turns a matcher list into a single
19//! lazy postings source, mirroring Prometheus' `PostingsForMatchers`: matchers
20//! that must hold are intersected, matchers that exclude are subtracted, and
21//! the choice of "start from all series" is made the same way.
22
23use crate::error::{Error, Result};
24
25#[cfg(feature = "regex")]
26use regex::Regex;
27
28use super::postings_ops::{difference, intersect_all, BoxPostings};
29use super::{IndexReader, PostingsList};
30
31/// How a [`LabelMatcher`] compares a label value.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum MatchType {
34    /// `=`: the label value equals the matcher value.
35    Equal,
36    /// `!=`: the label value differs from the matcher value.
37    NotEqual,
38    /// `=~`: the label value matches the (fully anchored) regular expression.
39    Regex,
40    /// `!~`: the label value does not match the regular expression.
41    NotRegex,
42}
43
44impl MatchType {
45    /// True for the two matcher kinds whose value is a regular expression.
46    pub fn is_regex(&self) -> bool {
47        matches!(self, MatchType::Regex | MatchType::NotRegex)
48    }
49
50    /// True for the negated matcher kinds.
51    pub fn is_negative(&self) -> bool {
52        matches!(self, MatchType::NotEqual | MatchType::NotRegex)
53    }
54
55    /// The matcher kind that selects the opposite *label values*.
56    ///
57    /// The set-level inverse of a matcher ("series that have this label but do
58    /// not match") is computed by the planner, not by flipping this type.
59    pub fn inverse(&self) -> MatchType {
60        match self {
61            MatchType::Equal => MatchType::NotEqual,
62            MatchType::NotEqual => MatchType::Equal,
63            MatchType::Regex => MatchType::NotRegex,
64            MatchType::NotRegex => MatchType::Regex,
65        }
66    }
67
68    /// The PromQL operator for this match type.
69    pub fn operator(&self) -> &'static str {
70        match self {
71            MatchType::Equal => "=",
72            MatchType::NotEqual => "!=",
73            MatchType::Regex => "=~",
74            MatchType::NotRegex => "!~",
75        }
76    }
77}
78
79/// A compiled matcher, so a plan compiles each regex exactly once.
80enum Compiled {
81    Equal(String),
82    NotEqual(String),
83    #[cfg(feature = "regex")]
84    Regex(Regex),
85    #[cfg(feature = "regex")]
86    NotRegex(Regex),
87}
88
89impl Compiled {
90    fn matches(&self, value: &str) -> bool {
91        match self {
92            Compiled::Equal(v) => value == v,
93            Compiled::NotEqual(v) => value != v,
94            #[cfg(feature = "regex")]
95            Compiled::Regex(re) => re.is_match(value),
96            #[cfg(feature = "regex")]
97            Compiled::NotRegex(re) => !re.is_match(value),
98        }
99    }
100}
101
102/// A label matcher: `name <op> value`.
103///
104/// The fields are public so a caller can build one in a struct literal; the
105/// constructors are shorthand. `matches` compiles a regex on every call, so a
106/// loop over many values should go through
107/// [`IndexReader::postings_for_matchers`], which compiles once.
108#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109pub struct LabelMatcher {
110    /// Label name to test. An empty name with an empty value is the "all
111    /// series" key.
112    pub name: String,
113    /// Comparison to apply.
114    pub match_type: MatchType,
115    /// Value (or regular expression) to compare against.
116    pub value: String,
117}
118
119impl LabelMatcher {
120    /// Builds a matcher from its parts.
121    pub fn new(name: impl Into<String>, match_type: MatchType, value: impl Into<String>) -> Self {
122        Self {
123            name: name.into(),
124            match_type,
125            value: value.into(),
126        }
127    }
128
129    /// `name="value"`.
130    pub fn equal(name: impl Into<String>, value: impl Into<String>) -> Self {
131        Self::new(name, MatchType::Equal, value)
132    }
133
134    /// `name!="value"`.
135    pub fn not_equal(name: impl Into<String>, value: impl Into<String>) -> Self {
136        Self::new(name, MatchType::NotEqual, value)
137    }
138
139    /// `name=~"regex"`.
140    pub fn regex(name: impl Into<String>, value: impl Into<String>) -> Self {
141        Self::new(name, MatchType::Regex, value)
142    }
143
144    /// `name!~"regex"`.
145    pub fn not_regex(name: impl Into<String>, value: impl Into<String>) -> Self {
146        Self::new(name, MatchType::NotRegex, value)
147    }
148
149    /// True for the "all series" matcher (`{""=""}`, the empty key).
150    pub fn is_all_postings_key(&self) -> bool {
151        self.name.is_empty() && self.value.is_empty() && self.match_type == MatchType::Equal
152    }
153
154    /// The matcher with the opposite match type, same name and value.
155    ///
156    /// Used by the planner to reuse the positive/inverse postings paths.
157    pub fn inverted(&self) -> LabelMatcher {
158        LabelMatcher {
159            name: self.name.clone(),
160            match_type: self.match_type.inverse(),
161            value: self.value.clone(),
162        }
163    }
164
165    /// Tests one label value.
166    ///
167    /// A missing label must be passed as `""`, which is how Prometheus models
168    /// absence. Returns an error for a regex matcher whose expression does not
169    /// compile, or when the crate is built without the `regex` feature.
170    pub fn matches(&self, value: &str) -> Result<bool> {
171        Ok(self.compile()?.matches(value))
172    }
173
174    /// Tests the empty string: "would this matcher select a series that does
175    /// not have the label?".
176    pub fn matches_empty(&self) -> Result<bool> {
177        self.matches("")
178    }
179
180    /// Compiles the matcher, validating a regular expression once.
181    fn compile(&self) -> Result<Compiled> {
182        match self.match_type {
183            MatchType::Equal => Ok(Compiled::Equal(self.value.clone())),
184            MatchType::NotEqual => Ok(Compiled::NotEqual(self.value.clone())),
185            MatchType::Regex | MatchType::NotRegex => {
186                #[cfg(feature = "regex")]
187                {
188                    let re = compile_anchored(&self.value)?;
189                    Ok(match self.match_type {
190                        MatchType::Regex => Compiled::Regex(re),
191                        _ => Compiled::NotRegex(re),
192                    })
193                }
194                #[cfg(not(feature = "regex"))]
195                {
196                    Err(Error::Unsupported(
197                        "regex label matchers require the `regex` feature".to_string(),
198                    ))
199                }
200            }
201        }
202    }
203}
204
205impl std::fmt::Display for LabelMatcher {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        write!(
208            f,
209            "{}{}\"{}\"",
210            self.name,
211            self.match_type.operator(),
212            self.value
213        )
214    }
215}
216
217/// Compiles a Prometheus-style fully anchored regex.
218///
219/// Prometheus wraps the expression as `^(?s:expr)$`: fully anchored (so
220/// `=~"a|b"` does not match `ab`) **and** with the dotall flag, which makes `.`
221/// match newlines too. Both details change results, so both are reproduced.
222#[cfg(feature = "regex")]
223fn compile_anchored(expr: &str) -> Result<Regex> {
224    let anchored = format!("^(?s:{expr})$");
225    Regex::new(&anchored)
226        .map_err(|e| Error::format(format!("invalid regular expression {expr:?}: {e}")))
227}
228
229impl IndexReader {
230    /// Postings of every series that has `name` set to a non-empty value.
231    ///
232    /// This is what `name=~".+"` selects.
233    pub fn postings_for_all_label_values<'a>(&'a self, name: &str) -> Result<BoxPostings<'a>> {
234        self.postings_for_values(name, |value| !value.is_empty())
235    }
236
237    /// Turns a matcher list into one lazy postings source.
238    ///
239    /// The plan follows Prometheus' `PostingsForMatchers`:
240    ///
241    /// 1. a single `{""=""}` matcher selects all series;
242    /// 2. matchers that cannot match `""` prove the label is present, which
243    ///    lets negative matchers subtract instead of scan every value;
244    /// 3. when only excluding matchers remain, the base is all series;
245    /// 4. matchers that must hold are intersected, excluding ones subtracted.
246    ///
247    /// `=~".*"` is a no-op, `!~".*"` selects nothing, and `=~".+"` selects all
248    /// series that have the label — the same special cases Prometheus applies.
249    pub fn postings_for_matchers<'a>(
250        &'a self,
251        matchers: &[LabelMatcher],
252    ) -> Result<BoxPostings<'a>> {
253        if matchers.is_empty() {
254            return Ok(Box::new(self.all_postings()?));
255        }
256        if matchers.len() == 1 && matchers[0].is_all_postings_key() {
257            return Ok(Box::new(self.all_postings()?));
258        }
259
260        // Compile once: an invalid regex fails here instead of mid-plan.
261        let compiled = matchers
262            .iter()
263            .map(|m| m.compile())
264            .collect::<Result<Vec<_>>>()?;
265
266        // A matcher that cannot match "" proves its label is present.
267        let mut must_be_set: Vec<bool> = Vec::with_capacity(matchers.len());
268        for c in &compiled {
269            must_be_set.push(!c.matches(""));
270        }
271        let mut label_must_be_set = std::collections::HashMap::<&str, bool>::new();
272        for (matcher, set) in matchers.iter().zip(&must_be_set) {
273            // Within one label name, "any matcher proves the label is set" is
274            // enough; a later matcher that matches "" must not undo it.
275            let entry = label_must_be_set
276                .entry(matcher.name.as_str())
277                .or_insert(false);
278            *entry = *entry || *set;
279        }
280
281        let is_subtracting = |matcher: &LabelMatcher, c: &Compiled| -> bool {
282            if !label_must_be_set
283                .get(matcher.name.as_str())
284                .copied()
285                .unwrap_or(false)
286            {
287                return true;
288            }
289            matcher.match_type.is_negative() && c.matches("")
290        };
291
292        let has_subtracting = matchers
293            .iter()
294            .zip(&compiled)
295            .any(|(m, c)| is_subtracting(m, c));
296        let has_intersecting = matchers
297            .iter()
298            .zip(&compiled)
299            .any(|(m, c)| !is_subtracting(m, c));
300
301        let mut intersecting: Vec<BoxPostings<'a>> = Vec::new();
302        let mut subtracting: Vec<BoxPostings<'a>> = Vec::new();
303
304        if has_subtracting && !has_intersecting {
305            // Nothing to intersect with, so start from every series and let the
306            // excluding matchers remove from it.
307            intersecting.push(Box::new(self.all_postings()?));
308        }
309
310        for (index, matcher) in matchers.iter().enumerate() {
311            if matcher.is_all_postings_key() {
312                return Err(Error::format(
313                    "the all-postings matcher must be the only matcher",
314                ));
315            }
316
317            // `.*` matches every value, including the empty one.
318            if matcher.match_type == MatchType::Regex && matcher.value == ".*" {
319                continue;
320            }
321            if matcher.match_type == MatchType::NotRegex && matcher.value == ".*" {
322                return Ok(Box::new(PostingsList::empty()));
323            }
324
325            // `.+` matches every non-empty value.
326            if matcher.match_type == MatchType::Regex && matcher.value == ".+" {
327                intersecting.push(self.postings_for_all_label_values(&matcher.name)?);
328                continue;
329            }
330            if matcher.match_type == MatchType::NotRegex && matcher.value == ".+" {
331                subtracting.push(self.postings_for_all_label_values(&matcher.name)?);
332                continue;
333            }
334
335            let name_is_set = label_must_be_set
336                .get(matcher.name.as_str())
337                .copied()
338                .unwrap_or(false);
339            // `must_be_set[index]` is "this matcher does not accept """, so its
340            // negation tells us whether the matcher would select a series that
341            // lacks the label.
342            let matches_empty = !must_be_set[index];
343            let negative = matcher.match_type.is_negative();
344
345            match (name_is_set, negative, matches_empty) {
346                // The label is proven present and the matcher is negative but
347                // rejects "": subtract the positive counterpart (`l!="foo"`).
348                (true, true, true) => {
349                    let inverse = matcher.inverted();
350                    subtracting.push(self.postings_for_positive(&inverse)?);
351                }
352                // Negative matcher that accepts "" (`l!=""`): keep the series
353                // where the inverse holds, i.e. the label is set.
354                (true, true, false) => {
355                    let inverse = matcher.inverted();
356                    intersecting.push(self.postings_for_inverse(&inverse)?);
357                }
358                // Positive matcher whose label must be set: intersect.
359                (true, false, _) => {
360                    intersecting.push(self.postings_for_positive(matcher)?);
361                }
362                // The matcher accepts "", so it also selects series without the
363                // label: subtract the ones that have it and match.
364                (false, _, _) => {
365                    subtracting.push(self.postings_for_inverse(matcher)?);
366                }
367            }
368        }
369
370        let mut plan = intersect_all(intersecting);
371        for subtract in subtracting {
372            plan = Box::new(difference(plan, subtract));
373        }
374        Ok(plan)
375    }
376
377    /// Postings for a matcher that must hold (`=`, `=~`).
378    fn postings_for_positive<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
379        match matcher.match_type {
380            MatchType::Equal => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
381            MatchType::Regex => {
382                let compiled = matcher.compile()?;
383                self.postings_for_values(&matcher.name, |value| compiled.matches(value))
384            }
385            _ => Err(Error::format(format!(
386                "postings_for_positive called with {matcher}"
387            ))),
388        }
389    }
390
391    /// Postings of series that have `matcher.name` set but do not match it.
392    ///
393    /// This is the set-level inverse Prometheus calls
394    /// `inversePostingsForMatcher`: the label must be present, and the value
395    /// must fail the matcher.
396    fn postings_for_inverse<'a>(&'a self, matcher: &LabelMatcher) -> Result<BoxPostings<'a>> {
397        if matcher.name.is_empty() {
398            return Ok(Box::new(PostingsList::empty()));
399        }
400        let compiled = matcher.compile()?;
401        match matcher.match_type {
402            // The inverse of `!= x` is `= x`.
403            MatchType::NotEqual => Ok(Box::new(self.postings(&matcher.name, &matcher.value)?)),
404            // The inverse of `!~ re` is `=~ re`; `compiled` holds the negated
405            // matcher, so negating its verdict yields "matches re".
406            MatchType::NotRegex => {
407                self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
408            }
409            // `=""` and `=~""` invert to "the label is set at all".
410            MatchType::Equal | MatchType::Regex if matcher.value.is_empty() => {
411                self.postings_for_all_label_values(&matcher.name)
412            }
413            MatchType::Equal => {
414                self.postings_for_values(&matcher.name, |value| value != matcher.value)
415            }
416            MatchType::Regex => {
417                self.postings_for_values(&matcher.name, |value| !compiled.matches(value))
418            }
419        }
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn equality_semantics() {
429        let m = LabelMatcher::equal("job", "api");
430        assert!(m.matches("api").unwrap());
431        assert!(!m.matches("api2").unwrap());
432        assert!(!m.matches("").unwrap());
433        assert_eq!(m.to_string(), "job=\"api\"");
434    }
435
436    #[test]
437    fn negative_equality_treats_missing_as_empty() {
438        let m = LabelMatcher::not_equal("job", "api");
439        assert!(!m.matches("api").unwrap());
440        assert!(m.matches("web").unwrap());
441        // A missing label is the empty string, which differs from "api".
442        assert!(m.matches("").unwrap());
443    }
444
445    #[cfg(feature = "regex")]
446    #[test]
447    fn regex_is_fully_anchored() {
448        let m = LabelMatcher::regex("job", "a|b");
449        assert!(m.matches("a").unwrap());
450        assert!(m.matches("b").unwrap());
451        assert!(!m.matches("ab").unwrap());
452        assert!(!m.matches("").unwrap());
453        assert!(!m.matches("xa").unwrap());
454    }
455
456    #[cfg(feature = "regex")]
457    #[test]
458    fn negative_regex_inverts_the_match() {
459        let m = LabelMatcher::not_regex("job", "a|b");
460        assert!(!m.matches("a").unwrap());
461        assert!(m.matches("c").unwrap());
462        assert!(m.matches("").unwrap());
463    }
464
465    #[cfg(feature = "regex")]
466    #[test]
467    fn invalid_regex_reports_the_expression() {
468        let m = LabelMatcher::regex("job", "a[");
469        let error = m.matches("a").unwrap_err();
470        assert!(
471            error.to_string().contains("invalid regular expression"),
472            "{error}"
473        );
474    }
475
476    #[test]
477    fn matcher_kind_helpers() {
478        assert!(MatchType::Regex.is_regex());
479        assert!(!MatchType::Equal.is_regex());
480        assert!(MatchType::NotEqual.is_negative());
481        assert_eq!(MatchType::Equal.inverse(), MatchType::NotEqual);
482        assert_eq!(MatchType::Regex.inverse(), MatchType::NotRegex);
483        assert_eq!(MatchType::NotRegex.operator(), "!~");
484    }
485
486    #[test]
487    fn the_all_postings_key_is_recognised() {
488        assert!(LabelMatcher::equal("", "").is_all_postings_key());
489        assert!(!LabelMatcher::equal("a", "").is_all_postings_key());
490        assert!(!LabelMatcher::not_equal("", "").is_all_postings_key());
491    }
492}