Skip to main content

rustev_core/
ops.rs

1//! The closed exact-operator registries `rustev.exact/1` (spec 002, 3.8) and
2//! `rustev.exact/2` (spec 032, 3.5 and 3.6), which adds `join_keyed@1` and
3//! `merge_fields@1` with every `rustev.exact/1` operator unchanged.
4//!
5//! An operator is named with a version. Changing what an operator means is a
6//! new version, never an edit (E-06). Each operator's arguments are decoded
7//! strictly against its own schema.
8
9use std::collections::{BTreeMap, BTreeSet};
10
11use rustev_contract::decimal::Decimal;
12use rustev_contract::definition::{Expr, Literal, Predicate, ReasonKind};
13use rustev_contract::judgment::{Excluded, Filtered, RankEntry, Ranking, Shortlist, Unresolved};
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Serialize};
16use serde_json::Value as Json;
17
18use crate::expr::{
19    Fault, Ref, Scope, StepTy, TyEnv, eval_expr, eval_predicate, eval_ref, expr_refs,
20    expr_structure, predicate_refs, predicate_structure, ref_ty, type_expr, type_predicate,
21};
22use crate::sem::{SemInstances, SemKind, SemValue};
23use crate::value::{JoinMatch, Ty, Value};
24
25/// Every registered `(name, version)`.
26pub const REGISTRY: &[(&str, u32)] = &[
27    ("count_where", 1),
28    ("window_filter", 1),
29    ("extremum", 1),
30    ("timestamp_diff", 1),
31    ("compare", 1),
32    ("arith", 1),
33    ("fx_convert", 1),
34    ("member_of", 1),
35    ("field_presence", 1),
36    ("filter_with_reasons", 1),
37    ("top_k", 1),
38    ("weighted_rank", 1),
39];
40
41/// Operators `rustev.exact/2` adds (spec 032, 3.1.1).
42pub const REGISTRY_V2_ADDS: &[(&str, u32)] =
43    &[("join_keyed", 1), ("merge_fields", 1), ("compose_key", 1)];
44
45pub fn is_registered(op: &str, version: u32) -> bool {
46    REGISTRY.iter().any(|(n, v)| *n == op && *v == version)
47}
48
49/// Whether `(op, version)` is in `rustev.exact/2`.
50pub fn is_registered_v2(op: &str, version: u32) -> bool {
51    is_registered(op, version)
52        || REGISTRY_V2_ADDS
53            .iter()
54            .any(|(n, v)| *n == op && *v == version)
55}
56
57/// A bounded constructed key (spec 036, 3.7).
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct ComposeKey {
61    pub parts: Vec<KeyPart>,
62    pub separator: String,
63}
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65#[serde(deny_unknown_fields)]
66pub struct KeyPart {
67    pub value: Expr,
68    pub normalize: KeyNormalization,
69}
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum KeyNormalization {
73    Exact,
74    AsciiToken,
75}
76impl ComposeKey {
77    fn eval(&self, scope: &Scope<'_>) -> Result<Value, Fault> {
78        let mut parts = Vec::new();
79        for p in &self.parts {
80            let text = match eval_expr(&p.value, scope)? {
81                Value::Text(s) | Value::Enum(s) => s,
82                Value::Integer(n) => n.to_string(),
83                _ => return Err(Fault::Invalid("compose_key part type".into())),
84            };
85            // Spec 036 3.7.2: trim whitespace only and collapse runs of
86            // whitespace, `-` and `_` into one `-`; a leading or trailing `-`
87            // is in `[a-z0-9-]` and stays, since nothing is stripped silently.
88            let text = if p.normalize == KeyNormalization::AsciiToken {
89                let mut out = String::new();
90                for b in text.trim_matches(|c: char| c.is_ascii_whitespace()).bytes() {
91                    let b = b.to_ascii_lowercase();
92                    if b.is_ascii_whitespace() || b == b'-' || b == b'_' {
93                        if !out.ends_with('-') {
94                            out.push('-');
95                        }
96                    } else if b.is_ascii_lowercase() || b.is_ascii_digit() {
97                        out.push(char::from(b));
98                    } else {
99                        return Err(Fault::Invalid(
100                            "compose_key invalid ascii_token byte".into(),
101                        ));
102                    }
103                }
104                out
105            } else {
106                text
107            };
108            if text.is_empty() || text.contains(&self.separator) {
109                return Err(Fault::Invalid(
110                    "compose_key empty part or separator in part".into(),
111                ));
112            }
113            parts.push(text);
114        }
115        let key = parts.join(&self.separator);
116        if key.len() > 512 {
117            return Err(Fault::Invalid("compose_key exceeds 512 bytes".into()));
118        }
119        Ok(Value::Text(key))
120    }
121}
122
123/// A typed keyed join (spec 032, 3.5).
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct JoinKeyed {
127    /// A list of records, or a list of ids.
128    pub left: String,
129    /// `id` for a list of ids, or a text or enum item field.
130    pub key: String,
131    /// A map.
132    pub right: String,
133}
134
135/// A typed per-field merge (spec 032, 3.6). There is no default rule.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[serde(deny_unknown_fields)]
138pub struct MergeFields {
139    pub base: String,
140    pub overlay: String,
141    pub rules: Vec<FieldRule>,
142    /// Evaluated over the merged record's fields (spec 032, 3.6.3).
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub present_when: Option<rustev_contract::grade::PresentWhen>,
145}
146
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
148#[serde(deny_unknown_fields)]
149pub struct FieldRule {
150    pub field: String,
151    pub rule: MergeRule,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case", deny_unknown_fields)]
156pub enum MergeRule {
157    OverlayOnly,
158    BaseOnly,
159    OverlayElseBaseIfGradeAtLeast {
160        grade: rustev_contract::grade::Grade,
161    },
162}
163
164impl MergeRule {
165    pub fn name(&self) -> &'static str {
166        match self {
167            MergeRule::OverlayOnly => "overlay_only",
168            MergeRule::BaseOnly => "base_only",
169            MergeRule::OverlayElseBaseIfGradeAtLeast { .. } => {
170                "overlay_else_base_if_grade_at_least"
171            }
172        }
173    }
174
175    pub fn reads_base(&self) -> bool {
176        !matches!(self, MergeRule::OverlayOnly)
177    }
178
179    pub fn reads_overlay(&self) -> bool {
180        !matches!(self, MergeRule::BaseOnly)
181    }
182}
183
184#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185#[serde(deny_unknown_fields)]
186pub struct CountWhere {
187    pub list: String,
188    pub predicate: Predicate,
189}
190
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct WindowFilter {
194    pub list: String,
195    pub field: String,
196    pub within_ms: u64,
197    pub predicate: Predicate,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202pub enum Which {
203    Min,
204    Max,
205}
206
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
208#[serde(deny_unknown_fields)]
209pub struct Extremum {
210    pub list: String,
211    pub field: String,
212    pub which: Which,
213}
214
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
216#[serde(deny_unknown_fields)]
217pub struct TimestampDiff {
218    pub later: Expr,
219    pub earlier: Expr,
220    pub unit_ms: u64,
221}
222
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct Compare {
226    pub predicate: Predicate,
227}
228
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230#[serde(deny_unknown_fields)]
231pub struct Arith {
232    pub expr: Expr,
233}
234
235#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237pub struct FxConvert {
238    pub amount: Expr,
239    pub from: Expr,
240    pub to: Expr,
241    pub rates: String,
242    pub scale: u32,
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct MemberOf {
248    pub value: Expr,
249    pub set: Vec<Literal>,
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct FieldPresence {
255    /// `input:<name>` references, in the order they are reported.
256    pub inputs: Vec<String>,
257}
258
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260#[serde(deny_unknown_fields)]
261pub struct NamedRule {
262    pub name: String,
263    pub predicate: Predicate,
264}
265
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267#[serde(deny_unknown_fields)]
268pub struct FilterWithReasons {
269    pub list: String,
270    pub id_field: String,
271    pub rules: Vec<NamedRule>,
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum Direction {
277    Ascending,
278    Descending,
279}
280
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282#[serde(deny_unknown_fields)]
283pub struct TopK {
284    pub list: String,
285    pub id_field: String,
286    /// `step:<id>` of a filter result; only its eligible ids are ranked.
287    pub among: String,
288    pub key: Expr,
289    pub direction: Direction,
290    pub k: u64,
291}
292
293#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
294#[serde(deny_unknown_fields)]
295pub struct WeightTable {
296    /// `input:<name>`: a list of records.
297    pub list: String,
298    pub key_field: String,
299    pub class_field: String,
300    pub table: Vec<ClassWeight>,
301}
302
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct ClassWeight {
306    pub class: String,
307    pub weight: Decimal,
308}
309
310#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case", deny_unknown_fields)]
312pub enum Source {
313    /// Weighted mean of a two-index proposition's `true` mass over the other
314    /// index, weights by class; zero items give 0.
315    PropositionMean {
316        step: String,
317        candidate_bind: String,
318        weights: WeightTable,
319    },
320    /// A one-index rubric's expectation divided by its highest level index.
321    RubricExpectation { step: String },
322    /// `1 - i / (n - 1)` over the candidate order; 1 when `n = 1`.
323    ShortlistPosition,
324}
325
326#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327#[serde(deny_unknown_fields)]
328pub struct Component {
329    pub name: String,
330    pub weight: Decimal,
331    pub source: Source,
332}
333
334#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
335#[serde(deny_unknown_fields)]
336pub struct WeightedRank {
337    /// `step:<id>` of a shortlist or filter result, in the order ranked.
338    pub candidates: String,
339    pub components: Vec<Component>,
340}
341
342/// Decoded operator arguments.
343#[derive(Debug, Clone, PartialEq)]
344pub enum OpArgs {
345    CountWhere(CountWhere),
346    WindowFilter(WindowFilter),
347    Extremum(Extremum),
348    TimestampDiff(TimestampDiff),
349    Compare(Compare),
350    Arith(Arith),
351    FxConvert(FxConvert),
352    MemberOf(MemberOf),
353    FieldPresence(FieldPresence),
354    FilterWithReasons(FilterWithReasons),
355    TopK(TopK),
356    WeightedRank(WeightedRank),
357    JoinKeyed(JoinKeyed),
358    MergeFields(MergeFields),
359    ComposeKey(ComposeKey),
360}
361
362fn de<T: DeserializeOwned>(args: &Json) -> Result<T, String> {
363    serde_json::from_value(args.clone()).map_err(|e| e.to_string())
364}
365
366impl OpArgs {
367    /// Registry name and version.
368    pub fn op(&self) -> (&'static str, u32) {
369        match self {
370            OpArgs::CountWhere(_) => ("count_where", 1),
371            OpArgs::WindowFilter(_) => ("window_filter", 1),
372            OpArgs::Extremum(_) => ("extremum", 1),
373            OpArgs::TimestampDiff(_) => ("timestamp_diff", 1),
374            OpArgs::Compare(_) => ("compare", 1),
375            OpArgs::Arith(_) => ("arith", 1),
376            OpArgs::FxConvert(_) => ("fx_convert", 1),
377            OpArgs::MemberOf(_) => ("member_of", 1),
378            OpArgs::FieldPresence(_) => ("field_presence", 1),
379            OpArgs::FilterWithReasons(_) => ("filter_with_reasons", 1),
380            OpArgs::TopK(_) => ("top_k", 1),
381            OpArgs::WeightedRank(_) => ("weighted_rank", 1),
382            OpArgs::JoinKeyed(_) => ("join_keyed", 1),
383            OpArgs::MergeFields(_) => ("merge_fields", 1),
384            OpArgs::ComposeKey(_) => ("compose_key", 1),
385        }
386    }
387
388    /// The arguments as the definition document carries them.
389    pub fn to_json(&self) -> Json {
390        let v = match self {
391            OpArgs::CountWhere(a) => serde_json::to_value(a),
392            OpArgs::WindowFilter(a) => serde_json::to_value(a),
393            OpArgs::Extremum(a) => serde_json::to_value(a),
394            OpArgs::TimestampDiff(a) => serde_json::to_value(a),
395            OpArgs::Compare(a) => serde_json::to_value(a),
396            OpArgs::Arith(a) => serde_json::to_value(a),
397            OpArgs::FxConvert(a) => serde_json::to_value(a),
398            OpArgs::MemberOf(a) => serde_json::to_value(a),
399            OpArgs::FieldPresence(a) => serde_json::to_value(a),
400            OpArgs::FilterWithReasons(a) => serde_json::to_value(a),
401            OpArgs::TopK(a) => serde_json::to_value(a),
402            OpArgs::WeightedRank(a) => serde_json::to_value(a),
403            OpArgs::JoinKeyed(a) => serde_json::to_value(a),
404            OpArgs::MergeFields(a) => serde_json::to_value(a),
405            OpArgs::ComposeKey(a) => serde_json::to_value(a),
406        };
407        // Every argument type serializes to a JSON object.
408        v.unwrap_or(Json::Null)
409    }
410}
411
412/// A field name an operator argument carries, which in version 2 is
413/// non-empty and holds no '/', '.' or '*' (spec 032, 3.4.4).
414fn plain_field_name(what: &str, name: &str) -> Result<(), String> {
415    if name.is_empty() {
416        return Err(format!("{what} is empty"));
417    }
418    if name.contains(['/', '.', '*']) {
419        return Err(format!(
420            "{what} {name:?} is not a field name: it holds '/', '.' or '*'"
421        ));
422    }
423    Ok(())
424}
425
426/// Decode the arguments of a registered operator; `None` when `(op,
427/// version)` is not registered (refusal category 2, not a parse failure).
428pub fn decode(op: &str, version: u32, args: &Json) -> Option<Result<OpArgs, String>> {
429    if !is_registered(op, version) {
430        return None;
431    }
432    decode_any(op, args)
433}
434
435/// Decode the arguments of an operator of `rustev.exact/2`.
436pub fn decode_v2(op: &str, version: u32, args: &Json) -> Option<Result<OpArgs, String>> {
437    if !is_registered_v2(op, version) {
438        return None;
439    }
440    match op {
441        "compose_key" => Some(de(args).map(OpArgs::ComposeKey)),
442        "join_keyed" => Some(de(args).map(OpArgs::JoinKeyed)),
443        "merge_fields" => Some(de(args).map(OpArgs::MergeFields)),
444        _ => decode_any(op, args),
445    }
446}
447
448fn decode_any(op: &str, args: &Json) -> Option<Result<OpArgs, String>> {
449    Some(match op {
450        "count_where" => de(args).map(OpArgs::CountWhere),
451        "window_filter" => de(args).map(OpArgs::WindowFilter),
452        "extremum" => de(args).map(OpArgs::Extremum),
453        "timestamp_diff" => de(args).map(OpArgs::TimestampDiff),
454        "compare" => de(args).map(OpArgs::Compare),
455        "arith" => de(args).map(OpArgs::Arith),
456        "fx_convert" => de(args).map(OpArgs::FxConvert),
457        "member_of" => de(args).map(OpArgs::MemberOf),
458        "field_presence" => de(args).map(OpArgs::FieldPresence),
459        "filter_with_reasons" => de(args).map(OpArgs::FilterWithReasons),
460        "top_k" => de(args).map(OpArgs::TopK),
461        _ => de(args).map(OpArgs::WeightedRank),
462    })
463}
464
465fn has_fx_expr(e: &Expr) -> bool {
466    match e {
467        Expr::Fx { .. } => true,
468        Expr::Ref(_) | Expr::Lit(_) => false,
469        Expr::Add { left, right }
470        | Expr::Sub { left, right }
471        | Expr::Mul { left, right }
472        | Expr::Div { left, right } => has_fx_expr(left) || has_fx_expr(right),
473        Expr::Round { value, .. } | Expr::Len(value) | Expr::ToDecimal(value) => has_fx_expr(value),
474        Expr::Graded { .. } => false,
475    }
476}
477
478fn has_fx_pred(p: &Predicate) -> bool {
479    match p {
480        Predicate::Cmp { left, right, .. }
481        | Predicate::Under {
482            value: left,
483            ancestor: right,
484            ..
485        } => has_fx_expr(left) || has_fx_expr(right),
486        Predicate::All(ps) | Predicate::Any(ps) => ps.iter().any(has_fx_pred),
487        Predicate::Not(p) => has_fx_pred(p),
488        Predicate::Member { value, .. } | Predicate::MemberRef { value, .. } => has_fx_expr(value),
489        Predicate::Present(_) | Predicate::IsConstructed { .. } => false,
490    }
491}
492
493/// Keep only `input:` and `step:` references (item references and `now` are
494/// not dependencies).
495fn deps_only(refs: Vec<String>) -> Vec<String> {
496    let mut seen = BTreeSet::new();
497    refs.into_iter()
498        .filter(|r| r.starts_with("input:") || r.starts_with("step:"))
499        .map(|r| crate::expr::base_ref(&r))
500        .filter(|r| seen.insert(r.clone()))
501        .collect()
502}
503
504impl OpArgs {
505    /// References this step reads, in argument order (spec 002, 3.10.4).
506    pub fn refs(&self) -> Vec<String> {
507        let mut out = Vec::new();
508        match self {
509            OpArgs::ComposeKey(a) => {
510                for p in &a.parts {
511                    expr_refs(&p.value, &mut out);
512                }
513            }
514            OpArgs::CountWhere(a) => {
515                out.push(a.list.clone());
516                predicate_refs(&a.predicate, &mut out);
517            }
518            OpArgs::WindowFilter(a) => {
519                out.push(a.list.clone());
520                predicate_refs(&a.predicate, &mut out);
521            }
522            OpArgs::Extremum(a) => out.push(a.list.clone()),
523            OpArgs::TimestampDiff(a) => {
524                expr_refs(&a.later, &mut out);
525                expr_refs(&a.earlier, &mut out);
526            }
527            OpArgs::Compare(a) => predicate_refs(&a.predicate, &mut out),
528            OpArgs::Arith(a) => expr_refs(&a.expr, &mut out),
529            OpArgs::FxConvert(a) => {
530                expr_refs(&a.amount, &mut out);
531                expr_refs(&a.from, &mut out);
532                expr_refs(&a.to, &mut out);
533                out.push(a.rates.clone());
534            }
535            OpArgs::MemberOf(a) => expr_refs(&a.value, &mut out),
536            OpArgs::FieldPresence(a) => out.extend(a.inputs.iter().cloned()),
537            OpArgs::FilterWithReasons(a) => {
538                out.push(a.list.clone());
539                a.rules
540                    .iter()
541                    .for_each(|r| predicate_refs(&r.predicate, &mut out));
542            }
543            OpArgs::TopK(a) => {
544                out.push(a.list.clone());
545                out.push(a.among.clone());
546                expr_refs(&a.key, &mut out);
547            }
548            OpArgs::WeightedRank(a) => {
549                out.push(a.candidates.clone());
550                for c in &a.components {
551                    match &c.source {
552                        Source::PropositionMean { step, weights, .. } => {
553                            out.push(step.clone());
554                            out.push(weights.list.clone());
555                        }
556                        Source::RubricExpectation { step } => out.push(step.clone()),
557                        Source::ShortlistPosition => {}
558                    }
559                }
560            }
561            OpArgs::JoinKeyed(a) => {
562                out.push(a.left.clone());
563                out.push(a.right.clone());
564            }
565            OpArgs::MergeFields(a) => {
566                out.push(a.base.clone());
567                out.push(a.overlay.clone());
568            }
569        }
570        deps_only(out)
571    }
572
573    /// Every raw reference string, including item references and `now`,
574    /// for the structure phase.
575    pub fn all_ref_strings(&self) -> Vec<String> {
576        let mut out = Vec::new();
577        match self {
578            OpArgs::CountWhere(a) => {
579                out.push(a.list.clone());
580                predicate_refs(&a.predicate, &mut out);
581            }
582            OpArgs::WindowFilter(a) => {
583                out.push(a.list.clone());
584                predicate_refs(&a.predicate, &mut out);
585            }
586            OpArgs::FilterWithReasons(a) => {
587                out.push(a.list.clone());
588                a.rules
589                    .iter()
590                    .for_each(|r| predicate_refs(&r.predicate, &mut out));
591            }
592            OpArgs::TopK(a) => {
593                out.push(a.list.clone());
594                out.push(a.among.clone());
595                expr_refs(&a.key, &mut out);
596            }
597            _ => out = self.refs(),
598        }
599        out
600    }
601
602    /// Whether the arguments use a predicate or reference form of
603    /// `rustev.exact/2` (spec 032, 3.1.3).
604    pub fn uses_v2(&self) -> bool {
605        use crate::expr::{expr_uses_v2, predicate_uses_v2};
606        match self {
607            OpArgs::CountWhere(a) => predicate_uses_v2(&a.predicate),
608            OpArgs::WindowFilter(a) => predicate_uses_v2(&a.predicate),
609            OpArgs::Extremum(_) | OpArgs::FieldPresence(_) | OpArgs::WeightedRank(_) => false,
610            OpArgs::JoinKeyed(_) | OpArgs::MergeFields(_) | OpArgs::ComposeKey(_) => true,
611            OpArgs::TimestampDiff(a) => expr_uses_v2(&a.later) || expr_uses_v2(&a.earlier),
612            OpArgs::Compare(a) => predicate_uses_v2(&a.predicate),
613            OpArgs::Arith(a) => expr_uses_v2(&a.expr),
614            OpArgs::FxConvert(a) => {
615                expr_uses_v2(&a.amount) || expr_uses_v2(&a.from) || expr_uses_v2(&a.to)
616            }
617            OpArgs::MemberOf(a) => expr_uses_v2(&a.value),
618            OpArgs::FilterWithReasons(a) => a.rules.iter().any(|r| predicate_uses_v2(&r.predicate)),
619            OpArgs::TopK(a) => expr_uses_v2(&a.key),
620        }
621    }
622
623    /// Structural checks (compile phase b).
624    pub fn structure(&self) -> Result<(), String> {
625        match self {
626            OpArgs::ComposeKey(a) => {
627                if !(2..=8).contains(&a.parts.len())
628                    || ![":", "/", "|", "."].contains(&a.separator.as_str())
629                {
630                    return Err("compose_key needs 2..=8 parts and separator : / | .".into());
631                }
632                a.parts.iter().try_for_each(|p| expr_structure(&p.value))
633            }
634            OpArgs::CountWhere(a) => predicate_structure(&a.predicate),
635            OpArgs::WindowFilter(a) => predicate_structure(&a.predicate),
636            OpArgs::Extremum(_) => Ok(()),
637            OpArgs::TimestampDiff(a) => {
638                if a.unit_ms == 0 {
639                    return Err("unit_ms must be positive".into());
640                }
641                expr_structure(&a.later)?;
642                expr_structure(&a.earlier)
643            }
644            OpArgs::Compare(a) => predicate_structure(&a.predicate),
645            OpArgs::Arith(a) => expr_structure(&a.expr),
646            OpArgs::FxConvert(a) => {
647                if a.scale > 9 {
648                    return Err(format!("scale {} exceeds 9", a.scale));
649                }
650                expr_structure(&a.amount)
651            }
652            OpArgs::MemberOf(a) => {
653                if a.set.is_empty() {
654                    return Err("member set is empty".into());
655                }
656                expr_structure(&a.value)
657            }
658            OpArgs::FieldPresence(a) => {
659                if a.inputs.is_empty() {
660                    return Err("field_presence names no input".into());
661                }
662                a.inputs.iter().try_for_each(|r| match Ref::parse(r)? {
663                    Ref::Input(_, p) if p.is_empty() => Ok(()),
664                    _ => Err(format!("field_presence takes inputs, not {r:?}")),
665                })
666            }
667            OpArgs::FilterWithReasons(a) => {
668                let mut names = BTreeSet::new();
669                for r in &a.rules {
670                    if !names.insert(&r.name) {
671                        return Err(format!("duplicate rule name {:?}", r.name));
672                    }
673                    predicate_structure(&r.predicate)?;
674                }
675                Ok(())
676            }
677            OpArgs::TopK(a) => {
678                if a.k == 0 {
679                    return Err("k must be positive".into());
680                }
681                expr_structure(&a.key)
682            }
683            OpArgs::WeightedRank(a) => {
684                let mut names = BTreeSet::new();
685                for c in &a.components {
686                    if !names.insert(&c.name) {
687                        return Err(format!("duplicate component {:?}", c.name));
688                    }
689                    if c.weight < Decimal::ZERO {
690                        return Err(format!("negative weight for {:?}", c.name));
691                    }
692                }
693                if a.components.is_empty() {
694                    return Err("weighted_rank has no component".into());
695                }
696                Ok(())
697            }
698            OpArgs::JoinKeyed(a) => {
699                if a.key.is_empty() {
700                    return Err("join_keyed names no key".into());
701                }
702                plain_field_name("join_keyed key", &a.key)
703            }
704            OpArgs::MergeFields(a) => {
705                let mut fields = BTreeSet::new();
706                for r in &a.rules {
707                    plain_field_name("merge rule field", &r.field)?;
708                    if !fields.insert(&r.field) {
709                        return Err(format!("merge rule names {:?} twice", r.field));
710                    }
711                }
712                if let Some(p) = &a.present_when {
713                    crate::quality::present_when_structure(p)?;
714                }
715                Ok(())
716            }
717        }
718    }
719
720    /// Reasons this operator itself can produce, beyond its dependencies'.
721    pub fn own_reasons(&self) -> BTreeSet<ReasonKind> {
722        let mut r = BTreeSet::new();
723        let fx = match self {
724            OpArgs::CountWhere(a) => has_fx_pred(&a.predicate),
725            OpArgs::WindowFilter(a) => has_fx_pred(&a.predicate),
726            OpArgs::Compare(a) => has_fx_pred(&a.predicate),
727            OpArgs::Arith(a) => has_fx_expr(&a.expr),
728            OpArgs::ComposeKey(a) => a.parts.iter().any(|p| has_fx_expr(&p.value)),
729            OpArgs::MemberOf(a) => has_fx_expr(&a.value),
730            OpArgs::FxConvert(_) => true,
731            _ => false,
732        };
733        match self {
734            OpArgs::Extremum(_)
735            | OpArgs::FieldPresence(_)
736            | OpArgs::WeightedRank(_)
737            | OpArgs::MergeFields(_) => {}
738            // `join_keyed@1` included: duplicate left ids are
739            // `invalid_input` (spec 032, 3.5.3).
740            _ => {
741                r.insert(ReasonKind::InvalidInput);
742            }
743        }
744        if fx {
745            r.insert(ReasonKind::MissingEvidence);
746            r.insert(ReasonKind::Conflict);
747        }
748        r
749    }
750
751    /// The output type, or a kind mismatch (compile phase e).
752    pub fn type_check(&self, env: &TyEnv<'_>) -> Result<Ty, String> {
753        match self {
754            OpArgs::ComposeKey(a) => {
755                for p in &a.parts {
756                    if !matches!(
757                        type_expr(&p.value, env)?,
758                        Ty::Text { .. } | Ty::Integer | Ty::Enum(_)
759                    ) {
760                        return Err("compose_key parts must be text, integer or enum".into());
761                    }
762                }
763                Ok(Ty::Text { max_bytes: 512 })
764            }
765            OpArgs::CountWhere(a) => {
766                let item = list_item(&a.list, env)?;
767                type_predicate(&a.predicate, &with_item(env, &item))?;
768                Ok(Ty::Integer)
769            }
770            OpArgs::WindowFilter(a) => {
771                let (item, max) = list_item_max(&a.list, env)?;
772                match record_field(&item, &a.field)? {
773                    Ty::Timestamp => {}
774                    t => {
775                        return Err(format!(
776                            "window field {:?} is {}, not a timestamp",
777                            a.field,
778                            t.name()
779                        ));
780                    }
781                }
782                type_predicate(&a.predicate, &with_item(env, &item))?;
783                Ok(Ty::List {
784                    item: Box::new(item),
785                    max,
786                })
787            }
788            OpArgs::Extremum(a) => {
789                let item = list_item(&a.list, env)?;
790                let t = record_field(&item, &a.field)?;
791                if !t.is_orderable() {
792                    return Err(format!("{} has no order", t.name()));
793                }
794                Ok(Ty::Maybe(Box::new(t)))
795            }
796            OpArgs::TimestampDiff(a) => {
797                let mut maybe = false;
798                for e in [&a.later, &a.earlier] {
799                    match type_expr(e, env)? {
800                        Ty::Timestamp => {}
801                        Ty::Maybe(t) if *t == Ty::Timestamp => maybe = true,
802                        t => return Err(format!("timestamp_diff of {}", t.name())),
803                    }
804                }
805                Ok(if maybe {
806                    Ty::Maybe(Box::new(Ty::Integer))
807                } else {
808                    Ty::Integer
809                })
810            }
811            OpArgs::Compare(a) => type_predicate(&a.predicate, env).map(|_| Ty::Bool),
812            OpArgs::Arith(a) => match type_expr(&a.expr, env)? {
813                t @ (Ty::Integer | Ty::Decimal) => Ok(t),
814                t => Err(format!("arith yields {}, not a number", t.name())),
815            },
816            OpArgs::FxConvert(a) => {
817                let e = Expr::Fx {
818                    amount: Box::new(a.amount.clone()),
819                    from: Box::new(a.from.clone()),
820                    to: Box::new(a.to.clone()),
821                    rates: a.rates.clone(),
822                    scale: a.scale,
823                };
824                type_expr(&e, env)
825            }
826            OpArgs::MemberOf(a) => {
827                let p = Predicate::Member {
828                    value: a.value.clone(),
829                    set: a.set.clone(),
830                };
831                type_predicate(&p, env).map(|_| Ty::Bool)
832            }
833            OpArgs::FieldPresence(a) => {
834                let mut longest = 0u64;
835                for r in &a.inputs {
836                    let name = r.trim_start_matches("input:");
837                    if !env.inputs.contains_key(name) {
838                        return Err(format!("unknown input {name:?}"));
839                    }
840                    longest = longest.max(name.len() as u64);
841                }
842                Ok(Ty::List {
843                    item: Box::new(Ty::Text { max_bytes: longest }),
844                    max: a.inputs.len() as u64,
845                })
846            }
847            OpArgs::FilterWithReasons(a) => {
848                let (item, max) = list_item_max(&a.list, env)?;
849                let id_bytes = id_field_bytes(&item, &a.id_field)?;
850                let ienv = with_item(env, &item);
851                for r in &a.rules {
852                    type_predicate(&r.predicate, &ienv)?;
853                }
854                Ok(Ty::Filtered { max, id_bytes })
855            }
856            OpArgs::TopK(a) => {
857                let (item, _) = list_item_max(&a.list, env)?;
858                let id_bytes = id_field_bytes(&item, &a.id_field)?;
859                let among_max = match ref_ty(&a.among, env)? {
860                    Ty::Filtered { max, .. } => max,
861                    t => return Err(format!("top_k among {}, not a filter result", t.name())),
862                };
863                let kt = type_expr(&a.key, &with_item(env, &item))?;
864                if !kt.is_orderable() {
865                    return Err(format!("top_k key is {}, which has no order", kt.name()));
866                }
867                Ok(Ty::Shortlist {
868                    max: a.k.min(among_max),
869                    id_bytes,
870                })
871            }
872            OpArgs::WeightedRank(a) => {
873                let max = match ref_ty(&a.candidates, env)? {
874                    Ty::Shortlist { max, .. } | Ty::Filtered { max, .. } => max,
875                    t => {
876                        return Err(format!(
877                            "weighted_rank over {}, not a shortlist or filter",
878                            t.name()
879                        ));
880                    }
881                };
882                for c in &a.components {
883                    match &c.source {
884                        Source::PropositionMean {
885                            step,
886                            candidate_bind,
887                            weights,
888                        } => {
889                            match semantic(step, env)? {
890                                (k, binds)
891                                    if k.has_mass()
892                                        && binds.len() == 2
893                                        && binds.contains(candidate_bind) => {}
894                                (k, binds) => {
895                                    return Err(format!(
896                                        "{step} is {} over {} index(es); proposition_mean needs mass over two, one bound as {candidate_bind:?}",
897                                        k.name(),
898                                        binds.len()
899                                    ));
900                                }
901                            }
902                            let item = list_item(&weights.list, env)?;
903                            id_field_bytes(&item, &weights.key_field)?;
904                            id_field_bytes(&item, &weights.class_field)?;
905                        }
906                        Source::RubricExpectation { step } => match semantic(step, env)? {
907                            (SemKind::Ordinal(_), binds) if binds.len() == 1 => {}
908                            (k, _) => {
909                                return Err(format!(
910                                    "{step} is {}; rubric_expectation needs an ordinal level over one index",
911                                    k.name()
912                                ));
913                            }
914                        },
915                        Source::ShortlistPosition => {}
916                    }
917                }
918                Ok(Ty::Ranking { max })
919            }
920            OpArgs::JoinKeyed(a) => {
921                let (item, max) = list_item_max(&a.left, env)?;
922                let id_bytes = if a.key == "id" {
923                    match &item {
924                        Ty::Text { max_bytes } => *max_bytes,
925                        Ty::Enum(o) => o.iter().map(|s| s.len() as u64).max().unwrap_or(0),
926                        _ => id_field_bytes(&item, &a.key)?,
927                    }
928                } else {
929                    id_field_bytes(&item, &a.key)?
930                };
931                match ref_ty(&a.right, env)? {
932                    Ty::Map { value, .. } => Ok(Ty::Joined {
933                        value,
934                        max,
935                        id_bytes,
936                    }),
937                    t => Err(format!("join_keyed right is {}, not a map", t.name())),
938                }
939            }
940            OpArgs::MergeFields(a) => {
941                let (base, overlay, list) = merge_sides(a, env)?;
942                let mut out = Vec::new();
943                for r in &a.rules {
944                    let b = record_field(&base, &r.field).ok();
945                    let o = record_field(&overlay, &r.field).ok();
946                    let t = match (&r.rule, b, o) {
947                        (MergeRule::OverlayOnly, _, Some(o)) => o,
948                        (MergeRule::BaseOnly, Some(b), _) => b,
949                        (MergeRule::OverlayElseBaseIfGradeAtLeast { .. }, Some(b), Some(o)) => {
950                            if !unwrap_nullable(&b).same_shape(unwrap_nullable(&o)) {
951                                return Err(format!(
952                                    "field {:?} is {} in the base and {} in the overlay",
953                                    r.field,
954                                    unwrap_nullable(&b).name(),
955                                    unwrap_nullable(&o).name()
956                                ));
957                            }
958                            o
959                        }
960                        _ => return Err(format!("no side of {:?} carries it", r.field)),
961                    };
962                    // A merged field can be absent, so reading it yields its
963                    // type or `missing_evidence`.
964                    let t = match t {
965                        Ty::Nullable(t) => Ty::Nullable(t),
966                        t => Ty::Nullable(Box::new(t)),
967                    };
968                    out.push((r.field.clone(), t));
969                }
970                out.sort_by(|(a, _), (b, _)| a.cmp(b));
971                // The output's presence predicate names only its own fields,
972                // all nullable after merging (spec 032, 3.6.3 and 3.4.2).
973                if let Some(p) = &a.present_when {
974                    let mut named = Vec::new();
975                    p.fields(&mut named);
976                    if let Some(n) = named.iter().find(|n| !out.iter().any(|(f, _)| f == *n)) {
977                        return Err(format!(
978                            "present_when names {n:?}, which is not a merged field"
979                        ));
980                    }
981                }
982                let rec = Ty::Record(out);
983                Ok(match list {
984                    Some(max) => Ty::List {
985                        item: Box::new(rec),
986                        max,
987                    },
988                    None => rec,
989                })
990            }
991        }
992    }
993
994    /// The category 11 refusals of `merge_fields@1` (spec 032, 3.6.1): a
995    /// field of either side with no rule, or a rule naming a field missing
996    /// from a side it reads.
997    pub fn merge_rule_error(&self, env: &TyEnv<'_>) -> Option<String> {
998        let OpArgs::MergeFields(a) = self else {
999            return None;
1000        };
1001        let (base, overlay, _) = merge_sides(a, env).ok()?;
1002        let names = |t: &Ty| -> Vec<String> {
1003            match t {
1004                Ty::Record(f) => f.iter().map(|(n, _)| n.clone()).collect(),
1005                _ => vec![],
1006            }
1007        };
1008        let (bn, on) = (names(&base), names(&overlay));
1009        for r in &a.rules {
1010            if r.rule.reads_base() && !bn.contains(&r.field) {
1011                return Some(format!(
1012                    "{} reads {:?}, which the base record lacks",
1013                    r.rule.name(),
1014                    r.field
1015                ));
1016            }
1017            if r.rule.reads_overlay() && !on.contains(&r.field) {
1018                return Some(format!(
1019                    "{} reads {:?}, which the overlay record lacks",
1020                    r.rule.name(),
1021                    r.field
1022                ));
1023            }
1024        }
1025        // Every field of either side without a rule, each once, in name order.
1026        let missing: BTreeSet<&String> = bn
1027            .iter()
1028            .chain(on.iter())
1029            .filter(|f| !a.rules.iter().any(|r| &r.field == *f))
1030            .collect();
1031        (!missing.is_empty()).then(|| {
1032            let each: Vec<String> = missing
1033                .iter()
1034                .map(|f| format!("field {f:?} has no merge rule"))
1035                .collect();
1036            format!("{}, and there is no default", each.join("; "))
1037        })
1038    }
1039}
1040
1041fn unwrap_nullable(t: &Ty) -> &Ty {
1042    match t {
1043        Ty::Nullable(t) => t,
1044        t => t,
1045    }
1046}
1047
1048/// The base and overlay record types of a merge, and the list bound when
1049/// it merges per item.
1050fn merge_sides(a: &MergeFields, env: &TyEnv<'_>) -> Result<(Ty, Ty, Option<u64>), String> {
1051    match (ref_ty(&a.base, env)?, ref_ty(&a.overlay, env)?) {
1052        (b @ Ty::Record(_), o @ Ty::Record(_)) => Ok((b, o, None)),
1053        (Ty::List { item, max }, Ty::Joined { value, .. }) => match (*item, *value) {
1054            (b @ Ty::Record(_), o @ Ty::Record(_)) => Ok((b, o, Some(max))),
1055            _ => Err("a per-item merge joins records to records".into()),
1056        },
1057        (b, o) => Err(format!(
1058            "merge_fields takes two records, or a list of records and a join over it; got {} and {}",
1059            b.name(),
1060            o.name()
1061        )),
1062    }
1063}
1064
1065fn semantic<'e>(r: &str, env: &'e TyEnv<'_>) -> Result<(SemKind, &'e Vec<String>), String> {
1066    match Ref::parse(r)? {
1067        Ref::Step(s) => match env.steps.get(&s) {
1068            Some(StepTy::Semantic(k, binds)) => Ok((*k, binds)),
1069            Some(StepTy::ModelRanking(_)) | Some(StepTy::Selection(_)) => {
1070                Err(format!("{r} is a distinct ranking value, not semantic"))
1071            }
1072            Some(StepTy::Exact(t)) => Err(format!("{r} is exact ({}), not semantic", t.name())),
1073            None => Err(format!("unknown step {s:?}")),
1074        },
1075        _ => Err(format!("{r} is not a step")),
1076    }
1077}
1078
1079fn with_item<'a>(env: &TyEnv<'a>, item: &'a Ty) -> TyEnv<'a> {
1080    TyEnv {
1081        inputs: env.inputs,
1082        steps: env.steps,
1083        item: Some(item),
1084        v2: env.v2,
1085    }
1086}
1087
1088fn list_item_max(r: &str, env: &TyEnv<'_>) -> Result<(Ty, u64), String> {
1089    match ref_ty(r, env)? {
1090        Ty::List { item, max } => Ok((*item, max)),
1091        // A join result's items, as per-item operators read them.
1092        Ty::Joined {
1093            value,
1094            max,
1095            id_bytes,
1096        } if env.v2 => Ok((Ty::join_item(&value, id_bytes), max)),
1097        t => Err(format!("{r} is {}, not a list", t.name())),
1098    }
1099}
1100
1101fn list_item(r: &str, env: &TyEnv<'_>) -> Result<Ty, String> {
1102    list_item_max(r, env).map(|(t, _)| t)
1103}
1104
1105fn record_field(item: &Ty, name: &str) -> Result<Ty, String> {
1106    match item {
1107        Ty::Record(fields) => fields
1108            .iter()
1109            .find(|(n, _)| n == name)
1110            .map(|(_, t)| t.clone())
1111            .ok_or_else(|| format!("no field {name:?}")),
1112        t => Err(format!("{} has no field {name:?}", t.name())),
1113    }
1114}
1115
1116fn id_field_bytes(item: &Ty, name: &str) -> Result<u64, String> {
1117    match record_field(item, name)? {
1118        Ty::Text { max_bytes } => Ok(max_bytes),
1119        // A merged id can be absent; an item whose id cannot be read is
1120        // refused at evaluation as any item without an id.
1121        Ty::Nullable(t) if matches!(*t, Ty::Text { .. } | Ty::Enum(_)) => {
1122            id_field_bytes(&Ty::Record(vec![(name.to_string(), *t)]), name)
1123        }
1124        Ty::Enum(o) => Ok(o.iter().map(|s| s.len() as u64).max().unwrap_or(0)),
1125        t => Err(format!("id field {name:?} is {}, not text", t.name())),
1126    }
1127}
1128
1129/// What an operator needs at evaluation time besides expression scope.
1130pub struct OpContext<'a> {
1131    pub scope: Scope<'a>,
1132    pub semantic: &'a BTreeMap<String, SemInstances>,
1133    /// Status of every declared input.
1134    pub inputs_status: &'a BTreeMap<String, Result<(), Unresolved>>,
1135    /// Input fields in this step's lineage, named by `invalid_input`.
1136    pub lineage_inputs: &'a [String],
1137    /// Each semantic step's fan-out binds, in instance-key order.
1138    pub binds: &'a BTreeMap<String, Vec<String>>,
1139}
1140
1141fn fault(f: Fault, cx: &OpContext<'_>) -> Unresolved {
1142    match f {
1143        Fault::Invalid(d) => Unresolved::invalid(cx.lineage_inputs.iter().cloned(), d),
1144        Fault::Missing(m) => Unresolved::missing([m]),
1145        Fault::Conflict(c) => Unresolved::conflict([c]),
1146        Fault::Absent(p) => Unresolved::missing([p]),
1147    }
1148}
1149
1150fn items(r: &str, cx: &OpContext<'_>) -> Result<Vec<Value>, Unresolved> {
1151    match eval_ref(r, &cx.scope) {
1152        // An operator that does not exclude absent items reads them as
1153        // missing evidence for their path (spec 032, 3.4.4).
1154        Ok(Value::List(v)) if cx.scope.v2 && v.iter().any(|i| matches!(i, Value::Absent(_))) => {
1155            Err(missing_items(r))
1156        }
1157        Ok(Value::Joined(entries)) if cx.scope.v2 => entries
1158            .iter()
1159            .map(|e| e.item().ok_or_else(|| missing_items(r)))
1160            .collect(),
1161        Ok(Value::List(v)) => Ok(v),
1162        Ok(_) => Err(Unresolved::invalid(
1163            cx.lineage_inputs.iter().cloned(),
1164            format!("{r} is not a list"),
1165        )),
1166        Err(f) => Err(fault(f, cx)),
1167    }
1168}
1169
1170fn item_scope<'a>(cx: &'a OpContext<'a>, item: &'a Value) -> Scope<'a> {
1171    Scope {
1172        constructed: cx.scope.constructed,
1173        now: cx.scope.now,
1174        inputs: cx.scope.inputs,
1175        steps: cx.scope.steps,
1176        present: cx.scope.present,
1177        item: Some(item),
1178        v2: cx.scope.v2,
1179    }
1180}
1181
1182fn get_field<'v>(item: &'v Value, name: &str) -> Option<&'v Value> {
1183    match item {
1184        Value::Record(m) => m.get(name),
1185        _ => None,
1186    }
1187}
1188
1189fn id_of(item: &Value, id_field: &str) -> Option<String> {
1190    match get_field(item, id_field) {
1191        Some(Value::Text(s) | Value::Enum(s)) => Some(s.clone()),
1192        _ => None,
1193    }
1194}
1195
1196/// Items with unique ids, or `invalid_input` on a duplicate or missing id.
1197fn keyed<'v>(
1198    list: &'v [Value],
1199    id_field: &str,
1200    cx: &OpContext<'_>,
1201) -> Result<Vec<(String, &'v Value)>, Unresolved> {
1202    let mut seen = BTreeSet::new();
1203    let mut out = Vec::with_capacity(list.len());
1204    for it in list {
1205        let id = id_of(it, id_field).ok_or_else(|| {
1206            Unresolved::invalid(
1207                cx.lineage_inputs.iter().cloned(),
1208                format!("item without {id_field:?}"),
1209            )
1210        })?;
1211        if !seen.insert(id.clone()) {
1212            return Err(Unresolved::invalid(
1213                cx.lineage_inputs.iter().cloned(),
1214                format!("duplicate id {id:?}"),
1215            ));
1216        }
1217        out.push((id, it));
1218    }
1219    Ok(out)
1220}
1221
1222/// Missing evidence for the items of `r`, named as an input or step is
1223/// named in a missing reason: without its `input:` or `step:` kind.
1224fn missing_items(r: &str) -> Unresolved {
1225    let path = r.split_once(':').map_or(r, |(_, p)| p);
1226    Unresolved::missing([format!("{path}/*")])
1227}
1228
1229/// A row a version 2 filter judges: an id and the item, or the reason it
1230/// is excluded before any rule.
1231type Row = (String, Result<Value, &'static str>);
1232
1233/// The rows a version 2 filter judges (spec 032, 3.4.4 and 3.5.4). An
1234/// absent item has no readable id; it is named by its position.
1235fn rows_v2(list: &str, id_field: &str, cx: &OpContext<'_>) -> Result<Vec<Row>, Unresolved> {
1236    let invalid = |d: String| Unresolved::invalid(cx.lineage_inputs.iter().cloned(), d);
1237    let rows: Vec<(String, Result<Value, &'static str>)> =
1238        match eval_ref(list, &cx.scope).map_err(|f| fault(f, cx))? {
1239            Value::Joined(entries) => entries
1240                .iter()
1241                .map(|e| {
1242                    // `item` is `Some` exactly for a matched entry; the reason
1243                    // names why any other entry has none.
1244                    let row = e.item().ok_or(match &e.matched {
1245                        JoinMatch::MatchedAbsent(a) => a.reason.name(),
1246                        _ => "unmatched",
1247                    });
1248                    (e.id.clone(), row)
1249                })
1250                .collect(),
1251            Value::List(items) => items
1252                .iter()
1253                .enumerate()
1254                .map(|(i, it)| match it {
1255                    Value::Absent(a) => Ok((crate::grading::position_id(i), Err(a.reason.name()))),
1256                    it => id_of(it, id_field)
1257                        .map(|id| (id, Ok(it.clone())))
1258                        .ok_or_else(|| invalid(format!("item without {id_field:?}"))),
1259                })
1260                .collect::<Result<_, _>>()?,
1261            _ => return Err(invalid(format!("{list} is not a list"))),
1262        };
1263    let mut seen = BTreeSet::new();
1264    for (id, _) in &rows {
1265        if !seen.insert(id.clone()) {
1266            return Err(invalid(format!("duplicate id {id:?}")));
1267        }
1268    }
1269    Ok(rows)
1270}
1271
1272/// `filter_with_reasons@1` in `rustev.exact/2`: absent and unmatched items
1273/// are excluded before the rules, and a rule reading an absent value or a
1274/// `null` field excludes the item `missing:<path>`.
1275fn filter_v2(a: &FilterWithReasons, cx: &OpContext<'_>) -> Result<Value, Unresolved> {
1276    let mut eligible = Vec::new();
1277    let mut excluded = Vec::new();
1278    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
1279    for (id, row) in rows_v2(&a.list, &a.id_field, cx)? {
1280        let mut reasons: Vec<String> = Vec::new();
1281        match row {
1282            Err(r) => reasons.push(r.into()),
1283            Ok(item) => {
1284                let scope = item_scope(cx, &item);
1285                for r in &a.rules {
1286                    let reason = match eval_predicate(&r.predicate, &scope) {
1287                        Ok(true) => continue,
1288                        Ok(false) => r.name.clone(),
1289                        Err(Fault::Absent(p)) => format!("missing:{p}"),
1290                        Err(_) => format!("unevaluable:{}", r.name),
1291                    };
1292                    if !reasons.contains(&reason) {
1293                        reasons.push(reason);
1294                    }
1295                }
1296            }
1297        }
1298        if reasons.is_empty() {
1299            eligible.push(id);
1300        } else {
1301            for r in &reasons {
1302                *counts.entry(r.clone()).or_default() += 1;
1303            }
1304            excluded.push(Excluded { id, reasons });
1305        }
1306    }
1307    Ok(Value::Filtered(Filtered {
1308        eligible,
1309        excluded,
1310        counts,
1311    }))
1312}
1313
1314/// `top_k@1` in `rustev.exact/2`: a key reading an absent value or a `null`
1315/// field excludes the item `missing:<path>`.
1316fn top_k_v2(a: &TopK, cx: &OpContext<'_>) -> Result<Value, Unresolved> {
1317    let f = |e: Fault| fault(e, cx);
1318    let rows = rows_v2(&a.list, &a.id_field, cx)?;
1319    let among: BTreeSet<String> = match eval_ref(&a.among, &cx.scope).map_err(f)? {
1320        Value::Filtered(fl) => fl.eligible.into_iter().collect(),
1321        _ => return Err(f(Fault::Invalid("top_k among a non-filter".into()))),
1322    };
1323    if let Some(missing) = among
1324        .iter()
1325        .find(|id| !rows.iter().any(|(k, r)| k == *id && r.is_ok()))
1326    {
1327        return Err(f(Fault::Invalid(format!(
1328            "eligible id {missing:?} is not in {}",
1329            a.list
1330        ))));
1331    }
1332    let mut scored = Vec::new();
1333    let mut excluded = Vec::new();
1334    for (id, row) in rows.into_iter().filter(|(id, _)| among.contains(id)) {
1335        let Ok(item) = row else { continue };
1336        match eval_expr(&a.key, &item_scope(cx, &item)) {
1337            Ok(v) => match order_key(&v) {
1338                Some(k) => scored.push((k, id)),
1339                None => excluded.push(Excluded {
1340                    id,
1341                    reasons: vec!["unevaluable:key".into()],
1342                }),
1343            },
1344            Err(Fault::Absent(p)) => excluded.push(Excluded {
1345                id,
1346                reasons: vec![format!("missing:{p}")],
1347            }),
1348            Err(_) => excluded.push(Excluded {
1349                id,
1350                reasons: vec!["unevaluable:key".into()],
1351            }),
1352        }
1353    }
1354    scored.sort_by(|(ka, ia), (kb, ib)| {
1355        let by_key = match a.direction {
1356            Direction::Ascending => ka.cmp(kb),
1357            Direction::Descending => kb.cmp(ka),
1358        };
1359        by_key.then_with(|| ia.as_bytes().cmp(ib.as_bytes()))
1360    });
1361    let k = usize::try_from(a.k).unwrap_or(usize::MAX);
1362    let truncated = scored.len().saturating_sub(k) as u64;
1363    let ids = scored.into_iter().take(k).map(|(_, id)| id).collect();
1364    Ok(Value::Shortlist(Shortlist {
1365        ids,
1366        truncated,
1367        excluded,
1368    }))
1369}
1370
1371fn order_key(v: &Value) -> Option<(u8, i128)> {
1372    match v {
1373        Value::Integer(i) => Some((0, i128::from(*i))),
1374        Value::Decimal(d) => Some((1, d.units())),
1375        Value::Timestamp(t) => Some((2, i128::from(t.as_ms()))),
1376        Value::Duration(d) => Some((3, i128::from(d.0))),
1377        _ => None,
1378    }
1379}
1380
1381impl OpArgs {
1382    /// Evaluate with every dependency resolved (the evaluator checks that
1383    /// first, except for `field_presence`, which reads statuses).
1384    pub fn eval(&self, cx: &OpContext<'_>) -> Result<Value, Unresolved> {
1385        let f = |e: Fault| fault(e, cx);
1386        match self {
1387            OpArgs::ComposeKey(a) => a.eval(&cx.scope).map_err(f),
1388            // Plan 3 evaluation is increment 3 of spec 032; `Evaluation::start`
1389            // refuses a plan 3 until then, so these are never reached.
1390            OpArgs::JoinKeyed(_) | OpArgs::MergeFields(_) => Err(Unresolved::Unsupported {
1391                capability: format!("{}@1 evaluation", self.op().0),
1392            }),
1393            OpArgs::CountWhere(a) => {
1394                let list = items(&a.list, cx)?;
1395                let mut n: i64 = 0;
1396                for it in &list {
1397                    if eval_predicate(&a.predicate, &item_scope(cx, it)).map_err(f)? {
1398                        n += 1;
1399                    }
1400                }
1401                Ok(Value::Integer(n))
1402            }
1403            OpArgs::WindowFilter(a) => {
1404                let list = items(&a.list, cx)?;
1405                let now = cx.scope.now;
1406                let floor = now
1407                    .as_ms()
1408                    .saturating_sub(i64::try_from(a.within_ms).unwrap_or(i64::MAX));
1409                let mut out = Vec::new();
1410                for it in list {
1411                    let Some(Value::Timestamp(t)) = get_field(&it, &a.field) else {
1412                        return Err(f(Fault::Invalid(format!(
1413                            "item without timestamp {:?}",
1414                            a.field
1415                        ))));
1416                    };
1417                    if *t > now {
1418                        return Err(f(Fault::Invalid(format!(
1419                            "{:?} is after the evaluation time",
1420                            a.field
1421                        ))));
1422                    }
1423                    if t.as_ms() >= floor
1424                        && eval_predicate(&a.predicate, &item_scope(cx, &it)).map_err(f)?
1425                    {
1426                        out.push(it);
1427                    }
1428                }
1429                Ok(Value::List(out))
1430            }
1431            OpArgs::Extremum(a) => {
1432                let list = items(&a.list, cx)?;
1433                let mut best: Option<&Value> = None;
1434                for it in &list {
1435                    let Some(v) = get_field(it, &a.field) else {
1436                        continue;
1437                    };
1438                    let better = match best {
1439                        None => true,
1440                        Some(b) => match a.which {
1441                            Which::Min => order_key(v) < order_key(b),
1442                            Which::Max => order_key(v) > order_key(b),
1443                        },
1444                    };
1445                    if better {
1446                        best = Some(v);
1447                    }
1448                }
1449                Ok(Value::Maybe(best.cloned().map(Box::new)))
1450            }
1451            OpArgs::TimestampDiff(a) => {
1452                let later = eval_expr(&a.later, &cx.scope).map_err(f)?;
1453                let earlier = eval_expr(&a.earlier, &cx.scope).map_err(f)?;
1454                // The result is `maybe` exactly when an operand's type is.
1455                let is_maybe =
1456                    matches!(later, Value::Maybe(_)) || matches!(earlier, Value::Maybe(_));
1457                let unwrap = |v: Value| match v {
1458                    Value::Timestamp(t) => Ok(Some(t)),
1459                    Value::Maybe(None) => Ok(None),
1460                    Value::Maybe(Some(b)) => match *b {
1461                        Value::Timestamp(t) => Ok(Some(t)),
1462                        _ => Err(Fault::Invalid("timestamp_diff of a non-timestamp".into())),
1463                    },
1464                    _ => Err(Fault::Invalid("timestamp_diff of a non-timestamp".into())),
1465                };
1466                match (unwrap(later).map_err(f)?, unwrap(earlier).map_err(f)?) {
1467                    (Some(l), Some(e)) => {
1468                        let d = l.since(e).map_err(|_| {
1469                            f(Fault::Invalid("negative timestamp difference".into()))
1470                        })?;
1471                        let q = i64::try_from(d.0 / a.unit_ms)
1472                            .map_err(|_| f(Fault::Invalid("overflow".into())))?;
1473                        Ok(if is_maybe {
1474                            Value::Maybe(Some(Box::new(Value::Integer(q))))
1475                        } else {
1476                            Value::Integer(q)
1477                        })
1478                    }
1479                    _ => Ok(Value::Maybe(None)),
1480                }
1481            }
1482            OpArgs::Compare(a) => eval_predicate(&a.predicate, &cx.scope)
1483                .map(Value::Bool)
1484                .map_err(f),
1485            OpArgs::Arith(a) => eval_expr(&a.expr, &cx.scope).map_err(f),
1486            OpArgs::FxConvert(a) => {
1487                let e = Expr::Fx {
1488                    amount: Box::new(a.amount.clone()),
1489                    from: Box::new(a.from.clone()),
1490                    to: Box::new(a.to.clone()),
1491                    rates: a.rates.clone(),
1492                    scale: a.scale,
1493                };
1494                eval_expr(&e, &cx.scope).map_err(f)
1495            }
1496            OpArgs::MemberOf(a) => {
1497                let v = eval_expr(&a.value, &cx.scope).map_err(f)?;
1498                Ok(Value::Bool(
1499                    a.set.iter().any(|l| Value::from_literal(l) == v),
1500                ))
1501            }
1502            OpArgs::FieldPresence(a) => {
1503                let mut missing = Vec::new();
1504                for r in &a.inputs {
1505                    let name = r.trim_start_matches("input:");
1506                    match cx.inputs_status.get(name) {
1507                        Some(Ok(())) => {}
1508                        Some(Err(Unresolved::MissingEvidence { .. })) | None => {
1509                            missing.push(Value::Text(name.to_string()))
1510                        }
1511                        Some(Err(other)) => return Err(other.clone()),
1512                    }
1513                }
1514                Ok(Value::List(missing))
1515            }
1516            OpArgs::FilterWithReasons(a) if cx.scope.v2 => filter_v2(a, cx),
1517            OpArgs::TopK(a) if cx.scope.v2 => top_k_v2(a, cx),
1518            OpArgs::FilterWithReasons(a) => {
1519                let list = items(&a.list, cx)?;
1520                let keyed = keyed(&list, &a.id_field, cx)?;
1521                let mut eligible = Vec::new();
1522                let mut excluded = Vec::new();
1523                let mut counts: BTreeMap<String, u64> = BTreeMap::new();
1524                for (id, it) in keyed {
1525                    let scope = item_scope(cx, it);
1526                    let mut reasons = Vec::new();
1527                    for r in &a.rules {
1528                        match eval_predicate(&r.predicate, &scope) {
1529                            Ok(true) => {}
1530                            Ok(false) => reasons.push(r.name.clone()),
1531                            Err(_) => reasons.push(format!("unevaluable:{}", r.name)),
1532                        }
1533                    }
1534                    if reasons.is_empty() {
1535                        eligible.push(id);
1536                    } else {
1537                        for r in &reasons {
1538                            *counts.entry(r.clone()).or_default() += 1;
1539                        }
1540                        excluded.push(Excluded { id, reasons });
1541                    }
1542                }
1543                Ok(Value::Filtered(Filtered {
1544                    eligible,
1545                    excluded,
1546                    counts,
1547                }))
1548            }
1549            OpArgs::TopK(a) => {
1550                let list = items(&a.list, cx)?;
1551                let keyed = keyed(&list, &a.id_field, cx)?;
1552                let among: BTreeSet<String> = match eval_ref(&a.among, &cx.scope).map_err(f)? {
1553                    Value::Filtered(fl) => fl.eligible.into_iter().collect(),
1554                    _ => return Err(f(Fault::Invalid("top_k among a non-filter".into()))),
1555                };
1556                if let Some(missing) = among.iter().find(|id| !keyed.iter().any(|(k, _)| k == *id))
1557                {
1558                    return Err(f(Fault::Invalid(format!(
1559                        "eligible id {missing:?} is not in {}",
1560                        a.list
1561                    ))));
1562                }
1563                let mut scored = Vec::new();
1564                let mut excluded = Vec::new();
1565                for (id, it) in keyed.into_iter().filter(|(id, _)| among.contains(id)) {
1566                    match eval_expr(&a.key, &item_scope(cx, it))
1567                        .ok()
1568                        .as_ref()
1569                        .and_then(order_key)
1570                    {
1571                        Some(k) => scored.push((k, id)),
1572                        None => excluded.push(Excluded {
1573                            id,
1574                            reasons: vec!["unevaluable:key".into()],
1575                        }),
1576                    }
1577                }
1578                scored.sort_by(|(ka, ia), (kb, ib)| {
1579                    let by_key = match a.direction {
1580                        Direction::Ascending => ka.cmp(kb),
1581                        Direction::Descending => kb.cmp(ka),
1582                    };
1583                    by_key.then_with(|| ia.as_bytes().cmp(ib.as_bytes()))
1584                });
1585                let k = usize::try_from(a.k).unwrap_or(usize::MAX);
1586                let truncated = scored.len().saturating_sub(k) as u64;
1587                let ids = scored.into_iter().take(k).map(|(_, id)| id).collect();
1588                Ok(Value::Shortlist(Shortlist {
1589                    ids,
1590                    truncated,
1591                    excluded,
1592                }))
1593            }
1594            OpArgs::WeightedRank(a) => weighted_rank(a, cx),
1595        }
1596    }
1597}
1598
1599fn weights_by_key(
1600    w: &WeightTable,
1601    cx: &OpContext<'_>,
1602) -> Result<BTreeMap<String, Option<f64>>, Unresolved> {
1603    let list = items(&w.list, cx)?;
1604    let table: BTreeMap<&str, f64> = w
1605        .table
1606        .iter()
1607        .map(|c| (c.class.as_str(), c.weight.to_f64_nearest()))
1608        .collect();
1609    let mut out = BTreeMap::new();
1610    for it in &list {
1611        if let (Some(k), Some(c)) = (id_of(it, &w.key_field), id_of(it, &w.class_field)) {
1612            out.insert(k, table.get(c.as_str()).copied());
1613        }
1614    }
1615    Ok(out)
1616}
1617
1618fn weighted_rank(a: &WeightedRank, cx: &OpContext<'_>) -> Result<Value, Unresolved> {
1619    let candidates: Vec<String> =
1620        match eval_ref(&a.candidates, &cx.scope).map_err(|e| fault(e, cx))? {
1621            v @ (Value::Shortlist(_) | Value::Filtered(_)) => v.ids().unwrap_or_default(),
1622            _ => {
1623                return Err(fault(
1624                    Fault::Invalid("weighted_rank over a non-shortlist".into()),
1625                    cx,
1626                ));
1627            }
1628        };
1629    let n = candidates.len();
1630    let mut entries: Vec<RankEntry> = Vec::new();
1631    let mut excluded: Vec<Excluded> = Vec::new();
1632    'candidate: for (i, c) in candidates.iter().enumerate() {
1633        let mut components = BTreeMap::new();
1634        let mut score = 0.0f64;
1635        for comp in &a.components {
1636            let value = match &comp.source {
1637                Source::ShortlistPosition => {
1638                    if n <= 1 {
1639                        1.0
1640                    } else {
1641                        1.0 - (i as f64) / ((n - 1) as f64)
1642                    }
1643                }
1644                Source::RubricExpectation { step } => {
1645                    let inst = semantic_of(step, cx)?;
1646                    match inst.get(std::slice::from_ref(c)) {
1647                        Some(Ok(SemValue::Ordinal(o))) => {
1648                            let top = (o.levels().len().saturating_sub(1)).max(1) as f64;
1649                            o.expectation() / top
1650                        }
1651                        Some(Err(u)) => {
1652                            excluded.push(Excluded {
1653                                id: c.clone(),
1654                                reasons: vec![format!("{}:{u}", comp.name)],
1655                            });
1656                            continue 'candidate;
1657                        }
1658                        _ => {
1659                            excluded.push(Excluded {
1660                                id: c.clone(),
1661                                reasons: vec![format!("{}:no value", comp.name)],
1662                            });
1663                            continue 'candidate;
1664                        }
1665                    }
1666                }
1667                Source::PropositionMean {
1668                    step,
1669                    candidate_bind,
1670                    weights,
1671                } => {
1672                    let inst = semantic_of(step, cx)?;
1673                    let pos = cx
1674                        .binds
1675                        .get(step_name(step))
1676                        .and_then(|b| b.iter().position(|b| b == candidate_bind))
1677                        .unwrap_or(0);
1678                    let other = 1 - pos.min(1);
1679                    let wmap = weights_by_key(weights, cx)?;
1680                    let (mut num, mut den) = (0.0f64, 0.0f64);
1681                    for (key, v) in inst.iter().filter(|(k, _)| k.get(pos) == Some(c)) {
1682                        let claim = key.get(other).cloned().unwrap_or_default();
1683                        let w = match wmap.get(&claim) {
1684                            Some(Some(w)) => *w,
1685                            _ => {
1686                                excluded.push(Excluded {
1687                                    id: c.clone(),
1688                                    reasons: vec![format!("{}:unweighted {claim}", comp.name)],
1689                                });
1690                                continue 'candidate;
1691                            }
1692                        };
1693                        match v {
1694                            Ok(sv) => match sv.mass("true") {
1695                                Some(p) => {
1696                                    num += w * p;
1697                                    den += w;
1698                                }
1699                                None => {
1700                                    excluded.push(Excluded {
1701                                        id: c.clone(),
1702                                        reasons: vec![format!("{}:no mass", comp.name)],
1703                                    });
1704                                    continue 'candidate;
1705                                }
1706                            },
1707                            Err(u) => {
1708                                excluded.push(Excluded {
1709                                    id: c.clone(),
1710                                    reasons: vec![format!("{}:{u}", comp.name)],
1711                                });
1712                                continue 'candidate;
1713                            }
1714                        }
1715                    }
1716                    if den > 0.0 { num / den } else { 0.0 }
1717                }
1718            };
1719            components.insert(comp.name.clone(), value);
1720            score += comp.weight.to_f64_nearest() * value;
1721        }
1722        entries.push(RankEntry {
1723            candidate: c.clone(),
1724            position: 0,
1725            score,
1726            components,
1727        });
1728    }
1729    entries.sort_by(|x, y| {
1730        y.score
1731            .total_cmp(&x.score)
1732            .then_with(|| x.candidate.as_bytes().cmp(y.candidate.as_bytes()))
1733    });
1734    for (i, e) in entries.iter_mut().enumerate() {
1735        e.position = i as u64 + 1;
1736    }
1737    Ok(Value::Ranking(Ranking { entries, excluded }))
1738}
1739
1740fn step_name(r: &str) -> &str {
1741    r.strip_prefix("step:").unwrap_or(r)
1742}
1743
1744fn semantic_of<'c>(r: &str, cx: &'c OpContext<'_>) -> Result<&'c SemInstances, Unresolved> {
1745    cx.semantic.get(step_name(r)).ok_or_else(|| {
1746        Unresolved::invalid(
1747            cx.lineage_inputs.iter().cloned(),
1748            format!("{r} has no value"),
1749        )
1750    })
1751}
1752
1753#[cfg(test)]
1754mod tests {
1755    use super::*;
1756    use serde_json::json;
1757
1758    #[test]
1759    fn joins_and_merges_are_only_in_registry_2() {
1760        for (op, v) in REGISTRY_V2_ADDS {
1761            assert!(!is_registered(op, *v), "{op} is not in rustev.exact/1");
1762            assert!(is_registered_v2(op, *v), "{op} is in rustev.exact/2");
1763            assert!(decode(op, *v, &json!({})).is_none());
1764        }
1765        assert!(REGISTRY.iter().all(|(op, v)| is_registered_v2(op, *v)));
1766        assert!(!is_registered_v2("join_keyed", 2));
1767    }
1768
1769    #[test]
1770    fn a_merge_presence_predicate_names_merged_fields_only() {
1771        let nullable_decimal = Ty::Nullable(Box::new(Ty::Decimal));
1772        let inputs = BTreeMap::from([
1773            (
1774                "base".to_string(),
1775                Ty::Record(vec![
1776                    ("id".into(), Ty::Text { max_bytes: 8 }),
1777                    ("price".into(), nullable_decimal.clone()),
1778                ]),
1779            ),
1780            (
1781                "over".to_string(),
1782                Ty::Record(vec![("price".into(), nullable_decimal)]),
1783            ),
1784        ]);
1785        let steps = BTreeMap::new();
1786        let env = TyEnv {
1787            inputs: &inputs,
1788            steps: &steps,
1789            item: None,
1790            v2: true,
1791        };
1792        let merge = |present: &str| {
1793            decode_v2(
1794                "merge_fields",
1795                1,
1796                &json!({"base": "input:base", "overlay": "input:over", "rules": [
1797                    {"field": "id", "rule": "base_only"},
1798                    {"field": "price", "rule": "overlay_only"}],
1799                    "present_when": {"any_non_null": [present]}}),
1800            )
1801            .unwrap()
1802            .unwrap()
1803        };
1804        assert!(merge("price").type_check(&env).is_ok());
1805        // Every field without a rule is named, each once.
1806        let bare = decode_v2(
1807            "merge_fields",
1808            1,
1809            &json!({"base": "input:base", "overlay": "input:over", "rules": []}),
1810        )
1811        .unwrap()
1812        .unwrap();
1813        assert_eq!(
1814            bare.merge_rule_error(&env).as_deref(),
1815            Some(
1816                "field \"id\" has no merge rule; field \"price\" has no merge rule, \
1817                 and there is no default"
1818            )
1819        );
1820        let e = merge("total").type_check(&env).unwrap_err();
1821        assert!(e.contains("not a merged field"), "{e}");
1822    }
1823
1824    #[test]
1825    fn a_join_key_is_a_plain_field_name() {
1826        let join = |key: &str| {
1827            decode_v2(
1828                "join_keyed",
1829                1,
1830                &json!({"left": "input:hotels", "key": key, "right": "input:quotes"}),
1831            )
1832            .unwrap()
1833            .unwrap()
1834        };
1835        assert!(join("id").structure().is_ok());
1836        for bad in ["", "price/net", "price.net", "*"] {
1837            assert!(join(bad).structure().is_err(), "{bad:?}");
1838        }
1839        let merge = |field: &str| {
1840            decode_v2(
1841                "merge_fields",
1842                1,
1843                &json!({"base": "input:base", "overlay": "input:over",
1844                    "rules": [{"field": field, "rule": "base_only"}]}),
1845            )
1846            .unwrap()
1847            .unwrap()
1848        };
1849        assert!(merge("id").structure().is_ok());
1850        for bad in ["", "price/net", "price.net", "*"] {
1851            assert!(merge(bad).structure().is_err(), "{bad:?}");
1852        }
1853    }
1854
1855    #[test]
1856    fn registry_2_decodes_strictly() {
1857        assert!(matches!(
1858            decode_v2("join_keyed", 1, &json!({})),
1859            Some(Err(_))
1860        ));
1861        assert!(matches!(
1862            decode_v2("merge_fields", 1, &json!({"surprise": 1})),
1863            Some(Err(_))
1864        ));
1865        assert!(decode_v2("join_keyed", 2, &json!({})).is_none());
1866    }
1867}