Skip to main content

keel_core_api/
policy.rs

1//! Typed policy model: `keel.toml` (in its JSON form) deserialized straight
2//! into structs. Validation *is* the type system — `NonZero*` integers make
3//! zero counts unrepresentable, newtypes parse duration/rate/schedule
4//! literals in their `Deserialize` impls, and retry conditions are a closed
5//! enum. A document that deserializes is a valid policy; anything else is
6//! `KEEL-E001` with a precise field path (via `serde_path_to_error`).
7
8use core::fmt;
9use core::num::{NonZeroU32, NonZeroU64};
10use core::str::FromStr;
11use std::collections::BTreeMap;
12
13use crate::ErrorClass;
14use serde::Deserialize;
15
16/// A literal that failed to parse; surfaces through serde as the
17/// deserialization error message for the offending field.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ParseError {
20    what: &'static str,
21    input: String,
22    /// For literals that are grammatical but invalid (e.g. a schedule
23    /// composition whose segments can never all be reached): the reason,
24    /// appended so the KEEL-E001 first line says what to fix.
25    note: Option<&'static str>,
26}
27
28impl ParseError {
29    fn new(what: &'static str, input: &str) -> Self {
30        Self {
31            what,
32            input: input.to_owned(),
33            note: None,
34        }
35    }
36
37    fn with_note(what: &'static str, input: &str, note: &'static str) -> Self {
38        Self {
39            what,
40            input: input.to_owned(),
41            note: Some(note),
42        }
43    }
44}
45
46impl fmt::Display for ParseError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self.note {
49            None => write!(f, "unparseable {} literal: {:?}", self.what, self.input),
50            Some(note) => write!(
51                f,
52                "invalid {} literal: {:?} — {note}",
53                self.what, self.input
54            ),
55        }
56    }
57}
58
59impl core::error::Error for ParseError {}
60
61/// A duration literal: `200ms`, `30s`, `5m`, `2h`.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
63#[serde(try_from = "String")]
64pub struct DurationMs(pub u64);
65
66impl FromStr for DurationMs {
67    type Err = ParseError;
68
69    fn from_str(s: &str) -> Result<Self, Self::Err> {
70        let err = || ParseError::new("duration", s);
71        let s = s.trim();
72        let unit_at = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(err)?;
73        let (number, unit) = s.split_at(unit_at);
74        let n: u64 = number.parse().map_err(|_| err())?;
75        let mult = match unit {
76            "ms" => 1,
77            "s" => 1_000,
78            "m" => 60_000,
79            "h" => 3_600_000,
80            _ => return Err(err()),
81        };
82        Ok(Self(n * mult))
83    }
84}
85
86impl TryFrom<String> for DurationMs {
87    type Error = ParseError;
88
89    fn try_from(s: String) -> Result<Self, Self::Error> {
90        s.parse()
91    }
92}
93
94/// A rate literal: `90/s`, `60/min`, `10/h`. A zero limit is unrepresentable.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
96#[serde(try_from = "String")]
97pub struct Rate {
98    pub limit: NonZeroU64,
99    pub window_ms: u64,
100}
101
102impl FromStr for Rate {
103    type Err = ParseError;
104
105    fn from_str(s: &str) -> Result<Self, Self::Err> {
106        let err = || ParseError::new("rate", s);
107        let (limit, window) = s.trim().split_once('/').ok_or_else(err)?;
108        let limit: NonZeroU64 = limit.trim().parse().map_err(|_| err())?;
109        let window_ms = match window.trim() {
110            "s" | "sec" => 1_000,
111            "min" => 60_000,
112            "h" | "hour" => 3_600_000,
113            _ => return Err(err()),
114        };
115        Ok(Self { limit, window_ms })
116    }
117}
118
119impl TryFrom<String> for Rate {
120    type Error = ParseError;
121
122    fn try_from(s: String) -> Result<Self, Self::Error> {
123        s.parse()
124    }
125}
126
127/// A retry schedule per contracts/schedule-grammar.ebnf — the full algebra:
128/// one or more `andThen`-separated segments, each an `exp`/`fixed` primary
129/// with an optional cumulative-wait bound (`upTo`). Semantics are pinned
130/// normatively in conformance/README.md ("Schedule algebra"): `upTo` bounds
131/// the segment's cumulative *natural* wait and hands off to the next segment;
132/// every segment except the last must be bounded and the last never is (both
133/// degenerate shapes are configure-time `KEEL-E001`), so a schedule is always
134/// a total mapping attempt → wait.
135#[derive(Debug, Clone, PartialEq, Deserialize)]
136#[serde(try_from = "String")]
137pub struct Schedule {
138    /// Non-empty; the parser enforces `up_to_ms.is_some()` on every segment
139    /// except the last and `None` on the last.
140    pub segments: Vec<ScheduleSegment>,
141}
142
143/// One `andThen` segment: a primary plus its optional `upTo` bound.
144#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct ScheduleSegment {
146    pub primary: SchedulePrimary,
147    /// `upTo` bound on this segment's cumulative natural wait, in ms.
148    pub up_to_ms: Option<u64>,
149}
150
151/// A schedule primary (`exp` / `fixed`) from the frozen grammar.
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub enum SchedulePrimary {
154    Exp {
155        base_ms: u64,
156        factor: f64,
157        cap_ms: u64,
158        jitter: bool,
159    },
160    Fixed {
161        period_ms: u64,
162    },
163}
164
165impl SchedulePrimary {
166    /// Deterministic natural wait at local attempt `a` (1-based):
167    /// `min(base * factor^(a-1), cap)`, before any jitter.
168    #[expect(
169        clippy::cast_precision_loss,
170        clippy::cast_possible_truncation,
171        clippy::cast_sign_loss,
172        clippy::cast_possible_wrap,
173        reason = "backoff arithmetic: values are small and non-negative by construction"
174    )]
175    fn wait_ms(self, attempt: u32) -> u64 {
176        match self {
177            Self::Exp {
178                base_ms,
179                factor,
180                cap_ms,
181                ..
182            } => {
183                let wait = base_ms as f64 * factor.powi(attempt as i32 - 1);
184                wait.min(cap_ms as f64).round() as u64
185            }
186            Self::Fixed { period_ms } => period_ms,
187        }
188    }
189
190    fn jitter(self) -> bool {
191        matches!(self, Self::Exp { jitter: true, .. })
192    }
193}
194
195impl Default for Schedule {
196    /// The contract default: `exp(200ms, x2, max 30s, jitter)`.
197    fn default() -> Self {
198        Self {
199            segments: vec![ScheduleSegment {
200                primary: SchedulePrimary::Exp {
201                    base_ms: 200,
202                    factor: 2.0,
203                    cap_ms: 30_000,
204                    jitter: true,
205                },
206                up_to_ms: None,
207            }],
208        }
209    }
210}
211
212impl Schedule {
213    /// Deterministic wait after failed attempt `n` (1-based), before any
214    /// jitter or `Retry-After` override.
215    #[must_use]
216    pub fn wait_ms(&self, attempt: u32) -> u64 {
217        self.wait_and_jitter(attempt).0
218    }
219
220    /// `(wait, jitter?)` for retry attempt `n` — a pure function of `n`, per
221    /// the normative walk in conformance/README.md ("Schedule algebra"):
222    /// segments hand off when the next natural wait would push the segment's
223    /// cumulative emitted total past its `upTo` bound (an exact fit stays;
224    /// handoffs cascade past segments whose bound is below their first wait),
225    /// and each segment restarts at local attempt 1 on entry. The jitter flag
226    /// is the emitting segment's — the stubs ignore it (virtual clocks); the
227    /// real core samples equal jitter, uniform in `[w/2, w]`.
228    ///
229    /// # Panics
230    /// If `segments` is empty (unrepresentable via the parser).
231    #[must_use]
232    pub fn wait_and_jitter(&self, attempt: u32) -> (u64, bool) {
233        let attempt = attempt.max(1);
234        let last = self.segments.len() - 1;
235        let (mut i, mut a, mut e) = (0_usize, 1_u32, 0_u64);
236        let mut emitted = 0_u32;
237        loop {
238            let segment = self.segments[i];
239            let wait = segment.primary.wait_ms(a);
240            // A bound on the final segment is unrepresentable via the parser;
241            // `i < last` keeps hand-constructed values total anyway.
242            if i < last
243                && let Some(bound) = segment.up_to_ms
244                && e.saturating_add(wait) > bound
245            {
246                (i, a, e) = (i + 1, 1, 0);
247                continue;
248            }
249            emitted += 1;
250            if emitted == attempt {
251                return (wait, segment.primary.jitter());
252            }
253            a += 1;
254            e = e.saturating_add(wait);
255        }
256    }
257}
258
259impl FromStr for SchedulePrimary {
260    type Err = ParseError;
261
262    fn from_str(s: &str) -> Result<Self, Self::Err> {
263        let err = || ParseError::new("schedule", s);
264        let s = s.trim();
265        if let Some(inner) = s.strip_prefix("exp(").and_then(|r| r.strip_suffix(')')) {
266            let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
267            let [base, factor, rest @ ..] = parts.as_slice() else {
268                return Err(err());
269            };
270            let base_ms = base.parse::<DurationMs>().map_err(|_| err())?.0;
271            let factor: f64 = factor
272                .strip_prefix('x')
273                .ok_or_else(err)?
274                .parse()
275                .map_err(|_| err())?;
276            let mut cap_ms = u64::MAX;
277            let mut jitter = false;
278            for part in rest {
279                if let Some(d) = part.strip_prefix("max ") {
280                    cap_ms = d.parse::<DurationMs>().map_err(|_| err())?.0;
281                } else if *part == "jitter" {
282                    jitter = true;
283                } else {
284                    return Err(err());
285                }
286            }
287            Ok(Self::Exp {
288                base_ms,
289                factor,
290                cap_ms,
291                jitter,
292            })
293        } else if let Some(inner) = s.strip_prefix("fixed(").and_then(|r| r.strip_suffix(')')) {
294            let period_ms = inner.parse::<DurationMs>().map_err(|_| err())?.0;
295            Ok(Self::Fixed { period_ms })
296        } else {
297            Err(err())
298        }
299    }
300}
301
302impl FromStr for Schedule {
303    type Err = ParseError;
304
305    fn from_str(s: &str) -> Result<Self, Self::Err> {
306        let err = || ParseError::new("schedule", s);
307        // The grammar's `ws` makes `upTo` / `andThen` space-separated tokens;
308        // tokenizing on whitespace runs and rejoining a primary's tokens with
309        // single spaces is lossless for the primary parsers (they trim around
310        // commas). Keywords never occur inside `exp(…)`/`fixed(…)` in a valid
311        // literal, so no paren tracking is needed — misplaced keywords make
312        // the primary unparseable, which is the same KEEL-E001.
313        let tokens: Vec<&str> = s.split_whitespace().collect();
314        if tokens.is_empty() {
315            return Err(err());
316        }
317        let mut segments = Vec::new();
318        for segment_tokens in tokens.split(|t| *t == "andThen") {
319            let (primary_tokens, up_to_ms) = match segment_tokens.iter().position(|t| *t == "upTo")
320            {
321                None => (segment_tokens, None),
322                Some(pos) => {
323                    // exactly `upTo <duration>`, at the segment's tail
324                    let [duration] = &segment_tokens[pos + 1..] else {
325                        return Err(err());
326                    };
327                    let bound = duration.parse::<DurationMs>().map_err(|_| err())?.0;
328                    (&segment_tokens[..pos], Some(bound))
329                }
330            };
331            if primary_tokens.is_empty() {
332                return Err(err());
333            }
334            let primary: SchedulePrimary = primary_tokens.join(" ").parse().map_err(|_| err())?;
335            segments.push(ScheduleSegment { primary, up_to_ms });
336        }
337        // Shape rule (normative, conformance/README.md "Schedule algebra"):
338        // bounded exactly on the non-final segments, so every segment is
339        // reachable and every attempt has a wait.
340        let last = segments.len() - 1;
341        if segments
342            .iter()
343            .enumerate()
344            .any(|(i, segment)| (i < last) != segment.up_to_ms.is_some())
345        {
346            return Err(ParseError::with_note(
347                "schedule",
348                s,
349                "`upTo` must bound every segment except the last, and never the last \
350                 (an unbounded segment never hands off; a bounded tail would leave \
351                 attempts without a wait — cap total retrying with `attempts`)",
352            ));
353        }
354        Ok(Self { segments })
355    }
356}
357
358impl TryFrom<String> for Schedule {
359    type Error = ParseError;
360
361    fn try_from(s: String) -> Result<Self, Self::Error> {
362        s.parse()
363    }
364}
365
366/// One retryable-error condition from `retry.on` (closed set; unknown
367/// conditions fail configuration instead of silently never matching).
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
369#[serde(try_from = "String")]
370pub enum Condition {
371    Conn,
372    Timeout,
373    Cancelled,
374    Other,
375    Class4xx,
376    Class5xx,
377    Status(u16),
378}
379
380impl Condition {
381    pub fn matches(self, class: ErrorClass, http_status: Option<u16>) -> bool {
382        match self {
383            Self::Conn => class == ErrorClass::Conn,
384            Self::Timeout => class == ErrorClass::Timeout,
385            Self::Cancelled => class == ErrorClass::Cancelled,
386            Self::Other => class == ErrorClass::Other,
387            Self::Class4xx => {
388                class == ErrorClass::Http && http_status.is_some_and(|s| (400..=499).contains(&s))
389            }
390            Self::Class5xx => {
391                class == ErrorClass::Http && http_status.is_some_and(|s| (500..=599).contains(&s))
392            }
393            Self::Status(want) => class == ErrorClass::Http && http_status == Some(want),
394        }
395    }
396}
397
398impl FromStr for Condition {
399    type Err = ParseError;
400
401    fn from_str(s: &str) -> Result<Self, Self::Err> {
402        match s {
403            "conn" => Ok(Self::Conn),
404            "timeout" => Ok(Self::Timeout),
405            "cancelled" => Ok(Self::Cancelled),
406            "other" => Ok(Self::Other),
407            "4xx" => Ok(Self::Class4xx),
408            "5xx" => Ok(Self::Class5xx),
409            // Frozen schema errorCondition grammar is `[1-5][0-9][0-9]` (100–599):
410            // require three ASCII digits in range, not any 3-char u16 (which
411            // accepted `099`→99 and `999`, outside the contract).
412            exact if exact.len() == 3 && exact.bytes().all(|b| b.is_ascii_digit()) => {
413                let code: u16 = exact
414                    .parse()
415                    .map_err(|_| ParseError::new("retry condition", s))?;
416                if (100..=599).contains(&code) {
417                    Ok(Self::Status(code))
418                } else {
419                    Err(ParseError::new("retry condition", s))
420                }
421            }
422            _ => Err(ParseError::new("retry condition", s)),
423        }
424    }
425}
426
427impl TryFrom<String> for Condition {
428    type Error = ParseError;
429
430    fn try_from(s: String) -> Result<Self, Self::Error> {
431        s.parse()
432    }
433}
434
435/// `retry = { attempts, schedule, on }`. `attempts` is the TOTAL attempt
436/// budget (first call included) — zero is unrepresentable by type.
437#[derive(Debug, Clone, PartialEq, Deserialize)]
438#[serde(default, deny_unknown_fields)]
439pub struct RetryPolicy {
440    pub attempts: NonZeroU32,
441    pub schedule: Schedule,
442    pub on: Vec<Condition>,
443}
444
445impl RetryPolicy {
446    pub const DEFAULT_ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).unwrap();
447
448    /// The contract default retryable set: `["conn", "timeout", "429", "5xx"]`.
449    pub fn default_on() -> Vec<Condition> {
450        vec![
451            Condition::Conn,
452            Condition::Timeout,
453            Condition::Status(429),
454            Condition::Class5xx,
455        ]
456    }
457
458    pub fn is_retryable(&self, class: ErrorClass, http_status: Option<u16>) -> bool {
459        self.on.iter().any(|c| c.matches(class, http_status))
460    }
461}
462
463impl Default for RetryPolicy {
464    fn default() -> Self {
465        Self {
466            attempts: Self::DEFAULT_ATTEMPTS,
467            schedule: Schedule::default(),
468            on: Self::default_on(),
469        }
470    }
471}
472
473/// `breaker = { failures, cooldown, window, failure_rate, min_calls }`.
474///
475/// Two modes per the frozen schema (`$defs/breaker`), enforced identically by
476/// the real core and every stub — normative rules in `conformance/README.md`:
477/// - **count mode**: selected when `failures` is set (or no rate knob is set;
478///   `failures` then defaults to 5) — `failures` consecutive terminal failures
479///   open the breaker.
480/// - **rate mode**: selected when `failures` is absent and both `window` and
481///   `failure_rate` are set — trips when the trailing `window` holds at least
482///   `min_calls` outcomes (default 10) with `failed/total >= failure_rate`.
483///
484/// A rate-mode knob without both `window` and `failure_rate` (and without
485/// `failures`) is rejected at deserialize time (KEEL-E001): a half-configured
486/// mode must fail loudly, never silently degrade to count-mode defaults.
487#[derive(Debug, Clone, PartialEq, Deserialize)]
488#[serde(try_from = "BreakerPolicyDe")]
489pub struct BreakerPolicy {
490    /// Count-mode threshold. `None` means "not set by the user" — see
491    /// [`BreakerPolicy::mode`] for how that selects the mode.
492    pub failures: Option<NonZeroU64>,
493    pub cooldown: DurationMs,
494    pub window: Option<DurationMs>,
495    pub failure_rate: Option<f64>,
496    pub min_calls: Option<NonZeroU32>,
497}
498
499/// The breaker mode a [`BreakerPolicy`] resolves to, with every default
500/// applied — the engine/stubs consume this, never the raw knobs.
501#[derive(Debug, Clone, Copy, PartialEq)]
502pub enum BreakerMode {
503    /// `failures` consecutive terminal failures open the breaker.
504    Count { failures: NonZeroU64 },
505    /// Failure-rate tripping over a sliding window of post-retry outcomes.
506    Rate {
507        window: DurationMs,
508        failure_rate: f64,
509        min_calls: NonZeroU32,
510    },
511}
512
513impl BreakerPolicy {
514    /// Schema default for count mode's `failures`.
515    pub const DEFAULT_FAILURES: NonZeroU64 = NonZeroU64::new(5).unwrap();
516    /// Schema default for rate mode's `min_calls`.
517    pub const DEFAULT_MIN_CALLS: NonZeroU32 = NonZeroU32::new(10).unwrap();
518
519    /// The mode this policy selects (schema: "Setting `failures` selects count
520    /// mode"), with defaults applied. Deserialization already rejected
521    /// half-configured rate mode, so `window`+`failure_rate` are either both
522    /// present or irrelevant here.
523    #[must_use]
524    pub fn mode(&self) -> BreakerMode {
525        match (self.failures, self.window, self.failure_rate) {
526            (None, Some(window), Some(failure_rate)) => BreakerMode::Rate {
527                window,
528                failure_rate,
529                min_calls: self.min_calls.unwrap_or(Self::DEFAULT_MIN_CALLS),
530            },
531            (failures, _, _) => BreakerMode::Count {
532                failures: failures.unwrap_or(Self::DEFAULT_FAILURES),
533            },
534        }
535    }
536
537    /// Whether count mode was selected *while* rate-mode knobs are present —
538    /// those knobs are inert (the schema's precedence), which callers may want
539    /// to surface loudly rather than leave silent.
540    #[must_use]
541    pub fn has_inert_rate_knobs(&self) -> bool {
542        self.failures.is_some()
543            && (self.window.is_some() || self.failure_rate.is_some() || self.min_calls.is_some())
544    }
545}
546
547/// The raw deserialized shape of `breaker`, before mode-completeness
548/// validation promotes it to [`BreakerPolicy`].
549#[derive(Deserialize)]
550#[serde(default, deny_unknown_fields)]
551struct BreakerPolicyDe {
552    failures: Option<NonZeroU64>,
553    cooldown: DurationMs,
554    window: Option<DurationMs>,
555    #[serde(deserialize_with = "de_failure_rate")]
556    failure_rate: Option<f64>,
557    min_calls: Option<NonZeroU32>,
558}
559
560impl Default for BreakerPolicyDe {
561    fn default() -> Self {
562        Self {
563            failures: None,
564            cooldown: DurationMs(15_000),
565            window: None,
566            failure_rate: None,
567            min_calls: None,
568        }
569    }
570}
571
572impl TryFrom<BreakerPolicyDe> for BreakerPolicy {
573    type Error = String;
574
575    fn try_from(de: BreakerPolicyDe) -> Result<Self, Self::Error> {
576        let rate_pair = de.window.is_some() && de.failure_rate.is_some();
577        let any_rate_knob =
578            de.window.is_some() || de.failure_rate.is_some() || de.min_calls.is_some();
579        if de.failures.is_none() && any_rate_knob && !rate_pair {
580            return Err(String::from(
581                "breaker rate mode requires both `window` and `failure_rate` \
582                 (count mode sets `failures` instead)",
583            ));
584        }
585        Ok(Self {
586            failures: de.failures,
587            cooldown: de.cooldown,
588            window: de.window,
589            failure_rate: de.failure_rate,
590            min_calls: de.min_calls,
591        })
592    }
593}
594
595/// Validate `breaker.failure_rate` against the frozen schema range
596/// (`exclusiveMinimum: 0, maximum: 1`) at deserialize time, so an out-of-range or
597/// NaN value fails configuration with a precise field path (`KEEL-E001`) instead
598/// of being silently accepted — the bare `f64` used to take any value.
599fn de_failure_rate<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
600where
601    D: serde::Deserializer<'de>,
602{
603    let value = Option::<f64>::deserialize(deserializer)?;
604    if let Some(rate) = value
605        && !(rate > 0.0 && rate <= 1.0)
606    {
607        return Err(serde::de::Error::custom(format!(
608            "breaker.failure_rate must be greater than 0 and at most 1 (got {rate})"
609        )));
610    }
611    Ok(value)
612}
613
614impl Default for BreakerPolicy {
615    fn default() -> Self {
616        Self {
617            failures: None,
618            cooldown: DurationMs(15_000),
619            window: None,
620            failure_rate: None,
621            min_calls: None,
622        }
623    }
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
627#[serde(rename_all = "snake_case")]
628pub enum CacheScope {
629    #[default]
630    Memory,
631    Persistent,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
635#[serde(rename_all = "snake_case")]
636pub enum CacheMode {
637    #[default]
638    Always,
639    /// Caches only when `KEEL_ENV != prod` — the LLM dev-loop cache.
640    Dev,
641}
642
643#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
644#[serde(rename_all = "snake_case")]
645pub enum CacheKeySource {
646    #[default]
647    Args,
648    Url,
649}
650
651/// `cache = { ttl, scope, mode, key }`. Caching activates only with a `ttl`.
652#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
653#[serde(default, deny_unknown_fields)]
654pub struct CachePolicy {
655    pub ttl: Option<DurationMs>,
656    pub scope: CacheScope,
657    pub mode: CacheMode,
658    pub key: CacheKeySource,
659}
660
661/// `idempotency = { header }` — the header is required by the schema.
662#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
663#[serde(deny_unknown_fields)]
664pub struct IdempotencyPolicy {
665    pub header: String,
666}
667
668/// One target's policy table. Every layer is optional; a layer set at a more
669/// specific level replaces the whole layer table (no deep merge).
670#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
671#[serde(default, deny_unknown_fields)]
672pub struct TargetPolicy {
673    pub timeout: Option<DurationMs>,
674    pub retry: Option<RetryPolicy>,
675    pub breaker: Option<BreakerPolicy>,
676    pub rate: Option<Rate>,
677    pub cache: Option<CachePolicy>,
678    pub idempotency: Option<IdempotencyPolicy>,
679    pub fallback: Option<Vec<String>>,
680    pub budget: Option<String>,
681}
682
683#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
684#[serde(default, deny_unknown_fields)]
685pub struct Defaults {
686    pub outbound: Option<TargetPolicy>,
687    pub llm: Option<TargetPolicy>,
688}
689
690#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
691#[serde(rename_all = "snake_case")]
692pub enum NondeterminismResponse {
693    #[default]
694    Fail,
695    Warn,
696    Branch,
697}
698
699/// Tier 2 flow designation — parsed and carried, enforced by the real core.
700#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
701#[serde(default, deny_unknown_fields)]
702pub struct FlowsPolicy {
703    pub entrypoints: Vec<String>,
704    pub on_nondeterminism: NondeterminismResponse,
705}
706
707/// A journal location literal (`policy.journal`), validated against the frozen
708/// schema pattern `^(file:.+|postgres://.+)$` at parse time so a malformed value
709/// fails configuration (KEEL-E001) rather than being silently ignored. The real
710/// core honors it at configure time: `file:` attaches a SQLite journal at that
711/// path (replacing the construction-time default), and `postgres://` fails
712/// loudly with KEEL-E005 until a Postgres backend ships.
713#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
714#[serde(try_from = "String")]
715pub struct JournalLocation(pub String);
716
717impl FromStr for JournalLocation {
718    type Err = ParseError;
719
720    fn from_str(s: &str) -> Result<Self, Self::Err> {
721        let valid = s.strip_prefix("file:").is_some_and(|rest| !rest.is_empty())
722            || s.strip_prefix("postgres://")
723                .is_some_and(|rest| !rest.is_empty());
724        if valid {
725            Ok(Self(s.to_owned()))
726        } else {
727            Err(ParseError::new("journal location", s))
728        }
729    }
730}
731
732impl TryFrom<String> for JournalLocation {
733    type Error = ParseError;
734
735    fn try_from(s: String) -> Result<Self, Self::Error> {
736        s.parse()
737    }
738}
739
740/// `[telemetry]` (`otlp_endpoint`, `console`). Parsed and carried; `Engine`
741/// exposes `otlp_endpoint` back to native front ends (`telemetry_otlp_endpoint`)
742/// which feed it to `keel-core`'s `otel::init_otlp` when built with the `otel`
743/// feature — the standard `OTEL_*` environment variables take precedence over
744/// this table (see `keel-core`'s otel module for the exact precedence rules).
745/// `console` (the local pretty-console-summary switch) is validated and
746/// carried but has no consumer yet; `Engine::configure` warns on an explicit
747/// `false` so the user is not silently surprised.
748#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
749#[serde(default, deny_unknown_fields)]
750pub struct TelemetryPolicy {
751    pub otlp_endpoint: Option<String>,
752    pub console: bool,
753}
754
755impl Default for TelemetryPolicy {
756    fn default() -> Self {
757        // Schema default: console = true.
758        Self {
759            otlp_endpoint: None,
760            console: true,
761        }
762    }
763}
764
765/// The whole `keel.toml` document (contracts/policy.schema.json), typed.
766///
767/// `deny_unknown_fields` at every object level (here and on the layer structs)
768/// makes a typo'd or unknown key a configuration error (KEEL-E001 with the exact
769/// path via `serde_path_to_error`), honoring the frozen schema's
770/// `additionalProperties: false` and E001's "an unknown key was used" — instead
771/// of the previous silent drop that ran the target on defaults the user never
772/// asked for.
773#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
774#[serde(default, deny_unknown_fields)]
775pub struct Policy {
776    pub defaults: Defaults,
777    pub target: BTreeMap<String, TargetPolicy>,
778    pub flows: Option<FlowsPolicy>,
779    /// Journal location (schema-validated), honored by the real core at
780    /// configure time (see [`JournalLocation`]).
781    pub journal: Option<JournalLocation>,
782    /// Telemetry config (schema-validated); `otlp_endpoint` is honored by
783    /// native front ends (env still wins), `console` is not yet wired — see
784    /// [`TelemetryPolicy`].
785    pub telemetry: Option<TelemetryPolicy>,
786}
787
788/// The per-layer config resolved for one target: target entry, else
789/// `defaults.llm` for `llm:*` targets, else `defaults.outbound`.
790#[derive(Debug, Clone, Default)]
791pub struct ResolvedPolicy {
792    pub timeout: Option<DurationMs>,
793    pub retry: Option<RetryPolicy>,
794    pub breaker: Option<BreakerPolicy>,
795    pub rate: Option<Rate>,
796    pub cache: Option<CachePolicy>,
797    /// `idempotency = { header }` — the knob adapters consult to *inject* a
798    /// minted idempotency key on unsafe-method calls (and to recognize a
799    /// caller-supplied one). The core itself never injects; injection lives in
800    /// the adapter per contracts/adapter-pack.md ("Idempotency-key injection").
801    pub idempotency: Option<IdempotencyPolicy>,
802}
803
804impl Policy {
805    pub fn resolve(&self, target: &str) -> ResolvedPolicy {
806        ResolvedPolicy {
807            timeout: self.layer(target, |t| t.timeout.as_ref()).copied(),
808            retry: self.layer(target, |t| t.retry.as_ref()).cloned(),
809            breaker: self.layer(target, |t| t.breaker.as_ref()).cloned(),
810            rate: self.layer(target, |t| t.rate.as_ref()).copied(),
811            cache: self.layer(target, |t| t.cache.as_ref()).cloned(),
812            idempotency: self.layer(target, |t| t.idempotency.as_ref()).cloned(),
813        }
814    }
815
816    fn layer<'a, T>(
817        &'a self,
818        target: &str,
819        pick: impl Fn(&'a TargetPolicy) -> Option<&'a T>,
820    ) -> Option<&'a T> {
821        if let Some(t) = self.target.get(target)
822            && let Some(v) = pick(t)
823        {
824            return Some(v);
825        }
826        if target.starts_with("llm:")
827            && let Some(llm) = self.defaults.llm.as_ref()
828            && let Some(v) = pick(llm)
829        {
830            return Some(v);
831        }
832        self.defaults.outbound.as_ref().and_then(pick)
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839    use serde_json::json;
840
841    #[test]
842    fn duration_literals() {
843        assert_eq!("200ms".parse(), Ok(DurationMs(200)));
844        assert_eq!("30s".parse(), Ok(DurationMs(30_000)));
845        assert_eq!("5m".parse(), Ok(DurationMs(300_000)));
846        assert_eq!("2h".parse(), Ok(DurationMs(7_200_000)));
847        assert!("30".parse::<DurationMs>().is_err());
848        assert!("30sec".parse::<DurationMs>().is_err());
849        assert!("-1s".parse::<DurationMs>().is_err());
850    }
851
852    #[test]
853    fn rate_literals() {
854        let rate: Rate = "90/s".parse().unwrap();
855        assert_eq!((rate.limit.get(), rate.window_ms), (90, 1_000));
856        let rate: Rate = "60/min".parse().unwrap();
857        assert_eq!((rate.limit.get(), rate.window_ms), (60, 60_000));
858        assert!("0/s".parse::<Rate>().is_err(), "zero limit unrepresentable");
859        assert!("10/day".parse::<Rate>().is_err());
860    }
861
862    #[test]
863    fn schedule_exp_waits_and_cap() {
864        let schedule: Schedule = "exp(1s, x2, max 4s)".parse().unwrap();
865        let waits: Vec<u64> = (1..=4).map(|n| schedule.wait_ms(n)).collect();
866        assert_eq!(waits, [1_000, 2_000, 4_000, 4_000]);
867    }
868
869    #[test]
870    fn schedule_fixed_and_rejections() {
871        assert_eq!(
872            "fixed(1s)".parse::<Schedule>(),
873            Ok(Schedule {
874                segments: vec![ScheduleSegment {
875                    primary: SchedulePrimary::Fixed { period_ms: 1_000 },
876                    up_to_ms: None,
877                }],
878            })
879        );
880        assert!("linear(1s)".parse::<Schedule>().is_err());
881    }
882
883    #[test]
884    fn schedule_composition_parses_the_spec_example() {
885        // architecture-spec §4.1 / the frozen grammar's own example
886        let schedule: Schedule = "exp(1s, x2, max 5m) upTo 10m andThen fixed(1m)"
887            .parse()
888            .unwrap();
889        assert_eq!(
890            schedule.segments,
891            vec![
892                ScheduleSegment {
893                    primary: SchedulePrimary::Exp {
894                        base_ms: 1_000,
895                        factor: 2.0,
896                        cap_ms: 300_000,
897                        jitter: false,
898                    },
899                    up_to_ms: Some(600_000),
900                },
901                ScheduleSegment {
902                    primary: SchedulePrimary::Fixed { period_ms: 60_000 },
903                    up_to_ms: None,
904                },
905            ]
906        );
907        // The grammar's ws is "one or more spaces": extra spacing still parses.
908        assert_eq!(
909            "exp(1s, x2, max 5m)  upTo  10m  andThen  fixed(1m)".parse::<Schedule>(),
910            Ok(schedule)
911        );
912    }
913
914    #[test]
915    fn schedule_composition_hands_off_when_the_bound_would_be_overshot() {
916        let schedule: Schedule = "exp(1s, x2) upTo 4s andThen fixed(500ms)".parse().unwrap();
917        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
918        // 1s + 2s = 3s fits; the natural 4s would overshoot the 4s bound.
919        assert_eq!(waits, [1_000, 2_000, 500, 500, 500]);
920    }
921
922    #[test]
923    fn schedule_composition_exact_fit_stays_and_cascade_skips() {
924        let schedule: Schedule =
925            "fixed(1s) upTo 3s andThen fixed(10s) upTo 5s andThen fixed(250ms)"
926                .parse()
927                .unwrap();
928        let waits: Vec<u64> = (1..=6).map(|n| schedule.wait_ms(n)).collect();
929        // Three 1s waits fill upTo 3s exactly (e + w == bound stays); the 10s
930        // segment's first wait exceeds its own 5s bound, so it contributes
931        // zero waits and the handoff cascades to the 250ms tail.
932        assert_eq!(waits, [1_000, 1_000, 1_000, 250, 250, 250]);
933    }
934
935    #[test]
936    fn schedule_composition_restarts_exp_and_tracks_jitter_per_segment() {
937        let schedule: Schedule = "fixed(1s) upTo 2s andThen exp(100ms, x3, jitter)"
938            .parse()
939            .unwrap();
940        // exp restarts at local attempt 1 after the handoff.
941        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
942        assert_eq!(waits, [1_000, 1_000, 100, 300, 900]);
943        // jitter is the emitting segment's flag, not schedule-global.
944        assert_eq!(schedule.wait_and_jitter(1), (1_000, false));
945        assert_eq!(schedule.wait_and_jitter(3), (100, true));
946    }
947
948    #[test]
949    fn schedule_composition_shape_rule_rejections() {
950        // Grammatical but invalid shapes fail configure-time (KEEL-E001), per
951        // conformance/README.md "Schedule algebra": a non-final segment
952        // without upTo never hands off; a bounded final segment would leave
953        // attempts without a wait.
954        for degenerate in [
955            "fixed(1s) andThen fixed(2s)",
956            "exp(1s, x2, max 5m) upTo 10m",
957            "fixed(1s) upTo 3s andThen fixed(2s) andThen fixed(4s)",
958            "fixed(1s) upTo 3s andThen fixed(2s) upTo 5s",
959        ] {
960            let error = degenerate.parse::<Schedule>().unwrap_err();
961            assert!(
962                error.to_string().contains("upTo"),
963                "{degenerate}: expected the shape-rule note, got {error}"
964            );
965        }
966        // Broken composition syntax stays a plain parse rejection.
967        for broken in [
968            "fixed(1s) upTo",
969            "upTo 3s andThen fixed(1s)",
970            "fixed(1s) upTo 1s upTo 2s andThen fixed(1s)",
971            "fixed(1s) andThen",
972            "andThen fixed(1s)",
973            "fixed(1s) upTo 3s fixed(2s)",
974        ] {
975            assert!(
976                broken.parse::<Schedule>().is_err(),
977                "{broken} must be rejected"
978            );
979        }
980    }
981
982    #[test]
983    fn condition_matching() {
984        let on = RetryPolicy::default_on();
985        let matches = |class, status| on.iter().any(|c| c.matches(class, status));
986        assert!(matches(ErrorClass::Conn, None));
987        assert!(matches(ErrorClass::Http, Some(429)));
988        assert!(matches(ErrorClass::Http, Some(503)));
989        assert!(!matches(ErrorClass::Http, Some(400)));
990        assert!(!matches(ErrorClass::Cancelled, None));
991        assert!("teapot".parse::<Condition>().is_err());
992        // Exact-status literals follow the frozen schema grammar [1-5][0-9][0-9].
993        assert_eq!("429".parse::<Condition>(), Ok(Condition::Status(429)));
994        assert_eq!("100".parse::<Condition>(), Ok(Condition::Status(100)));
995        assert_eq!("599".parse::<Condition>(), Ok(Condition::Status(599)));
996        for bad in ["999", "099", "600", "000", "12", "1234", "1x9"] {
997            assert!(bad.parse::<Condition>().is_err(), "{bad} must be rejected");
998        }
999    }
1000
1001    #[test]
1002    fn zero_attempts_is_unrepresentable() {
1003        let doc = json!({ "target": { "x": { "retry": { "attempts": 0 } } } });
1004        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1005        assert_eq!(err.path().to_string(), "target.x.retry.attempts");
1006    }
1007
1008    #[test]
1009    fn breaker_failure_rate_range_is_enforced() {
1010        // Frozen schema: breaker.failure_rate is exclusiveMinimum 0, maximum 1.
1011        let bad = |rate: serde_json::Value| {
1012            let doc = json!({ "target": { "x": { "breaker": { "failure_rate": rate } } } });
1013            serde_path_to_error::deserialize::<_, Policy>(&doc)
1014        };
1015        for rate in [json!(0.0), json!(-0.1), json!(1.5), json!(2.0)] {
1016            let err = bad(rate.clone()).unwrap_err();
1017            assert_eq!(
1018                err.path().to_string(),
1019                "target.x.breaker.failure_rate",
1020                "out-of-range failure_rate {rate} must fail at its path"
1021            );
1022        }
1023        // In-range values (0, 1] deserialize fine (paired with `window`:
1024        // rate mode requires both knobs).
1025        for rate in [0.01_f64, 0.5, 1.0] {
1026            let doc = json!({
1027                "target": { "x": { "breaker": { "window": "30s", "failure_rate": rate } } }
1028            });
1029            let policy = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap();
1030            let breaker = policy.target["x"].breaker.as_ref().unwrap();
1031            assert_eq!(breaker.failure_rate, Some(rate));
1032        }
1033    }
1034
1035    #[test]
1036    fn breaker_mode_selection_follows_the_schema() {
1037        let breaker = |doc: serde_json::Value| -> BreakerPolicy {
1038            let doc = json!({ "target": { "x": { "breaker": doc } } });
1039            let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1040            policy.target["x"].breaker.clone().unwrap()
1041        };
1042
1043        // Empty table: count mode on the schema default (failures = 5).
1044        assert_eq!(
1045            breaker(json!({})).mode(),
1046            BreakerMode::Count {
1047                failures: BreakerPolicy::DEFAULT_FAILURES
1048            }
1049        );
1050
1051        // Both rate knobs, no `failures`: rate mode, min_calls defaults to 10.
1052        assert_eq!(
1053            breaker(json!({ "window": "30s", "failure_rate": 0.5 })).mode(),
1054            BreakerMode::Rate {
1055                window: DurationMs(30_000),
1056                failure_rate: 0.5,
1057                min_calls: BreakerPolicy::DEFAULT_MIN_CALLS,
1058            }
1059        );
1060        assert_eq!(
1061            breaker(json!({ "window": "10s", "failure_rate": 1.0, "min_calls": 4 })).mode(),
1062            BreakerMode::Rate {
1063                window: DurationMs(10_000),
1064                failure_rate: 1.0,
1065                min_calls: NonZeroU32::new(4).unwrap(),
1066            }
1067        );
1068
1069        // "Setting `failures` selects count mode" (frozen schema): rate knobs
1070        // present alongside it are inert, and the policy says so.
1071        let mixed = breaker(json!({ "failures": 3, "window": "30s", "failure_rate": 0.5 }));
1072        assert_eq!(
1073            mixed.mode(),
1074            BreakerMode::Count {
1075                failures: NonZeroU64::new(3).unwrap()
1076            }
1077        );
1078        assert!(mixed.has_inert_rate_knobs());
1079        assert!(!breaker(json!({ "failures": 3 })).has_inert_rate_knobs());
1080    }
1081
1082    #[test]
1083    fn half_configured_breaker_rate_mode_is_rejected() {
1084        // A rate-mode knob without both `window` and `failure_rate` (and
1085        // without `failures`) must fail at configure, not silently run count
1086        // mode the user never asked for.
1087        for doc in [
1088            json!({ "window": "30s" }),
1089            json!({ "failure_rate": 0.5 }),
1090            json!({ "min_calls": 10 }),
1091            json!({ "window": "30s", "min_calls": 10 }),
1092            json!({ "failure_rate": 0.5, "min_calls": 10 }),
1093        ] {
1094            let policy = json!({ "target": { "x": { "breaker": doc } } });
1095            let err = serde_path_to_error::deserialize::<_, Policy>(&policy).unwrap_err();
1096            assert_eq!(err.path().to_string(), "target.x.breaker", "doc: {doc}");
1097            assert!(
1098                err.inner().to_string().contains("rate mode requires both"),
1099                "doc {doc}: got {}",
1100                err.inner()
1101            );
1102        }
1103        // `failures` present makes any knob combination count mode (schema
1104        // precedence), so those documents stay valid.
1105        let policy =
1106            json!({ "target": { "x": { "breaker": { "failures": 3, "window": "30s" } } } });
1107        assert!(serde_path_to_error::deserialize::<_, Policy>(&policy).is_ok());
1108    }
1109
1110    #[test]
1111    fn unknown_key_is_rejected_with_its_path() {
1112        // A typo'd nested key: the frozen schema's additionalProperties:false and
1113        // E001's "an unknown key was used" mean this must fail, not silently run
1114        // on the defaults.
1115        let doc = json!({ "target": { "api.stripe.com": { "retry": { "atempts": 10 } } } });
1116        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1117        assert!(
1118            err.inner().to_string().contains("atempts")
1119                || err.inner().to_string().contains("unknown field"),
1120            "expected an unknown-field error, got {}",
1121            err.inner()
1122        );
1123    }
1124
1125    #[test]
1126    fn unknown_top_level_and_layer_keys_are_rejected() {
1127        assert!(
1128            serde_path_to_error::deserialize::<_, Policy>(&json!({ "bogus_top": true })).is_err()
1129        );
1130        assert!(
1131            serde_path_to_error::deserialize::<_, Policy>(
1132                &json!({ "target": { "api.x": { "retrys": {} } } })
1133            )
1134            .is_err(),
1135            "a mistyped layer table must be rejected, not dropped"
1136        );
1137    }
1138
1139    #[test]
1140    fn journal_and_telemetry_parse_and_validate() {
1141        let doc = json!({
1142            "journal": "file:/srv/keel/journal.db",
1143            "telemetry": { "otlp_endpoint": "http://collector:4317" }
1144        });
1145        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1146        assert_eq!(
1147            policy.journal.unwrap(),
1148            JournalLocation("file:/srv/keel/journal.db".to_owned())
1149        );
1150        let telemetry = policy.telemetry.unwrap();
1151        assert_eq!(
1152            telemetry.otlp_endpoint.as_deref(),
1153            Some("http://collector:4317")
1154        );
1155        assert!(telemetry.console, "schema default console = true");
1156
1157        // A journal string that matches neither `file:` nor `postgres://` fails.
1158        let bad = json!({ "journal": "sqlite:/tmp/x.db" });
1159        assert!(serde_path_to_error::deserialize::<_, Policy>(&bad).is_err());
1160    }
1161
1162    #[test]
1163    fn idempotency_resolves_like_any_other_layer() {
1164        // The `idempotency` layer must surface through `resolve()` so adapters
1165        // (via the front ends) and the engine can honor the injection contract
1166        // (contracts/adapter-pack.md "Idempotency-key injection").
1167        let doc = json!({
1168            "defaults": {
1169                "outbound": { "idempotency": { "header": "X-Idem" } },
1170                "llm": { "idempotency": { "header": "X-Llm-Idem" } }
1171            },
1172            "target": {
1173                "api.stripe.com": { "idempotency": { "header": "Idempotency-Key" } },
1174                "api.plain.example": { "timeout": "1s" }
1175            }
1176        });
1177        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1178
1179        // Exact target entry wins.
1180        let stripe = policy.resolve("api.stripe.com");
1181        assert_eq!(
1182            stripe.idempotency.as_ref().map(|i| i.header.as_str()),
1183            Some("Idempotency-Key")
1184        );
1185        // llm:* falls to defaults.llm, then anything else to defaults.outbound.
1186        let llm = policy.resolve("llm:openai");
1187        assert_eq!(
1188            llm.idempotency.as_ref().map(|i| i.header.as_str()),
1189            Some("X-Llm-Idem")
1190        );
1191        let plain = policy.resolve("api.plain.example");
1192        assert_eq!(
1193            plain.idempotency.as_ref().map(|i| i.header.as_str()),
1194            Some("X-Idem")
1195        );
1196        // No idempotency anywhere: resolves to None.
1197        let empty: Policy = serde_path_to_error::deserialize(&json!({})).unwrap();
1198        assert!(empty.resolve("api.stripe.com").idempotency.is_none());
1199    }
1200
1201    #[test]
1202    fn layer_resolution_precedence() {
1203        let doc = json!({
1204            "defaults": {
1205                "outbound": { "retry": { "attempts": 3 }, "rate": "9/s" },
1206                "llm": { "retry": { "attempts": 6 } }
1207            },
1208            "target": { "llm:openai": { "cache": { "ttl": "10m" } } }
1209        });
1210        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1211
1212        // llm:* target: cache from its own entry, retry from defaults.llm,
1213        // rate falls through to defaults.outbound
1214        let llm = policy.resolve("llm:openai");
1215        assert_eq!(llm.cache.unwrap().ttl, Some(DurationMs(600_000)));
1216        assert_eq!(llm.retry.unwrap().attempts.get(), 6);
1217        assert_eq!(llm.rate.unwrap().limit.get(), 9);
1218
1219        // plain target: everything from defaults.outbound
1220        let plain = policy.resolve("api.example.com");
1221        assert_eq!(plain.retry.unwrap().attempts.get(), 3);
1222        assert!(plain.cache.is_none());
1223    }
1224}