helm-schema-core 0.0.6

Generate an accurate JSON schema for any helm chart
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
use std::collections::BTreeSet;

use crate::{Guard, GuardValue};

/// How an inexact predicate participates in later semantic projection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ApproximationRole {
    /// Ordinary control flow whose exact relation is unavailable.
    #[default]
    Control,
    /// A sound subset identifies when one candidate supplies an expression's
    /// returned value.
    OutputSelection,
}

/// Typed Boolean formula recovered from template control flow.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Predicate {
    /// Formula that holds for every input.
    True,
    /// Formula that holds for no input.
    False,
    /// A control condition whose exact relation could not be lowered.
    ///
    /// The paths remain available for diagnostics and conservative attribution, but consumers
    /// must not turn this marker into a narrowing schema condition.
    Approximate {
        /// Stable description of the expression shape that could not be lowered.
        marker: String,
        /// Values paths mentioned by the unlowerable expression.
        paths: BTreeSet<String>,
        /// Whether the subset describes ordinary execution or returned-value
        /// selection.
        role: ApproximationRole,
        /// A predicate that IMPLIES the real condition (a sound subset).
        /// Usable only in POSITIVE polarity where firing less often is safe
        /// — a fail-arm's outer condition — never through a negation, which
        /// would invert the containment.
        sound_subset: Option<Box<Predicate>>,
    },
    /// Exactly lowerable atomic guard.
    Guard(Guard),
    /// Logical negation of a predicate.
    Not(Box<Predicate>),
    /// Conjunction of every enclosed predicate.
    And(Vec<Predicate>),
    /// Disjunction of the enclosed predicates.
    Or(Vec<Predicate>),
}

impl From<Guard> for Predicate {
    fn from(guard: Guard) -> Self {
        match guard {
            Guard::Not { path } => Self::Not(Box::new(Self::truthy_path(path))),
            Guard::Or { paths } => Self::Or(paths.into_iter().map(Self::truthy_path).collect()),
            Guard::AnyOf { alternatives } => Self::Or(
                alternatives
                    .into_iter()
                    .map(|alternative| Self::all(alternative.into_iter().map(Self::from).collect()))
                    .collect(),
            ),
            Guard::NotTypeIs { path, schema_type } => {
                Self::Not(Box::new(Self::Guard(Guard::TypeIs { path, schema_type })))
            }
            guard => Self::Guard(guard),
        }
    }
}

impl Predicate {
    /// Creates an atomic truthiness predicate for a values path.
    pub fn truthy_path(path: impl Into<String>) -> Self {
        Self::Guard(Guard::Truthy { path: path.into() })
    }

    /// Creates the exact predicate for Sprig's `kindIs "invalid"` over a values path.
    pub fn invalid_kind_path(path: impl Into<String>) -> Self {
        let path = path.into();
        Self::Or(vec![
            Self::from(Guard::Absent { path: path.clone() }),
            Self::from(Guard::Eq {
                path,
                value: GuardValue::Null,
            }),
        ])
    }

    /// Marks an unlowerable condition without inventing a relation between its paths.
    pub fn approximate(marker: impl Into<String>, paths: BTreeSet<String>) -> Self {
        Self::Approximate {
            marker: marker.into(),
            paths,
            role: ApproximationRole::Control,
            sound_subset: None,
        }
    }

    /// Marks an unlowerable condition that still admits a bounded sound
    /// strengthening: `guards` hold only in states where the real condition
    /// holds too.
    pub fn approximate_with_sound_subset(
        marker: impl Into<String>,
        paths: BTreeSet<String>,
        sound_subset: Vec<Guard>,
    ) -> Self {
        let sound_subset = match sound_subset.as_slice() {
            [] => None,
            _ => Some(Box::new(Self::all(
                sound_subset.into_iter().map(Self::from).collect(),
            ))),
        };
        Self::Approximate {
            marker: marker.into(),
            paths,
            role: ApproximationRole::Control,
            sound_subset,
        }
    }

    /// Marks an unlowerable condition with a typed predicate that implies it.
    #[must_use]
    pub fn approximate_with_sound_predicate(
        marker: impl Into<String>,
        paths: BTreeSet<String>,
        sound_subset: Self,
    ) -> Self {
        let sound_subset = (!matches!(sound_subset, Self::False)
            && !sound_subset.contains_approximation())
        .then(|| Box::new(sound_subset.normalize_boolean()));
        Self::Approximate {
            marker: marker.into(),
            paths,
            role: ApproximationRole::Control,
            sound_subset,
        }
    }

    /// Marks an inexact returned-value selection with a typed predicate that
    /// proves when the candidate supplies the result.
    #[must_use]
    pub fn approximate_output_selection(
        marker: impl Into<String>,
        paths: BTreeSet<String>,
        sound_subset: Self,
    ) -> Self {
        let sound_subset = (!matches!(sound_subset, Self::False)
            && !sound_subset.contains_approximation())
        .then(|| Box::new(sound_subset.normalize_boolean()));
        Self::Approximate {
            marker: marker.into(),
            paths,
            role: ApproximationRole::OutputSelection,
            sound_subset,
        }
    }

    /// Normalizes a conjunction, collapsing empty and singleton formulas.
    #[must_use]
    pub fn all(predicates: Vec<Self>) -> Self {
        match predicates.as_slice() {
            [] => Self::True,
            [predicate] => predicate.clone(),
            _ => Self::And(predicates),
        }
    }

    /// Returns the logical complement without retaining redundant double negation.
    #[must_use]
    pub fn negated(&self) -> Self {
        match self {
            Self::True => Self::False,
            Self::False => Self::True,
            Self::Not(inner) => inner.as_ref().clone(),
            other => Self::Not(Box::new(other.clone())),
        }
    }

    /// Canonicalizes an exact Boolean formula without distributive expansion.
    ///
    /// Opaque approximate predicates are returned unchanged. Exact formulas
    /// use a bounded decision diagram internally and fall back to the input
    /// formula if neither normal form stays bounded.
    #[must_use]
    pub fn normalize_boolean(self) -> Self {
        crate::predicate_bdd::normalize(self)
    }

    /// Reports whether this exact Boolean formula entails `consequent`.
    ///
    /// Opaque approximations never prove entailment. The bounded decision
    /// diagram may also abstain when either formula exceeds its limits.
    #[must_use]
    pub fn exactly_implies(&self, consequent: &Self) -> bool {
        crate::predicate_bdd::exact_implies(self, consequent)
    }

    /// Reports whether the predicate is the constant `true` or `false` formula.
    #[must_use]
    pub fn is_trivial(&self) -> bool {
        matches!(self, Self::True | Self::False)
    }

    /// Whether this predicate contains a condition that could not be lowered exactly.
    #[must_use]
    pub fn contains_approximation(&self) -> bool {
        match self {
            Self::Approximate { .. } => true,
            Self::Not(inner) => inner.contains_approximation(),
            Self::And(predicates) | Self::Or(predicates) => {
                predicates.iter().any(Self::contains_approximation)
            }
            Self::True | Self::False | Self::Guard(_) => false,
        }
    }

    /// Returns every values path referenced by the formula.
    #[must_use]
    pub fn value_paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_value_paths(&mut paths);
        paths
    }

    /// Expands header predicates into the context-selection facts active in their bodies.
    pub fn with_context_predicates(self) -> Vec<Self> {
        match self {
            Self::True => Vec::new(),
            Self::False => vec![Self::False],
            Self::Approximate { .. }
            | Self::Guard(
                Guard::Range { .. }
                | Guard::RangeKeyPrefix { .. }
                | Guard::RangeKeyEquals { .. }
                | Guard::RangeKeyMatches { .. }
                | Guard::Absent { .. }
                | Guard::With { .. }
                | Guard::Default { .. }
                | Guard::TypeIs { .. }
                | Guard::NotTypeIs { .. }
                | Guard::Not { .. }
                | Guard::Or { .. }
                | Guard::AnyOf { .. }
                | Guard::IntGt { .. }
                | Guard::IntLt { .. }
                | Guard::AtMostOneMember { .. }
                | Guard::MinMembers { .. }
                | Guard::HasKey { .. }
                | Guard::NotHasKey { .. }
                | Guard::ContainsEquals { .. }
                | Guard::ContainsMemberEquals { .. }
                | Guard::ContainsTruthyMember { .. },
            ) => vec![self],
            Self::And(predicates) => predicates
                .into_iter()
                .flat_map(Self::with_context_predicates)
                .collect(),
            Self::Guard(Guard::Truthy { path }) => vec![Self::from(Guard::With { path })],
            Self::Or(predicates) => {
                let paths: Option<Vec<String>> = predicates
                    .iter()
                    .map(|predicate| match predicate {
                        Self::Guard(Guard::Truthy { path }) => Some(path.clone()),
                        _ => None,
                    })
                    .collect();
                let Some(paths) = paths else {
                    return vec![Self::Or(predicates)];
                };
                let mut out: Vec<Self> = paths
                    .iter()
                    .map(|path| Self::from(Guard::With { path: path.clone() }))
                    .collect();
                out.push(Self::Or(paths.into_iter().map(Self::truthy_path).collect()));
                out
            }
            Self::Not(inner) => match inner.as_ref() {
                Self::Guard(Guard::Truthy { path }) => vec![
                    Self::from(Guard::With { path: path.clone() }),
                    Self::Not(inner),
                ],
                _ => vec![Self::Not(inner)],
            },
            Self::Guard(Guard::Eq { path, value }) => vec![
                Self::from(Guard::With { path: path.clone() }),
                Self::from(Guard::Eq { path, value }),
            ],
            Self::Guard(Guard::MatchesPattern {
                path,
                pattern,
                templated,
            }) => vec![
                Self::from(Guard::With { path: path.clone() }),
                Self::from(Guard::MatchesPattern {
                    path,
                    pattern,
                    templated,
                }),
            ],
            Self::Guard(Guard::NotMatchesPattern { path, pattern }) => vec![
                Self::from(Guard::With { path: path.clone() }),
                Self::from(Guard::NotMatchesPattern { path, pattern }),
            ],
            Self::Guard(Guard::NotEq { path, value }) => vec![
                Self::from(Guard::With { path: path.clone() }),
                Self::from(Guard::NotEq { path, value }),
            ],
        }
    }

    /// Returns values paths whose branch structure permits them to be absent.
    #[must_use]
    pub fn conditionally_optional_paths(&self) -> BTreeSet<String> {
        let mut paths = BTreeSet::new();
        self.collect_conditionally_optional_paths(&mut paths);
        paths
    }

    /// Projects this formula into the contract guard vocabulary.
    pub fn contract_guards(&self) -> Vec<Guard> {
        match self {
            Self::True | Self::False | Self::Approximate { .. } => Vec::new(),
            Self::Guard(guard) => vec![guard.clone()],
            Self::Not(inner) => negated_contract_guards(inner),
            Self::And(predicates) => predicates.iter().flat_map(Self::contract_guards).collect(),
            Self::Or(predicates) => or_contract_guards(predicates),
        }
    }

    /// Whether [`Self::contract_guards`] represents this predicate
    /// EXACTLY: the flattened guard conjunction selects the same states.
    /// Negations distribute by De Morgan down to negatable guard leaves;
    /// a negation reaching a leaf the vocabulary cannot flip flattens to
    /// NOTHING, which an `And` flatten would silently drop — a fail
    /// conjunction missing such a conjunct negates into states the
    /// validator never rejects, so callers keep those conjuncts as raw
    /// predicates instead.
    #[must_use]
    pub fn contract_guards_are_exact(&self) -> bool {
        match self {
            Self::True | Self::Guard(_) => true,
            Self::False | Self::Approximate { .. } => false,
            Self::Not(inner) => negation_flattens_exactly(inner),
            Self::And(predicates) | Self::Or(predicates) => {
                predicates.iter().all(Self::contract_guards_are_exact)
            }
        }
    }

    fn collect_value_paths(&self, out: &mut BTreeSet<String>) {
        match self {
            Self::True | Self::False => {}
            Self::Approximate { paths, .. } => out.extend(paths.iter().cloned()),
            Self::Guard(guard) => {
                for path in guard.value_paths() {
                    out.insert(path.to_string());
                }
            }
            Self::Not(inner) => inner.collect_value_paths(out),
            Self::And(predicates) | Self::Or(predicates) => {
                for predicate in predicates {
                    predicate.collect_value_paths(out);
                }
            }
        }
    }

    fn collect_conditionally_optional_paths(&self, out: &mut BTreeSet<String>) {
        match self {
            Self::Guard(Guard::NotEq { path, .. } | Guard::Absent { path }) => {
                out.insert(path.clone());
            }
            Self::Not(inner) => match inner.as_ref() {
                Self::Guard(Guard::Truthy { path }) => {
                    out.insert(path.clone());
                }
                _ => inner.collect_conditionally_optional_paths(out),
            },
            Self::Or(predicates) => {
                for predicate in predicates {
                    out.extend(predicate.value_paths());
                }
            }
            Self::And(predicates) => {
                for predicate in predicates {
                    predicate.collect_conditionally_optional_paths(out);
                }
            }
            Self::True
            | Self::False
            | Self::Approximate { .. }
            | Self::Guard(
                Guard::Truthy { .. }
                | Guard::Eq { .. }
                | Guard::MatchesPattern { .. }
                | Guard::NotMatchesPattern { .. }
                | Guard::RangeKeyPrefix { .. }
                | Guard::RangeKeyEquals { .. }
                | Guard::RangeKeyMatches { .. }
                | Guard::Range { .. }
                | Guard::With { .. }
                | Guard::Default { .. }
                | Guard::TypeIs { .. }
                | Guard::NotTypeIs { .. }
                | Guard::Not { .. }
                | Guard::Or { .. }
                | Guard::AnyOf { .. }
                | Guard::IntGt { .. }
                | Guard::IntLt { .. }
                | Guard::AtMostOneMember { .. }
                | Guard::MinMembers { .. }
                | Guard::HasKey { .. }
                | Guard::NotHasKey { .. }
                | Guard::ContainsEquals { .. }
                | Guard::ContainsMemberEquals { .. }
                | Guard::ContainsTruthyMember { .. },
            ) => {}
        }
    }

    /// Projects a predicate stack into a deduplicated guard conjunction.
    #[must_use]
    pub fn contract_guard_stack(predicates: &[Self]) -> Vec<Guard> {
        let mut guards = Vec::new();
        for predicate in predicates {
            for guard in predicate.contract_guards() {
                if !guards.contains(&guard) {
                    guards.push(guard);
                }
            }
        }
        guards
    }

    /// Rewrites every values path carried by this formula.
    #[must_use]
    pub fn map_value_paths<F>(self, map: &mut F) -> Self
    where
        F: FnMut(&str) -> String,
    {
        match self {
            Self::True => Self::True,
            Self::False => Self::False,
            Self::Approximate {
                marker,
                paths,
                role,
                sound_subset,
            } => Self::Approximate {
                marker,
                paths: paths.into_iter().map(|path| map(&path)).collect(),
                role,
                sound_subset: sound_subset
                    .map(|predicate| Box::new(predicate.map_value_paths(map))),
            },
            Self::Guard(guard) => Self::Guard(guard.map_value_paths(map)),
            Self::Not(inner) => Self::Not(Box::new(inner.map_value_paths(map))),
            Self::And(predicates) => Self::And(
                predicates
                    .into_iter()
                    .map(|predicate| predicate.map_value_paths(map))
                    .collect(),
            ),
            Self::Or(predicates) => Self::Or(
                predicates
                    .into_iter()
                    .map(|predicate| predicate.map_value_paths(map))
                    .collect(),
            ),
        }
    }
}

/// Whether [`negated_contract_guards`] flattens `¬inner` exactly: every
/// De Morgan leaf must be a negatable guard (`True`/`False` leaves are
/// excluded — the guard vocabulary cannot spell a constant).
fn negation_flattens_exactly(inner: &Predicate) -> bool {
    match inner {
        Predicate::Guard(
            Guard::Truthy { .. }
            | Guard::With { .. }
            | Guard::Not { .. }
            | Guard::Or { .. }
            | Guard::Eq { .. }
            | Guard::NotEq { .. }
            | Guard::TypeIs { .. }
            | Guard::NotTypeIs { .. }
            | Guard::HasKey { .. }
            | Guard::NotHasKey { .. },
        ) => true,
        Predicate::Not(inner) => inner.contract_guards_are_exact(),
        Predicate::And(predicates) | Predicate::Or(predicates) => {
            predicates.iter().all(negation_flattens_exactly)
        }
        _ => false,
    }
}

fn negated_contract_guards(inner: &Predicate) -> Vec<Guard> {
    match inner {
        Predicate::Guard(Guard::Truthy { path } | Guard::With { path }) => {
            vec![Guard::Not { path: path.clone() }]
        }
        Predicate::Guard(Guard::Not { path }) => vec![Guard::Truthy { path: path.clone() }],
        Predicate::Guard(Guard::Or { paths }) => paths
            .iter()
            .map(|path| Guard::Not { path: path.clone() })
            .collect(),
        Predicate::Guard(Guard::Eq { path, value }) => vec![Guard::NotEq {
            path: path.clone(),
            value: value.clone(),
        }],
        Predicate::Guard(Guard::NotEq { path, value }) => vec![Guard::Eq {
            path: path.clone(),
            value: value.clone(),
        }],
        Predicate::Guard(Guard::TypeIs { path, schema_type }) => vec![Guard::NotTypeIs {
            path: path.clone(),
            schema_type: schema_type.clone(),
        }],
        Predicate::Guard(Guard::NotTypeIs { path, schema_type }) => vec![Guard::TypeIs {
            path: path.clone(),
            schema_type: schema_type.clone(),
        }],
        Predicate::Guard(Guard::HasKey { path, key }) => vec![Guard::NotHasKey {
            path: path.clone(),
            key: key.clone(),
        }],
        Predicate::Guard(Guard::NotHasKey { path, key }) => vec![Guard::HasKey {
            path: path.clone(),
            key: key.clone(),
        }],
        Predicate::Not(inner) => inner.contract_guards(),
        // ¬(p₁ ∨ … ∨ pₙ) = ¬p₁ ∧ … ∧ ¬pₙ: a plain conjunction, exact only
        // when every disjunct negates exactly (an empty flatten anywhere
        // abstains the whole negation instead of silently dropping it).
        Predicate::Or(predicates) => {
            let mut guards = Vec::new();
            for predicate in predicates {
                let negated = negated_contract_guards(predicate);
                if negated.is_empty() {
                    return Vec::new();
                }
                guards.extend(negated);
            }
            guards
        }
        // ¬(p₁ ∧ … ∧ pₙ) = ¬p₁ ∨ … ∨ ¬pₙ: one alternative per conjunct,
        // sharing the disjunction normalization of the positive `Or` lane.
        Predicate::And(predicates) => {
            let mut alternatives = Vec::new();
            for predicate in predicates {
                let negated = negated_contract_guards(predicate);
                if negated.is_empty() {
                    return Vec::new();
                }
                alternatives.push(negated);
            }
            alternatives_to_guards(alternatives)
        }
        _ => Vec::new(),
    }
}

fn or_contract_guards(predicates: &[Predicate]) -> Vec<Guard> {
    let alternatives = predicates
        .iter()
        .map(Predicate::contract_guards)
        .collect::<Vec<_>>();

    if alternatives.iter().any(Vec::is_empty) {
        return Vec::new();
    }
    alternatives_to_guards(alternatives)
}

/// Normalize a disjunction of guard conjunctions into guard form: a single
/// alternative collapses to its conjunction, all-truthy alternatives become
/// the flat [`Guard::Or`], anything else the general [`Guard::AnyOf`].
fn alternatives_to_guards(mut alternatives: Vec<Vec<Guard>>) -> Vec<Guard> {
    for alternative in &mut alternatives {
        alternative.sort();
        alternative.dedup();
    }
    alternatives.sort();
    alternatives.dedup();

    if alternatives.len() == 1 {
        return alternatives.pop().unwrap_or_default();
    }

    if let Some(paths) = truthy_or_paths(&alternatives) {
        return vec![Guard::Or { paths }];
    }

    vec![Guard::AnyOf { alternatives }]
}

fn truthy_or_paths(alternatives: &[Vec<Guard>]) -> Option<Vec<String>> {
    alternatives
        .iter()
        .map(|alternative| match alternative.as_slice() {
            [Guard::Truthy { path }] => Some(path.clone()),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
#[path = "tests/predicate.rs"]
mod tests;