chronix 0.7.0

Chronix — an embedded, analytics-optimised time-series database.
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! `PromQL` abstract syntax tree types.

use std::fmt;

/// Duration in seconds (for range selectors, offsets, etc.).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Duration(pub f64);

impl Duration {
    /// Returns the duration in seconds.
    #[must_use]
    pub fn as_secs(&self) -> f64 {
        self.0
    }

    /// Returns the duration in nanoseconds.
    ///
    /// Clamps to `i64::MIN..=i64::MAX` to avoid undefined saturating
    /// behaviour when the float overflows.
    #[must_use]
    pub fn as_nanos(&self) -> i64 {
        secs_to_nanos_safe(self.0)
    }

    /// Returns the duration in milliseconds.
    ///
    /// Clamps to `i64::MIN..=i64::MAX`.
    #[must_use]
    pub fn as_millis(&self) -> i64 {
        let ms = self.0 * 1_000.0;
        float_to_i64_safe(ms)
    }
}

// ─── Safe numeric helpers ────────────────────────────────────────────

/// Convert seconds (f64) to nanoseconds (i64) without saturating-cast UB.
#[inline]
fn secs_to_nanos_safe(secs: f64) -> i64 {
    let ns = secs * 1_000_000_000.0;
    float_to_i64_safe(ns)
}

/// Clamp an f64 into the representable `i64` range before casting.
#[inline]
fn float_to_i64_safe(v: f64) -> i64 {
    #[allow(clippy::cast_possible_truncation)]
    if v.is_nan() {
        0
    } else if v >= i64::MAX as f64 {
        i64::MAX
    } else if v <= i64::MIN as f64 {
        i64::MIN
    } else {
        v as i64
    }
}

/// A label matcher.
#[derive(Debug, Clone, PartialEq)]
pub struct LabelMatcher {
    /// Label name.
    pub name: String,
    /// Match operator.
    pub op: MatchOp,
    /// Match value.
    pub value: String,
}

impl LabelMatcher {
    /// Whether this matcher is satisfied by a series that does **not** carry
    /// the label at all.
    ///
    /// An absent label reads as the empty string, so this is "does it match
    /// the empty value". A selector made only of such matchers names the whole
    /// database, which is why Prometheus refuses one.
    ///
    /// An invalid regex answers `false`; it is reported where the matcher is
    /// compiled, and answering `true` here would turn a bad pattern into the
    /// wrong error.
    #[must_use]
    pub fn matches_empty(&self) -> bool {
        match self.op {
            MatchOp::Equal => self.value.is_empty(),
            MatchOp::NotEqual => !self.value.is_empty(),
            MatchOp::RegexMatch | MatchOp::RegexNotMatch => {
                // Anchored and `(?s)`, exactly as `CompiledMatcher` anchors.
                let Ok(re) = regex::Regex::new(&format!("^(?s:{})$", self.value)) else {
                    return false;
                };
                re.is_match("") == (self.op == MatchOp::RegexMatch)
            }
        }
    }
}

/// Match operator for label matchers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchOp {
    /// `=`
    Equal,
    /// `!=`
    NotEqual,
    /// `=~`
    RegexMatch,
    /// `!~`
    RegexNotMatch,
}

impl fmt::Display for MatchOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MatchOp::Equal => write!(f, "="),
            MatchOp::NotEqual => write!(f, "!="),
            MatchOp::RegexMatch => write!(f, "=~"),
            MatchOp::RegexNotMatch => write!(f, "!~"),
        }
    }
}

/// Aggregation modifier: `by (labels)` or `without (labels)`.
#[derive(Debug, Clone, PartialEq)]
pub enum AggregationModifier {
    /// Aggregate by the specified labels.
    By(Vec<String>),
    /// Aggregate without the specified labels.
    Without(Vec<String>),
}

/// Aggregation operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregationOp {
    /// `sum` aggregation.
    Sum,
    /// `avg` aggregation.
    Avg,
    /// `min` aggregation.
    Min,
    /// `max` aggregation.
    Max,
    /// `count` aggregation.
    Count,
    /// `stddev` aggregation.
    Stddev,
    /// `stdvar` aggregation.
    Stdvar,
    /// `topk` aggregation.
    Topk,
    /// `bottomk` aggregation.
    Bottomk,
    /// `quantile` aggregation.
    Quantile,
    /// `count_values` aggregation.
    CountValues,
    /// `group` aggregation.
    Group,
}

impl AggregationOp {
    /// Parses an aggregation operator from a string (case-insensitive).
    #[must_use]
    pub fn parse_op(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "sum" => Some(Self::Sum),
            "avg" => Some(Self::Avg),
            "min" => Some(Self::Min),
            "max" => Some(Self::Max),
            "count" => Some(Self::Count),
            "stddev" => Some(Self::Stddev),
            "stdvar" => Some(Self::Stdvar),
            "topk" => Some(Self::Topk),
            "bottomk" => Some(Self::Bottomk),
            "quantile" => Some(Self::Quantile),
            "count_values" => Some(Self::CountValues),
            "group" => Some(Self::Group),
            _ => None,
        }
    }
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
    /// Addition (`+`).
    Add,
    /// Subtraction (`-`).
    Sub,
    /// Multiplication (`*`).
    Mul,
    /// Division (`/`).
    Div,
    /// Modulo (`%`).
    Mod,
    /// Exponentiation (`^`).
    Pow,
    /// Equal comparison (`==`).
    Eql,
    /// Not-equal comparison (`!=`).
    Neq,
    /// Less-than comparison (`<`).
    Lss,
    /// Greater-than comparison (`>`).
    Gtr,
    /// Less-than-or-equal comparison (`<=`).
    Lte,
    /// Greater-than-or-equal comparison (`>=`).
    Gte,
    /// Logical AND set operator.
    And,
    /// Logical OR set operator.
    Or,
    /// UNLESS set operator.
    Unless,
}

impl BinaryOp {
    /// Precedence (higher = binds tighter).
    #[must_use]
    pub fn precedence(self) -> u8 {
        match self {
            BinaryOp::Or => 1,
            // Prometheus: `and` and `unless` share the same precedence.
            BinaryOp::And | BinaryOp::Unless => 2,
            BinaryOp::Eql
            | BinaryOp::Neq
            | BinaryOp::Lss
            | BinaryOp::Gtr
            | BinaryOp::Lte
            | BinaryOp::Gte => 3,
            BinaryOp::Add | BinaryOp::Sub => 4,
            BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => 5,
            BinaryOp::Pow => 6,
        }
    }

    /// Right-associative (only Pow).
    #[must_use]
    pub fn is_right_assoc(self) -> bool {
        matches!(self, BinaryOp::Pow)
    }

    /// Returns `true` if this is a comparison operator.
    #[must_use]
    pub fn is_comparison(self) -> bool {
        matches!(
            self,
            BinaryOp::Eql
                | BinaryOp::Neq
                | BinaryOp::Lss
                | BinaryOp::Gtr
                | BinaryOp::Lte
                | BinaryOp::Gte
        )
    }

    /// Returns `true` if this is a set operator (`and`, `or`, `unless`).
    #[must_use]
    pub fn is_set_operator(self) -> bool {
        matches!(self, BinaryOp::And | BinaryOp::Or | BinaryOp::Unless)
    }

    /// Returns `true` if this is an arithmetic operator (`+`, `-`, `*`, `/`, `%`, `^`).
    #[must_use]
    pub fn is_arithmetic(self) -> bool {
        matches!(
            self,
            BinaryOp::Add
                | BinaryOp::Sub
                | BinaryOp::Mul
                | BinaryOp::Div
                | BinaryOp::Mod
                | BinaryOp::Pow
        )
    }
}

/// Vector matching for binary operations.
#[derive(Debug, Clone, PartialEq)]
pub struct VectorMatching {
    /// Matching cardinality.
    pub card: VectorMatchingCardinality,
    /// Labels used for matching.
    pub labels: Vec<String>,
    /// `true` for `on(...)`, `false` for `ignoring(...)`.
    pub on: bool,
    /// Labels to include from the "one" side in group_left/group_right.
    pub include: Vec<String>,
}

/// Cardinality of a binary vector matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VectorMatchingCardinality {
    /// One-to-one matching.
    OneToOne,
    /// Many-to-one matching (with `group_left`).
    ManyToOne,
    /// One-to-many matching (with `group_right`).
    OneToMany,
    /// Many-to-many matching.
    ManyToMany,
}

/// The `PromQL` AST node.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// A numeric literal: `42`, `1.5`.
    NumberLiteral(f64),

    /// A string literal: `"hello"`.
    StringLiteral(String),

    /// An instant vector selector: `metric_name{label="value"}`.
    VectorSelector {
        /// The metric name (can be empty if __name__ matcher is present).
        name: Option<String>,
        /// Label matchers.
        matchers: Vec<LabelMatcher>,
        /// Optional offset: `offset 5m`. Negative shifts forward in time.
        offset: Option<Duration>,
        /// Optional `@` modifier, pinning the evaluation instant.
        at: Option<AtModifier>,
    },

    /// A matrix selector: `metric_name{...}[5m]`.
    MatrixSelector {
        /// The vector selector.
        vector: Box<Expr>,
        /// The range duration.
        range: Duration,
    },

    /// A function call: `rate(http_requests_total[5m])`.
    Call {
        /// Function name.
        func: String,
        /// Function arguments.
        args: Vec<Expr>,
    },

    /// An aggregation: `sum by (host) (metric)`.
    Aggregation {
        /// Aggregation operator.
        op: AggregationOp,
        /// Expression to aggregate.
        expr: Box<Expr>,
        /// Optional parameter (e.g. k for `topk`).
        param: Option<Box<Expr>>,
        /// Optional `by` or `without` modifier.
        modifier: Option<AggregationModifier>,
    },

    /// A binary expression: `a + b`.
    BinaryExpr {
        /// Binary operator.
        op: BinaryOp,
        /// Left-hand side expression.
        lhs: Box<Expr>,
        /// Right-hand side expression.
        rhs: Box<Expr>,
        /// Whether the `bool` modifier is present.
        bool_mod: bool,
        /// Optional vector matching clause.
        matching: Option<VectorMatching>,
    },

    /// A unary negation: `-expr`.
    UnaryExpr {
        /// Unary operator.
        op: UnaryOp,
        /// Inner expression.
        expr: Box<Expr>,
    },

    /// Parenthesized expression.
    Paren(Box<Expr>),

    /// A subquery: `metric[5m:1m]`.
    Subquery {
        /// Inner expression.
        expr: Box<Expr>,
        /// Range duration.
        range: Duration,
        /// Optional step duration.
        step: Option<Duration>,
        /// Optional offset. Negative shifts forward in time.
        offset: Option<Duration>,
        /// Optional `@` modifier, pinning the evaluation instant.
        at: Option<AtModifier>,
    },
}

/// The `@` modifier: pins a selector's evaluation to a fixed instant.
///
/// `foo @ 1609746000` always reads the sample at that Unix second, whatever
/// time the query is evaluated at, and `foo @ start()` / `@ end()` resolve to
/// a range query's own bounds. The point of it is that one expression can
/// compare a moving value against a fixed one —
/// `rate(x[5m]) / rate(x[5m] @ start())` — which is otherwise not expressible.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AtModifier {
    /// An absolute instant, in Unix **seconds** as written.
    Timestamp(f64),
    /// The range query's start (`@ start()`); the evaluation time for an
    /// instant query, which is what Prometheus does.
    Start,
    /// The range query's end (`@ end()`).
    End,
}

impl AtModifier {
    /// Resolve to an absolute nanosecond instant.
    ///
    /// `start` and `end` are the range query's bounds; for an instant query
    /// both are the evaluation time.
    #[must_use]
    pub fn resolve(self, start: i64, end: i64) -> i64 {
        match self {
            Self::Timestamp(secs) => secs_to_nanos_safe(secs),
            Self::Start => start,
            Self::End => end,
        }
    }
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
    /// Negation (`-`).
    Neg,
}

// ── Query types ────────────────────────────────────────────────────────

/// A single sample (timestamp + value).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sample {
    /// Timestamp in nanoseconds.
    pub timestamp: i64,
    /// Sample value.
    pub value: f64,
}

/// A series of samples with labels.
#[derive(Debug, Clone, PartialEq)]
pub struct Series {
    /// Label key-value pairs identifying the series.
    pub labels: Vec<(String, String)>,
    /// Float samples in the series.
    pub samples: Vec<Sample>,
    /// Native-histogram samples in the series.
    ///
    /// A **separate list**, not a sum type on [`Sample`], which is the shape
    /// Prometheus itself uses (`Series.Floats` beside `Series.Histograms`).
    /// The reason is not taste: nearly every operator in PromQL — `rate`,
    /// the arithmetic, the comparison operators, the `*_over_time` family —
    /// is defined on floats and has nothing to say about a distribution.
    /// Making `Sample::value` a sum type would put a `match` in all of them
    /// for a variant they must reject anyway, and would touch the code paths
    /// where a wrong answer costs the most.
    ///
    /// Usually empty. A series carries floats or histograms, not both — a
    /// metric that changed type mid-range is the one case where both are
    /// populated, and the functions that meet it say so rather than mixing
    /// them.
    pub histograms: Vec<HistogramSample>,
}

/// One native-histogram observation in a series.
#[derive(Debug, Clone, PartialEq)]
pub struct HistogramSample {
    /// Timestamp in nanoseconds.
    pub timestamp: i64,
    /// The distribution observed at that instant.
    ///
    /// Boxed: a `Series` holds a vector of these, and a histogram carries
    /// three `Vec`s of its own.
    pub histogram: Box<chronix_core::histogram::Histogram>,
}

impl Series {
    /// A series of float samples — the ordinary case.
    #[must_use]
    pub fn floats(labels: Vec<(String, String)>, samples: Vec<Sample>) -> Self {
        Self {
            labels,
            samples,
            histograms: Vec::new(),
        }
    }

    /// A series of histogram samples.
    #[must_use]
    pub fn histograms(labels: Vec<(String, String)>, histograms: Vec<HistogramSample>) -> Self {
        Self {
            labels,
            samples: Vec::new(),
            histograms,
        }
    }

    /// Whether this series carries histogram samples rather than floats.
    #[must_use]
    pub fn is_histogram(&self) -> bool {
        !self.histograms.is_empty()
    }
}

/// The result of a `PromQL` evaluation.
#[derive(Debug, Clone, PartialEq)]
pub enum PromQLValue {
    /// An instant vector: one sample per series.
    Vector(Vec<Series>),
    /// A range vector / matrix: multiple samples per series.
    Matrix(Vec<Series>),
    /// A scalar value.
    Scalar(f64),
    /// A string value.
    String(String),
}