polyc-controller 2026.8.3

Conversation CRD + kube reconciler for the polychrome control plane.
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
//! Translate a standard-cron day-of-week field into [`saffron`]'s own
//! numbering, before any `expression.parse::<saffron::Cron>()` call (#1644).
//!
//! [`saffron`] numbers weekdays `1 = Sunday … 7 = Saturday`
//! (`saffron::parse::DayOfWeek`'s `TryFrom<u8>`). Standard cron — the
//! convention this project's admin-facing contract promises (the
//! `routine_create` tool schema and the `Routine` CRD's
//! `schedule.cron.expression` description both say "standard five-field cron
//! ... day-of-week") — numbers them `0 = Sunday, 1 = Monday … 6 = Saturday`,
//! and also accepts `7` as a second spelling of Sunday. Nothing between the
//! two was translating, so a day-of-week field was silently off by one
//! everywhere it was parsed.
//!
//! [`normalize_cron_dow`] is the ONE place that translates, called at every
//! `saffron::Cron` parse site in this crate
//! ([`crate::routine_reconcile::validate_schedule`]'s admission check and
//! both parse sites in [`crate::routine_next_fire`]) so every one of them
//! agrees on the same standard-cron convention the docs promise.
//!
//! # What gets translated
//!
//! Only numeric day-of-week values — the fifth field's own digits. Three-letter
//! day names (`SUN`/`MON`/…, case-insensitive) parse directly to the correct
//! [`chrono::Weekday`] in `saffron`'s own grammar already (its `dow` parser
//! maps `"MON"` straight to `Weekday::Mon`, bypassing the numeric
//! `TryFrom<u8>` this module works around), so they are left untouched. A
//! step count (the value after a bare `/`, whether following a single day or
//! a range) is a stride, not a day identifier, and is also left untouched.
//!
//! The mapping, applied to every numeric day-value token:
//!
//! | standard | meaning  | saffron |
//! |----------|----------|---------|
//! | `0`      | Sunday   | `1`     |
//! | `1`      | Monday   | `2`     |
//! | `2`      | Tuesday  | `3`     |
//! | `3`      | Wednesday| `4`     |
//! | `4`      | Thursday | `5`     |
//! | `5`      | Friday   | `6`     |
//! | `6`      | Saturday | `7`     |
//! | `7`      | Sunday   | `1`     |
//!
//! This is a monotonic relabeling of the same Sun-through-Sat ordering
//! `saffron` itself uses to decide whether a `start-end` range wraps past
//! Saturday — so a wrapping range (e.g. standard `5-1`, Fri through Mon) still
//! wraps correctly after translation (saffron `6-2`), with no special-casing
//! needed for wrap detection.
//!
//! One shape needs whole-range handling instead of per-endpoint shifting: a
//! bare `0-7` (or `7-0`) range names every day of the week, since `0` and `7`
//! are both Sunday — translating each endpoint separately would collapse it
//! to saffron `1-1` (Sunday only), silently narrowing "every day" to "just
//! Sunday". [`normalize_dow_atom`] special-cases exactly this one degenerate
//! spelling and emits `*` instead.
//!
//! # Untrusted input never panics
//!
//! A `Routine`'s cron expression is an unrestricted `String` at every layer
//! (the CRD schema and the `routine_create` tool schema place no charset or
//! pattern restriction on it), so arbitrary UTF-8 reaches this module from
//! both the admission path and the scheduler path. Every function here
//! either matches on whole atoms, or consumes a token through
//! [`take_day_token`], which only ever slices at a boundary it already
//! proved is safe (an all-ASCII-digit run, or a 3-byte prefix confirmed via
//! `str::get` rather than a raw `s[..3]` index) — so a malformed or
//! multi-byte atom (e.g. one starting with a non-ASCII character) always
//! falls through to "leave this atom unchanged," never a panic. `saffron`'s
//! own parser then rejects whatever this module didn't recognize, exactly as
//! it did before this module existed.
//!
//! # What is NOT handled
//!
//! `saffron`'s day-of-week grammar has two extensions standard cron has no
//! notion of at all: a bare `L` (meaning "the last day of the week" —
//! `saffron` hardcodes this to Saturday) and `D#N` ("the Nth such weekday of
//! the month"). Neither is part of the "standard five-field cron expression"
//! this project's contract promises, so admission never documents them as
//! accepted syntax; this module still normalizes the day value in a `D#N`
//! atom (`D` is a day identifier, so it must translate the same as anywhere
//! else) but passes a bare `L` through unchanged, since it carries no numeric
//! day value to translate.

/// The three-letter day-name tokens `saffron`'s own grammar accepts
/// case-insensitively, in `saffron`'s numeric order (index 0 = Sunday) — used
/// only to recognize a name token so it can be left untouched, never to
/// reassign it a number.
const DAY_NAMES: [&str; 7] = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];

/// Translate one standard-cron day-of-week digit string (`"0"`..`"7"`) into
/// `saffron`'s numbering. Any other digit string (out of range either way) is
/// returned unchanged, so `saffron`'s own parser still rejects it exactly as
/// it did before this module existed.
fn shift_digit(digits: &str) -> String {
    let Ok(value) = digits.parse::<u8>() else {
        return digits.to_owned();
    };
    match value {
        0 | 7 => "1".to_owned(),
        1..=6 => (value + 1).to_string(),
        _ => digits.to_owned(),
    }
}

/// Consume a single day token (a run of ASCII digits, or one of
/// [`DAY_NAMES`] matched case-insensitively) from the front of `s`.
///
/// Returns `(consumed, is_numeric, rest)`, or `None` if `s` doesn't start
/// with a recognizable day token at all — the caller's signal to give up and
/// return the whole atom unchanged rather than risk mangling something this
/// module didn't anticipate.
fn take_day_token(s: &str) -> Option<(&str, bool, &str)> {
    let digit_len = s.bytes().take_while(u8::is_ascii_digit).count();
    if digit_len > 0 {
        // Every byte counted above is an ASCII digit, so `digit_len` always
        // lands on a char boundary — `split_at` can't panic here.
        let (digits, rest) = s.split_at(digit_len);
        return Some((digits, true, rest));
    }
    // `s.get(..3)` — NOT a `s[..3]` byte-index slice — returns `None` both
    // when `s` is shorter than 3 bytes and when byte offset 3 falls inside a
    // multi-byte character (e.g. an atom starting with "é"), instead of
    // panicking on a non-char-boundary slice. Either way, an `s` that fails
    // this `get` doesn't start with a 3-byte ASCII day name, so it falls
    // through to `None` — the caller's "leave this atom unchanged" path —
    // exactly like any other shape this parser doesn't recognize (#1652
    // review: a cron expression's day-of-week field is unrestricted UTF-8 at
    // every parse site, admission included, so this path is reachable from
    // untrusted input and must never panic).
    let prefix = s.get(..3)?;
    if DAY_NAMES.iter().any(|n| prefix.eq_ignore_ascii_case(n)) {
        // `prefix` only existed because `s.get(..3)` already proved byte
        // offset 3 is a valid char boundary, so this `split_at` is safe too.
        let (name, rest) = s.split_at(3);
        return Some((name, false, rest));
    }
    None
}

/// Translate one comma-separated atom of the day-of-week field (a single
/// value, a `D-D` range, a `D#N`/`DL` modifier, or a `D/N`/`D-D/N` step) from
/// standard-cron numbering into `saffron`'s. `*` and `*/N` pass through
/// unchanged (no day-of-week digit to translate — see the module docs), and
/// a bare `L` passes through unchanged for the same reason.
///
/// Falls back to returning `atom` unchanged for any shape this parser
/// doesn't recognize, rather than guessing.
fn normalize_dow_atom(atom: &str) -> String {
    if atom == "*" || atom.starts_with("*/") || atom == "L" {
        return atom.to_owned();
    }

    let Some((first, first_numeric, rest)) = take_day_token(atom) else {
        return atom.to_owned();
    };
    let first_out = if first_numeric {
        shift_digit(first)
    } else {
        first.to_owned()
    };

    // A bare day, or one immediately followed by a modifier whose own value
    // is never a day-of-week digit ('L' = last, '#N' = nth, '/N' = step).
    if rest.is_empty() {
        return first_out;
    }
    if rest == "L" || rest.starts_with('#') || rest.starts_with('/') {
        return format!("{first_out}{rest}");
    }

    // A range: the low end of the '-' may itself carry a trailing '/N' step,
    // whose value is likewise never a day-of-week digit.
    if let Some(after_dash) = rest.strip_prefix('-') {
        let Some((second, second_numeric, range_rest)) = take_day_token(after_dash) else {
            return atom.to_owned();
        };

        // Standard cron's degenerate full-week spelling: `0` and `7` both
        // spell Sunday, so a bare (step-less) range between them — `0-7` or
        // `7-0` — names every day of the week, not just Sunday. Per-endpoint
        // shifting alone would collapse this to saffron `1-1` (Sunday only),
        // silently narrowing it — so this is the one shape translated as a
        // whole rather than endpoint-by-endpoint (#1652 review).
        if range_rest.is_empty()
            && first_numeric
            && second_numeric
            && let (Ok(a), Ok(b)) = (first.parse::<u8>(), second.parse::<u8>())
        {
            let mut endpoints = [a, b];
            endpoints.sort_unstable();
            if endpoints == [0, 7] {
                return "*".to_owned();
            }
        }

        let second_out = if second_numeric {
            shift_digit(second)
        } else {
            second.to_owned()
        };
        return format!("{first_out}-{second_out}{range_rest}");
    }

    // Unrecognized trailing shape — leave the whole atom untouched.
    atom.to_owned()
}

/// Translate a cron expression's day-of-week (fifth) field from standard
/// numbering into [`saffron`]'s, leaving the other four fields untouched.
///
/// Call this on every `expression` immediately before
/// `expression.parse::<saffron::Cron>()` — see the module docs for why this
/// is the one shared place every parse site must go through.
///
/// `expr` is split on ASCII whitespace; if it doesn't have exactly five
/// fields, it is returned unchanged (`saffron`'s own parser will reject it
/// for the same reason it always did — this function never masks that
/// error). Each comma-separated atom of the fifth field is translated
/// independently by [`normalize_dow_atom`], then the fields are rejoined with
/// single spaces.
#[must_use]
pub(crate) fn normalize_cron_dow(expr: &str) -> String {
    let fields: Vec<&str> = expr.split_ascii_whitespace().collect();
    let [minute, hour, dom, month, dow] = fields[..] else {
        return expr.to_owned();
    };
    let normalized_dow = dow
        .split(',')
        .map(normalize_dow_atom)
        .collect::<Vec<_>>()
        .join(",");
    format!("{minute} {hour} {dom} {month} {normalized_dow}")
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::normalize_cron_dow;

    /// One [`normalize_cron_dow`] table case: an as-written standard-cron
    /// expression and the `saffron`-numbered expression it must become.
    struct Case {
        name: &'static str,
        input: &'static str,
        expected: &'static str,
    }

    #[test]
    fn normalizes_the_day_of_week_field_only() {
        let cases = vec![
            Case {
                name: "weekday_range_shifts_up_by_one",
                input: "30 11 * * 1-5",
                expected: "30 11 * * 2-6",
            },
            Case {
                name: "standard_sunday_zero_maps_to_saffron_sunday_one",
                input: "0 9 * * 0",
                expected: "0 9 * * 1",
            },
            Case {
                name: "standard_sunday_seven_also_maps_to_saffron_sunday_one",
                input: "0 9 * * 7",
                expected: "0 9 * * 1",
            },
            Case {
                name: "saturday_six_shifts_to_seven",
                input: "* * * * 6",
                expected: "* * * * 7",
            },
            Case {
                name: "comma_list_shifts_each_value",
                input: "0 0 * * 1,3,5",
                expected: "0 0 * * 2,4,6",
            },
            Case {
                name: "star_is_untouched",
                input: "* * * * *",
                expected: "* * * * *",
            },
            Case {
                name: "star_step_is_untouched_since_it_names_no_specific_day",
                input: "* * * * */2",
                expected: "* * * * */2",
            },
            Case {
                name: "range_step_shifts_the_day_endpoints_but_not_the_step_count",
                input: "0 0 * * 1-5/2",
                expected: "0 0 * * 2-6/2",
            },
            Case {
                name: "bare_step_shifts_the_day_but_not_the_step_count",
                input: "0 0 * * 1/2",
                expected: "0 0 * * 2/2",
            },
            Case {
                name: "wrapping_range_across_the_week_boundary_shifts_both_ends",
                // Fri through Mon, standard 5-1, wrapping through Sat/Sun.
                input: "0 0 * * 5-1",
                expected: "0 0 * * 6-2",
            },
            Case {
                name: "sunday_to_friday_range_shifts_both_ends",
                input: "0 0 * * 0-5",
                expected: "0 0 * * 1-6",
            },
            Case {
                name: "three_letter_day_names_are_left_untouched",
                input: "0 9 * * MON-FRI",
                expected: "0 9 * * MON-FRI",
            },
            Case {
                name: "lowercase_day_names_are_left_untouched",
                input: "0 9 * * mon-fri",
                expected: "0 9 * * mon-fri",
            },
            Case {
                name: "mixed_numeric_and_name_range_shifts_only_the_numeric_end",
                input: "0 9 * * 1-FRI",
                expected: "0 9 * * 2-FRI",
            },
            Case {
                name: "nth_weekday_modifier_shifts_the_day_but_not_the_nth_count",
                input: "0 9 * * 1#3",
                expected: "0 9 * * 2#3",
            },
            Case {
                name: "last_weekday_modifier_shifts_the_day",
                input: "0 9 * * 5L",
                expected: "0 9 * * 6L",
            },
            Case {
                name: "bare_last_day_marker_has_no_digit_to_shift",
                input: "0 9 * * L",
                expected: "0 9 * * L",
            },
            Case {
                name: "out_of_range_digit_is_left_for_saffron_to_reject",
                input: "0 9 * * 8",
                expected: "0 9 * * 8",
            },
            Case {
                name: "non_cron_text_with_the_wrong_field_count_is_left_unchanged",
                input: "not a cron expression",
                expected: "not a cron expression",
            },
            Case {
                name: "other_fields_are_never_touched",
                input: "7 6 5 4 1",
                expected: "7 6 5 4 2",
            },
            Case {
                name: "sunday_zero_to_seven_range_names_the_whole_week",
                // `0` and `7` are both Sunday, so this range spans every
                // day — per-endpoint shifting alone would collapse it to
                // saffron `1-1` (Sunday only). #1652 review.
                input: "0 9 * * 0-7",
                expected: "0 9 * * *",
            },
            Case {
                name: "sunday_seven_to_zero_range_also_names_the_whole_week",
                input: "0 9 * * 7-0",
                expected: "0 9 * * *",
            },
        ];

        for case in cases {
            assert_eq!(
                normalize_cron_dow(case.input),
                case.expected,
                "case {}",
                case.name
            );
        }
    }

    /// #1652 review: a day-of-week atom is unrestricted UTF-8 at every parse
    /// site (admission and the scheduler both hand this module a bare
    /// `String`), so a multi-byte character whose span crosses the 3-byte
    /// prefix `take_day_token` checks for a day name must never panic on a
    /// non-char-boundary slice — it must fall through to "leave this atom
    /// unchanged," the same as any other shape this parser doesn't
    /// recognize, and let `saffron` reject it downstream exactly as it did
    /// before this module existed.
    #[test]
    fn a_multi_byte_day_of_week_atom_does_not_panic_and_is_left_unchanged() {
        // "é" is 2 bytes (0xC3 0xA9); "éé" is 4 bytes, so byte offset 3 falls
        // inside the second "é" — a non-char-boundary slice.
        let cases = [
            // An unrecognized atom passes through unchanged, whole field
            // untouched.
            ("0 9 * * éé", "0 9 * * éé"),
            ("0 9 * * aaé", "0 9 * * aaé"),
            // A comma-list still translates the atoms it DOES recognize —
            // only the malformed one is left alone.
            ("0 9 * * 1,éé", "0 9 * * 2,éé"),
        ];
        for (input, expected) in cases {
            // Must not panic; whatever comes out, `saffron` still rejects
            // the malformed atom downstream exactly as it did before this
            // module existed.
            let normalized = normalize_cron_dow(input);
            assert_eq!(normalized, expected, "input {input}");
            assert!(
                normalized.parse::<saffron::Cron>().is_err(),
                "expected `saffron` to still reject {input:?} (normalized to {normalized:?})"
            );
        }
    }
}