helm-schema-ir 0.0.4

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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
use std::collections::{BTreeMap, BTreeSet};

use helm_schema_ast::{Literal, TemplateExpr};

use crate::abstract_value::AbstractValue;
use crate::eval_effect::{Effects, EvalResult};
use crate::eval_env::EvalEnv;
use crate::expr_eval::{HelperCallValueResolver, eval_expr_with_helper_calls};
use helm_schema_ast::expression_schema_type;
use helm_schema_core::{GuardValue, Predicate};

use super::strict_operands::{
    pipeline_string_operand_facts, record_range_key_string_consumer_effects,
    record_raw_range_key_string_consumer_paths, record_string_call_consumers,
    record_string_consumer_effects,
};
use super::value_facts::{identity_value_paths, split_transformed_value, value_strings};
use super::{eval_all_args, eval_unknown_call, merge_arg_effects, merge_arg_values};

/// `default FALLBACK PRIMARY` and `PRIMARY | default FALLBACK` are one rule:
/// the primary's identity paths become defaulted (typed by a literal
/// fallback), and the value is the choice of primary and fallback values.
pub(super) fn eval_default(
    primary: EvalResult,
    fallback_args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut effects = primary.effects;
    let primary_paths = identity_value_paths(primary.value.as_ref());
    let primary_identity = direct_raw_identity_path(primary.value.as_ref());
    effects.add_default_paths(primary_paths.clone());
    // Only a LITERAL fallback types the path: `default "x" .Values.name`
    // documents a string-shaped input. A call fallback (`default (include
    // …) .Values.ns`) only proves the fallback renders text; the path
    // itself accepts whatever the render site accepts. The hint rides its
    // own channel: `default` itself never consumes the raw value — every
    // Helm-empty input selects the fallback and renders — so the fallback's
    // kind types only the truthy arm and must not close the base against
    // Helm-empty inputs.
    if let Some(schema_type) = fallback_args
        .first()
        .map(TemplateExpr::deparen)
        .filter(|expr| matches!(expr, TemplateExpr::Literal(_)))
        .and_then(expression_schema_type)
    {
        effects.add_fallback_type_hints(primary_paths, schema_type);
    }
    let mut values = primary.value.into_iter().collect::<Vec<_>>();
    let mut fallback_paths = BTreeSet::new();
    for fallback in fallback_args {
        let result = eval_expr_with_helper_calls(fallback, env, resolver);
        fallback_paths.extend(identity_value_paths(result.value.as_ref()));
        effects.merge(result.effects);
        if let Some(value) = result.value {
            values.push(value);
        }
    }
    if let Some(primary_path) = primary_identity {
        let overlaps_fallback = fallback_paths.remove(&primary_path);
        if !overlaps_fallback {
            let meta = effects
                .local_output_meta
                .entry(primary_path.clone())
                .or_default();
            meta.conjoin_branches(&BTreeSet::from([Predicate::truthy_path(
                primary_path.clone(),
            )]));
            // A scalar literal fallback is the binding's exact value on
            // every Helm-falsy input; equality decoding needs the literal
            // itself to spell the fallback arm. Floats abstain (their
            // file-vs-`--set` channels compare differently).
            if let [fallback] = fallback_args {
                meta.default_fallback = match fallback.deparen() {
                    TemplateExpr::Literal(Literal::String(value) | Literal::RawString(value)) => {
                        Some(GuardValue::string(value.clone()))
                    }
                    TemplateExpr::Literal(Literal::Bool(value)) => Some(GuardValue::Bool(*value)),
                    TemplateExpr::Literal(Literal::Int(value)) => Some(GuardValue::Int(*value)),
                    _ => None,
                };
            }
        }
        let fallback_condition = BTreeSet::from([Predicate::truthy_path(primary_path).negated()]);
        for path in fallback_paths {
            effects
                .local_output_meta
                .entry(path)
                .or_default()
                .conjoin_branches(&fallback_condition);
        }
    }
    // `values` holds the primary first and the fallback second exactly when
    // both resolved, which is the ordered first-truthy selection; a missing
    // arm leaves only the other value, where the chain collapses to it (the
    // same result the unordered choice produced).
    EvalResult::with_effects(AbstractValue::first_truthy(values), effects)
}

pub(super) fn direct_raw_identity_path(value: Option<&AbstractValue>) -> Option<String> {
    match value? {
        AbstractValue::ValuesPath(path) | AbstractValue::JsonDecodedPath(path) => {
            Some(path.clone())
        }
        _ => None,
    }
}

pub(super) fn eval_coalesce(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut effects = Effects::default();
    let mut values = Vec::new();
    let mut default_paths = BTreeSet::new();
    let mut candidate_paths = Vec::with_capacity(args.len());
    for arg in args {
        let result = eval_expr_with_helper_calls(arg, env, resolver);
        default_paths.extend(identity_value_paths(result.value.as_ref()));
        let candidate_path = matches!(
            arg.deparen(),
            TemplateExpr::Field(_) | TemplateExpr::Selector { .. }
        )
        .then(|| direct_raw_identity_path(result.value.as_ref()))
        .flatten()
        .filter(|path| !path.is_empty());
        candidate_paths.push(candidate_path);
        effects.merge(result.effects);
        if let Some(value) = result.value {
            values.push(value);
        }
    }
    // `coalesce` selects only non-empty candidates. Downstream strict consumers therefore see
    // each source path only while it is truthy, just as they see a `default` primary.
    effects.add_default_paths(default_paths);
    // A computed candidate makes every later arm depend on a truthiness test
    // we cannot name, so only claim ordered selection when every arm has a
    // direct identity.
    if candidate_paths.iter().all(Option::is_some) {
        let mut previous_false = BTreeSet::new();
        let mut seen = BTreeSet::new();
        for path in candidate_paths.into_iter().flatten() {
            if seen.insert(path.clone()) {
                let mut selection = previous_false.clone();
                selection.insert(Predicate::truthy_path(path.clone()));
                effects
                    .local_output_meta
                    .entry(path.clone())
                    .or_default()
                    .conjoin_branches(&selection);
            }
            previous_false.insert(Predicate::truthy_path(path).negated());
        }
    }
    // A constant final fallback rescues the Helm-empty rendering of a
    // STRINGIFIED first arm (cilium's `coalesce $stringValueKPR "false"`):
    // equality decoding may then admit the empty spellings for the fallback
    // literal. Bounded to the fully explained two-arm shape; a raw first
    // arm abstains because its Helm-emptiness spans false/0/nil/empty
    // collections, not just the empty string.
    if let [first, fallback] = values.as_slice()
        && let AbstractValue::StringSet(literals) = fallback
        && literals.len() == 1
        && let Some(literal) = literals
            .iter()
            .next()
            .filter(|literal| !literal.is_empty())
            .cloned()
        && let Some(rescues) = empty_rescue_paths(first, &effects)
    {
        for path in rescues {
            effects
                .local_output_meta
                .entry(path.0)
                .or_default()
                .empty_rescue = Some(crate::helper_meta::EmptyRescue {
                fallback: literal.clone(),
                spellings: path.1,
            });
        }
    }
    EvalResult::with_effects(AbstractValue::choice(values), effects)
}

/// The per-path [`crate::helper_meta::EmptyRescue`] spellings for a
/// `coalesce` first argument, provided every alternative is explained: a
/// STRINGIFIED identity (its rendering is empty exactly for the raw empty
/// string), or the empty-string literal a recorded fold diverts to. One
/// unexplained alternative (an empty literal without fold spellings, a raw
/// identity, derived text) abstains — its states reach the fallback for
/// spellings the rescue could not name.
fn empty_rescue_paths(
    value: &AbstractValue,
    effects: &Effects,
) -> Option<Vec<(String, BTreeSet<GuardValue>)>> {
    let arms: Vec<&AbstractValue> = match value {
        AbstractValue::Choice(choices) => choices.iter().collect(),
        AbstractValue::FirstTruthy(candidates) => candidates.iter().collect(),
        other => vec![other],
    };
    let is_empty_literal = |arm: &AbstractValue| matches!(arm, AbstractValue::StringSet(set) if set.len() == 1 && set.contains(""));
    let has_empty_literal_arm = arms.iter().any(|arm| is_empty_literal(arm));
    let stringified_in_effects = |path: &str| {
        effects.stringified_paths.contains(path)
            || effects
                .local_output_meta
                .get(path)
                .is_some_and(|meta| meta.stringified)
    };
    let mut rescues = Vec::new();
    for arm in arms {
        let (path, meta) = match arm {
            arm if is_empty_literal(arm) => continue,
            AbstractValue::OutputPath(path, meta) => (path, Some(meta)),
            AbstractValue::ValuesPath(path) => (path, None),
            _ => return None,
        };
        let stringified = meta.is_some_and(|meta| meta.stringified) || stringified_in_effects(path);
        if !stringified {
            return None;
        }
        let mut spellings = BTreeSet::from([GuardValue::string("")]);
        match meta.and_then(|meta| meta.empty_fold_spellings.as_ref()) {
            Some(fold) => spellings.extend(fold.iter().cloned()),
            // An empty-literal alternative without a recorded divert means
            // unknown raw values reach the fallback.
            None if has_empty_literal_arm => return None,
            None => {}
        }
        rescues.push((path.clone(), spellings));
    }
    (!rescues.is_empty()).then_some(rescues)
}

pub(super) fn eval_dict(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut map = BTreeMap::new();
    let mut effects = Effects::default();
    for pair in args.chunks_exact(2) {
        let [key, value] = pair else {
            continue;
        };
        let TemplateExpr::Literal(Literal::String(key) | Literal::RawString(key)) = key else {
            continue;
        };
        let value = eval_expr_with_helper_calls(value, env, resolver);
        effects.merge(value.effects);
        map.insert(key.clone(), value.value.unwrap_or(AbstractValue::Unknown));
    }
    EvalResult::with_effects(Some(AbstractValue::Dict(map)), effects)
}

pub(super) fn eval_pick(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let Some((subject, key_args)) = args.split_first() else {
        return eval_all_args(args, env, resolver);
    };
    let mut subject = eval_expr_with_helper_calls(subject, env, resolver);
    let mut keys = BTreeSet::new();
    for arg in key_args {
        let key = eval_expr_with_helper_calls(arg, env, resolver);
        keys.extend(value_strings(key.value.as_ref()));
        subject.effects.merge(key.effects);
    }
    let value = subject.value.map(|value| {
        let entries = keys
            .into_iter()
            .filter_map(|key| {
                value
                    .apply_to_path(std::slice::from_ref(&key))
                    .map(|picked| (key, picked))
            })
            .collect();
        AbstractValue::Dict(entries)
    });
    EvalResult::with_effects(value, subject.effects)
}

pub(super) fn eval_list(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut items = Vec::new();
    let mut effects = Effects::default();
    for arg in args {
        let item = eval_expr_with_helper_calls(arg, env, resolver);
        effects.merge(item.effects);
        items.push(item.value.unwrap_or(AbstractValue::Unknown));
    }
    EvalResult::with_effects(Some(AbstractValue::List(items)), effects)
}

pub(super) fn eval_concat(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut items = Vec::new();
    let mut effects = Effects::default();
    for arg in args {
        let result = eval_expr_with_helper_calls(arg, env, resolver);
        effects.merge(result.effects);
        match result.value {
            Some(AbstractValue::List(mut values)) => items.append(&mut values),
            Some(value) => {
                if let Some(item) = value.fragment_range_item() {
                    items.push(item);
                }
            }
            None => {}
        }
    }
    EvalResult::with_effects(Some(AbstractValue::List(items)), effects)
}

pub(super) fn eval_prepend(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let [list, item] = args else {
        return eval_all_args(args, env, resolver);
    };
    let mut list = eval_expr_with_helper_calls(list, env, resolver);
    let item = eval_expr_with_helper_calls(item, env, resolver);
    list.effects.merge(item.effects);
    let mut items = item.value.into_iter().collect::<Vec<_>>();
    match list.value {
        Some(AbstractValue::List(mut values)) => items.append(&mut values),
        Some(value) => {
            if let Some(item) = value.fragment_range_item() {
                items.push(item);
            }
        }
        None => {}
    }
    EvalResult::with_effects(Some(AbstractValue::List(items)), list.effects)
}

/// `pluck KEY MAP` whose KEY is the current ranged key of the SAME map
/// selects exactly the current member: the result is the singleton list
/// holding that member's identity (signoz's `pluck . $dict | first` member
/// read inside `range keys .`). Other shapes keep widened-call semantics.
pub(super) fn eval_pluck(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    if let [key_expr, map_expr] = args {
        let key = eval_expr_with_helper_calls(key_expr, env, resolver);
        if let Some(AbstractValue::RangeKey(key_source)) = &key.value {
            let map = eval_expr_with_helper_calls(map_expr, env, resolver);
            let member = match &map.value {
                Some(
                    value
                    @ (AbstractValue::ValuesPath(path) | AbstractValue::JsonDecodedPath(path)),
                ) if path == key_source => value.fragment_range_item(),
                _ => None,
            };
            if let Some(member) = member {
                let mut effects = key.effects;
                effects.merge(map.effects);
                return EvalResult::with_effects(Some(AbstractValue::List(vec![member])), effects);
            }
        }
    }
    eval_unknown_call(args, Effects::default(), env, resolver)
}

pub(super) fn eval_first(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let Some(arg) = args.first() else {
        return eval_all_args(args, env, resolver);
    };
    eval_first_result(eval_expr_with_helper_calls(arg, env, resolver))
}

pub(super) fn eval_first_result(result: EvalResult) -> EvalResult {
    let value = match result.value {
        Some(AbstractValue::List(items)) => items.first().cloned(),
        Some(AbstractValue::SplitList {
            source_paths,
            separator,
            total_text_preimage,
        }) => Some(AbstractValue::SplitSegment {
            source_paths,
            separator,
            last: false,
            total_text_preimage,
        }),
        Some(value) => value.fragment_range_item(),
        None => None,
    };
    EvalResult::with_effects(value, result.effects)
}

pub(super) fn eval_last(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let Some(arg) = args.first() else {
        return eval_all_args(args, env, resolver);
    };
    eval_last_result(eval_expr_with_helper_calls(arg, env, resolver))
}

pub(super) fn eval_last_result(result: EvalResult) -> EvalResult {
    let value = match result.value {
        Some(AbstractValue::List(items)) => items.last().cloned(),
        Some(AbstractValue::SplitList {
            source_paths,
            separator,
            total_text_preimage,
        }) => Some(AbstractValue::SplitSegment {
            source_paths,
            separator,
            last: true,
            total_text_preimage,
        }),
        Some(value) => value.fragment_range_item(),
        None => None,
    };
    EvalResult::with_effects(value, result.effects)
}

pub(super) fn eval_reverse(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let Some(arg) = args.first() else {
        return eval_all_args(args, env, resolver);
    };
    eval_reverse_result(eval_expr_with_helper_calls(arg, env, resolver))
}

pub(super) fn eval_reverse_result(result: EvalResult) -> EvalResult {
    let value = match result.value {
        Some(AbstractValue::List(mut items)) => {
            items.reverse();
            Some(AbstractValue::List(items))
        }
        other => other,
    };
    EvalResult::with_effects(value, result.effects)
}

pub(super) fn eval_split_list(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let [separator, subject] = args else {
        return eval_all_args(args, env, resolver);
    };
    let TemplateExpr::Literal(Literal::String(separator) | Literal::RawString(separator)) =
        separator.deparen()
    else {
        return eval_all_args(args, env, resolver);
    };
    let mut result = eval_expr_with_helper_calls(subject, env, resolver);
    let source_paths = result
        .value
        .as_ref()
        .map(AbstractValue::paths)
        .unwrap_or_default();
    let total_text_preimage = source_paths.iter().all(|path| {
        result.effects.shape_erased_paths.contains(path)
            || result
                .effects
                .local_output_meta
                .get(path)
                .is_some_and(|meta| meta.shape_erased || meta.derived_text)
    });
    // The subject must be a Go string at runtime whatever the split
    // produces: the literal-split fast path below is value refinement on
    // top of that contract, not a replacement for it.
    record_string_consumer_effects(
        &identity_value_paths(result.value.as_ref()),
        &mut result.effects,
    );
    let value = result.value.clone();
    record_range_key_string_consumer_effects(value.as_ref(), &mut result.effects);
    let Some(strings) = result.value.as_ref().map(AbstractValue::strings) else {
        let value = (!source_paths.is_empty()).then_some(AbstractValue::SplitList {
            source_paths,
            separator: separator.clone(),
            total_text_preimage,
        });
        return EvalResult::with_effects(value, result.effects);
    };
    if strings.is_empty() {
        let value = (!source_paths.is_empty()).then_some(AbstractValue::SplitList {
            source_paths,
            separator: separator.clone(),
            total_text_preimage,
        });
        return EvalResult::with_effects(value, result.effects);
    }

    let split_values = split_string_set(separator, strings);
    EvalResult::with_effects(split_values, result.effects)
}

pub(super) fn eval_regex_split(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let [pattern, subject, limit] = args else {
        return eval_all_args(args, env, resolver);
    };
    let mut subject = eval_expr_with_helper_calls(subject, env, resolver);
    let source_paths = subject
        .value
        .as_ref()
        .map(AbstractValue::paths)
        .unwrap_or_default();
    let total_text_preimage = source_paths.iter().all(|path| {
        subject.effects.shape_erased_paths.contains(path)
            || subject
                .effects
                .local_output_meta
                .get(path)
                .is_some_and(|meta| meta.shape_erased || meta.derived_text)
    });
    for arg in [pattern, limit] {
        subject
            .effects
            .merge(eval_expr_with_helper_calls(arg, env, resolver).effects);
    }
    record_string_call_consumers("regexSplit", args, env, resolver, &mut subject.effects);

    let separator = match pattern.deparen() {
        TemplateExpr::Literal(Literal::String(value) | Literal::RawString(value))
            if is_literal_regex(value) =>
        {
            value.clone()
        }
        _ => {
            return EvalResult::with_effects(AbstractValue::widened(source_paths), subject.effects);
        }
    };
    let value = (!source_paths.is_empty()).then_some(AbstractValue::SplitList {
        source_paths,
        separator,
        total_text_preimage,
    });
    EvalResult::with_effects(value, subject.effects)
}

fn is_literal_regex(pattern: &str) -> bool {
    !pattern.is_empty()
        && !pattern.chars().any(|character| {
            matches!(
                character,
                '\\' | '.' | '^' | '$' | '|' | '?' | '*' | '+' | '(' | ')' | '[' | ']' | '{' | '}'
            )
        })
}

pub(super) fn eval_nonempty_split(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let [separator, subject] = args else {
        return eval_all_args(args, env, resolver);
    };
    let separator = eval_expr_with_helper_calls(separator, env, resolver);
    let mut subject = eval_expr_with_helper_calls(subject, env, resolver);
    subject.effects.merge(separator.effects);
    let mut effects = subject.effects;
    record_string_call_consumers("split", args, env, resolver, &mut effects);
    let separator = value_strings(separator.value.as_ref());
    let value = single_string(separator).and_then(|separator| {
        // A raw-identity subject keeps its path through `._0` qualified by
        // the separator as a lexical escape before the legacy map
        // degrade.
        subject
            .value
            .as_ref()
            .and_then(|value| split_transformed_value(value, &effects, &separator))
            .or_else(|| nonempty_split_map(subject.value.as_ref(), &separator))
    });
    EvalResult::with_effects(value, effects)
}

pub(super) fn eval_nonempty_split_pipeline(
    current: EvalResult,
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let (string_paths, raw_range_key_paths) = pipeline_string_operand_facts(
        "split",
        args,
        current.value.as_ref(),
        &current.effects,
        env,
        resolver,
    );
    let separator = args
        .first()
        .map(|arg| eval_expr_with_helper_calls(arg, env, resolver))
        .and_then(|result| single_string(value_strings(result.value.as_ref())));
    let value = separator.as_deref().and_then(|separator| {
        current
            .value
            .as_ref()
            .and_then(|value| split_transformed_value(value, &current.effects, separator))
            .or_else(|| nonempty_split_map(current.value.as_ref(), separator))
    });
    let mut effects = current.effects;
    merge_arg_effects(args, env, resolver, &mut effects);
    record_string_consumer_effects(&string_paths, &mut effects);
    record_raw_range_key_string_consumer_paths(&raw_range_key_paths, &mut effects);
    EvalResult::with_effects(value, effects)
}

pub(super) fn nonempty_split_map(
    source: Option<&AbstractValue>,
    separator: &str,
) -> Option<AbstractValue> {
    let strings = source.map(AbstractValue::strings).unwrap_or_default();
    if strings.is_empty() {
        return Some(AbstractValue::Overlay {
            entries: BTreeMap::from([("_0".to_string(), AbstractValue::Unknown)]),
            fallback: Box::new(AbstractValue::Unknown),
        });
    }
    AbstractValue::choice(
        strings
            .into_iter()
            .map(|value| {
                AbstractValue::Dict(
                    value
                        .split(separator)
                        .enumerate()
                        .map(|(index, part)| {
                            (
                                format!("_{index}"),
                                AbstractValue::StringSet(BTreeSet::from([part.to_string()])),
                            )
                        })
                        .collect(),
                )
            })
            .collect(),
    )
}

fn single_string(strings: BTreeSet<String>) -> Option<String> {
    let mut strings = strings.into_iter();
    let first = strings.next()?;
    strings.next().is_none().then_some(first)
}

pub(super) fn is_nonempty_string_literal(expr: &TemplateExpr) -> bool {
    matches!(
        expr.deparen(),
        TemplateExpr::Literal(Literal::String(value) | Literal::RawString(value))
            if !value.is_empty()
    )
}

pub(super) fn split_string_set(
    separator: &str,
    strings: BTreeSet<String>,
) -> Option<AbstractValue> {
    if separator.is_empty() {
        return None;
    }

    let choices = strings
        .into_iter()
        .map(|value| {
            AbstractValue::List(
                value
                    .split(separator)
                    .map(|part| AbstractValue::StringSet(BTreeSet::from([part.to_string()])))
                    .collect(),
            )
        })
        .collect();
    AbstractValue::choice(choices)
}

pub(super) fn eval_append(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut effects = Effects::default();
    let mut items = match args
        .first()
        .map(|expr| eval_expr_with_helper_calls(expr, env, resolver))
    {
        Some(result) => {
            effects.merge(result.effects);
            match result.value {
                Some(AbstractValue::List(items)) => items,
                Some(value) => vec![value],
                None => Vec::new(),
            }
        }
        None => Vec::new(),
    };
    if let Some((_, rest)) = args.split_first() {
        merge_arg_values(rest, env, resolver, &mut items, &mut effects);
    }
    EvalResult::with_effects(Some(AbstractValue::List(items)), effects)
}

pub(super) fn eval_omit(
    args: &[TemplateExpr],
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let Some((base, key_args)) = args.split_first() else {
        return eval_all_args(args, env, resolver);
    };
    let mut base = eval_expr_with_helper_calls(base, env, resolver);
    let mut keys = BTreeSet::new();
    for arg in key_args {
        let key = eval_expr_with_helper_calls(arg, env, resolver);
        keys.extend(value_strings(key.value.as_ref()));
        base.effects.merge(key.effects);
    }
    let value = base.value.map(|value| value.omit_keys(&keys));
    // A values-backed base keeps its path identity (structural entries are
    // filtered in place), so the removal is recorded as an effect: sink
    // typing for the removed members must not bind through this render
    // (external-secrets' OpenShift `adaptSecurityContext` omit).
    if let Some(path) = value.as_ref().and_then(AbstractValue::unique_path) {
        base.effects
            .omitted_map_keys
            .entry(path)
            .or_default()
            .extend(keys.iter().cloned());
    }
    EvalResult::with_effects(value, base.effects)
}

pub(super) fn eval_merge(
    function: &str,
    args: &[TemplateExpr],
    piped: EvalResult,
    env: &EvalEnv,
    resolver: &mut impl HelperCallValueResolver,
) -> EvalResult {
    let mut effects = piped.effects;
    let piped_values = piped.value.into_iter().collect::<Vec<_>>();
    let operand_count = args.len() + piped_values.len();
    let mut values = Vec::new();
    merge_arg_values(args, env, resolver, &mut values, &mut effects);
    // A Go pipeline passes the piped subject as the LAST argument.
    values.extend(piped_values);
    // An overwrite-merge whose destination is the LITERAL values root
    // mutates the shared map in place: members under each source prefix
    // overwrite their effective-root twins for the rest of the render
    // (istiod's `mustMergeOverwrite $.Values (index $.Values "pilot")`
    // descope). Only the direct `$.Values`/`.Values` spelling qualifies —
    // a copied destination (`deepCopy $.Values`) mutates nothing shared.
    if matches!(function, "mergeOverwrite" | "mustMergeOverwrite")
        && args.first().is_some_and(expr_is_direct_values_root)
    {
        for source in values.iter().skip(1) {
            if let Some(path) = source.unique_path().filter(|path| !path.is_empty()) {
                effects.values_root_overlay_prefixes.insert(path);
            }
        }
    }
    // A definitely-empty literal destination (`mergeOverwrite (dict) a b`)
    // supplies no keys in any state, so it neither shadows nor contributes:
    // dropping it keeps the remaining operands eligible for the ordered
    // layer form (KPS's fresh-dict annotation merges).
    let dropped_empty_literals = values
        .iter()
        .filter(|value| matches!(value, AbstractValue::Dict(entries) if entries.is_empty()))
        .count();
    values.retain(|value| !matches!(value, AbstractValue::Dict(entries) if entries.is_empty()));
    let operand_count = operand_count - dropped_empty_literals;
    // Each identity-bearing operand's splice rows tolerate Helm-falsy
    // inputs: the strict map contract rides the operand's own fail
    // implication, not the merged value's render. Recorded even when the
    // ordered-layer form below abstains — a fold site's operands carry the
    // same contract split (airflow's worker-family labels merges). An
    // operand that is ITSELF a layered merge records every layer identity:
    // a truthy non-map in any visible layer terminates the outer merge the
    // same way, and collapsing to one path would drop the member-level
    // contract (airflow's per-set labels under the merged worker context).
    for value in &values {
        if let Some(path) = value.merge_layer_identity().filter(|path| !path.is_empty()) {
            effects.merge_operand_paths.insert(path);
        } else if let AbstractValue::MergedLayers(layers) = value {
            for layer in layers {
                if let Some(path) = layer.merge_layer_identity().filter(|path| !path.is_empty()) {
                    effects.merge_operand_paths.insert(path);
                }
            }
        }
    }
    if let Some(layers) = merge_layer_order(function, operand_count, &values) {
        return EvalResult::with_effects(Some(AbstractValue::MergedLayers(layers)), effects);
    }
    EvalResult::with_effects(AbstractValue::merge_all(values), effects)
}

/// Whether the expression IS the shared values root (`$.Values` or
/// `.Values` at document scope), not a copy or a subtree.
fn expr_is_direct_values_root(expr: &TemplateExpr) -> bool {
    match expr.deparen() {
        TemplateExpr::Field(path) => path.as_slice() == ["Values"],
        TemplateExpr::Selector { operand, path } => {
            path.as_slice() == ["Values"]
                && matches!(operand.as_ref(), TemplateExpr::Variable(name) if name.is_empty())
        }
        _ => false,
    }
}

/// The merge operands as ordered layers, highest precedence first, when
/// every operand carries a distinct values-backed identity. Sprig's `merge`
/// keeps the FIRST occurrence of a key across its arguments while
/// `mergeOverwrite` keeps the LAST; any operand without a single identity
/// (a literal dict, a multi-path fallback) abstains to the unordered fold.
fn merge_layer_order(
    function: &str,
    operand_count: usize,
    values: &[AbstractValue],
) -> Option<Vec<AbstractValue>> {
    if values.len() < 2 || values.len() != operand_count {
        return None;
    }
    let identities = values
        .iter()
        .map(|value| value.unique_path().filter(|path| !path.is_empty()))
        .collect::<Option<Vec<_>>>()?;
    let distinct: BTreeSet<&String> = identities.iter().collect();
    if distinct.len() != identities.len() {
        return None;
    }
    let mut layers = values.to_vec();
    if function.contains("Overwrite") {
        layers.reverse();
    }
    Some(layers)
}