rustev-contract 0.3.0

Rustev's versioned wire contract: documents, bounded parsing, canonical form and identities.
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
//! Judgments, `rustev.judgment/1`, and `rustev.judgment/2` for plans with
//! `actionability` (spec 033, 3.1.3): the typed result of a plan. A judgment
//! is a proposal, an escalation, an unresolved outcome, or (version 2) a
//! refusal or a request for input; it is never a grant and never an effect
//! (spec 001, 3.2). Version 2 carries an action on every unresolved
//! outcome, refusal, request for input and notice (spec 033, 3.5).

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::actionability::{Action, NeedsInput, Party, Refusal};
use crate::decimal::Decimal;
use crate::definition::ReasonKind;
use crate::ids::{PlanId, SnapshotId};
use crate::limits::RECORD_V1;
use crate::schema;
use crate::time::{DurationMs, Timestamp};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Judgment {
    pub schema: String,
    pub plan_id: PlanId,
    pub snapshot_id: SnapshotId,
    pub evaluation_time_ms: Timestamp,
    pub outcome: Outcome,
    pub derivation: Derivation,
    pub lineage: Lineage,
    /// Uncalibrated thresholds used, truncation, fallbacks.
    pub notices: Vec<Notice>,
    /// Which handler, rule and adjustments produced the outcome, in order.
    pub trace: Vec<String>,
}

crate::document::versioned_document!(
    Judgment,
    [schema::JUDGMENT, schema::JUDGMENT_V2],
    "rustev.judgment/1 or rustev.judgment/2",
    RECORD_V1,
    check = Judgment::extraction_version
);

impl Judgment {
    pub(crate) fn extraction_version(&self) -> Result<(), String> {
        fn attributed(v: &OutValue) -> bool {
            match v {
                OutValue::Attributed { .. } => true,
                OutValue::List(items) => items.iter().any(attributed),
                OutValue::Record(fields) => fields.values().any(attributed),
                _ => false,
            }
        }
        if self.schema != schema::JUDGMENT_V2
            && (self.lineage.producers.is_some()
                || matches!(&self.outcome, Outcome::Propose { params, .. } if params.values().any(attributed)))
        {
            return Err("attributed values and producers require rustev.judgment/2".into());
        }
        Ok(())
    }
}

/// A judgment's outcome. Version 1 uses `Propose`, `Escalate` and
/// `Unresolved`; version 2 (spec 033, 3.5.1) replaces `Unresolved` with
/// `UnresolvedAction` and adds `Refused` and `NeedsInput`. Both unresolved
/// forms share the wire key `unresolved`: `{"unresolved": <reason>}` in
/// version 1, `{"unresolved": {"reason": <reason>, "action": <action>}}` in
/// version 2.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(from = "OutcomeWire", into = "OutcomeWire")]
pub enum Outcome {
    Propose {
        action: String,
        params: BTreeMap<String, OutValue>,
    },
    Escalate {
        reason: String,
    },
    Unresolved(Unresolved),
    UnresolvedAction {
        reason: Unresolved,
        action: Action,
    },
    Refused {
        refusals: Vec<Refusal>,
        addressed_to: Party,
    },
    NeedsInput(Box<NeedsInput>),
}

impl Outcome {
    /// The unresolved reason of either version, if the outcome is one.
    pub fn unresolved(&self) -> Option<&Unresolved> {
        match self {
            Outcome::Unresolved(u) | Outcome::UnresolvedAction { reason: u, .. } => Some(u),
            _ => None,
        }
    }
}

#[derive(Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
enum OutcomeWire {
    Propose {
        action: String,
        params: BTreeMap<String, OutValue>,
    },
    Escalate {
        reason: String,
    },
    Unresolved(UnresolvedWire),
    Refused {
        refusals: Vec<Refusal>,
        addressed_to: Party,
    },
    NeedsInput(Box<NeedsInput>),
}

/// Version 2's `{reason, action}` is tried first; no version 1 reason is
/// named `reason` or `action`, so the two forms never overlap.
#[derive(Serialize, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
enum UnresolvedWire {
    Actionable(ActionableUnresolved),
    Plain(Unresolved),
}

#[derive(Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
struct ActionableUnresolved {
    reason: Unresolved,
    action: Action,
}

impl From<OutcomeWire> for Outcome {
    fn from(w: OutcomeWire) -> Self {
        match w {
            OutcomeWire::Propose { action, params } => Outcome::Propose { action, params },
            OutcomeWire::Escalate { reason } => Outcome::Escalate { reason },
            OutcomeWire::Unresolved(UnresolvedWire::Plain(u)) => Outcome::Unresolved(u),
            OutcomeWire::Unresolved(UnresolvedWire::Actionable(a)) => Outcome::UnresolvedAction {
                reason: a.reason,
                action: a.action,
            },
            OutcomeWire::Refused {
                refusals,
                addressed_to,
            } => Outcome::Refused {
                refusals,
                addressed_to,
            },
            OutcomeWire::NeedsInput(n) => Outcome::NeedsInput(n),
        }
    }
}

impl From<Outcome> for OutcomeWire {
    fn from(o: Outcome) -> Self {
        match o {
            Outcome::Propose { action, params } => OutcomeWire::Propose { action, params },
            Outcome::Escalate { reason } => OutcomeWire::Escalate { reason },
            Outcome::Unresolved(u) => OutcomeWire::Unresolved(UnresolvedWire::Plain(u)),
            Outcome::UnresolvedAction { reason, action } => {
                OutcomeWire::Unresolved(UnresolvedWire::Actionable(ActionableUnresolved {
                    reason,
                    action,
                }))
            }
            Outcome::Refused {
                refusals,
                addressed_to,
            } => OutcomeWire::Refused {
                refusals,
                addressed_to,
            },
            Outcome::NeedsInput(n) => OutcomeWire::NeedsInput(n),
        }
    }
}

/// The closed set of unresolved reasons (spec 002, 3.5.6). Field and fact
/// lists are sorted and deduplicated.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Unresolved {
    MissingEvidence {
        fields: Vec<String>,
    },
    StaleEvidence {
        fields: Vec<String>,
    },
    InvalidInput {
        fields: Vec<String>,
        detail: String,
    },
    Abstained {
        rule: String,
    },
    BackendUnavailable {
        detail: String,
    },
    InvalidBackendOutput {
        detail: String,
    },
    BudgetExhausted {
        resource: String,
    },
    DeadlineExceeded,
    Conflict {
        facts: Vec<String>,
    },
    Unsupported {
        capability: String,
    },
    /// A read whose value is below a required grade (spec 032, 3.9.4).
    InsufficientGrade {
        fields: Vec<String>,
    },
    /// Unscreened fields a model step would read (spec 035, 3.9.1).
    ScreenUnavailable {
        #[serde(deserialize_with = "crate::screening::unavailable_fields")]
        #[schemars(length(min = 1))]
        fields: Vec<String>,
    },
}

impl Unresolved {
    pub fn kind(&self) -> ReasonKind {
        match self {
            Unresolved::ScreenUnavailable { .. } => ReasonKind::ScreenUnavailable,
            Unresolved::MissingEvidence { .. } => ReasonKind::MissingEvidence,
            Unresolved::StaleEvidence { .. } => ReasonKind::StaleEvidence,
            Unresolved::InvalidInput { .. } => ReasonKind::InvalidInput,
            Unresolved::Abstained { .. } => ReasonKind::Abstained,
            Unresolved::BackendUnavailable { .. } => ReasonKind::BackendUnavailable,
            Unresolved::InvalidBackendOutput { .. } => ReasonKind::InvalidBackendOutput,
            Unresolved::BudgetExhausted { .. } => ReasonKind::BudgetExhausted,
            Unresolved::DeadlineExceeded => ReasonKind::DeadlineExceeded,
            Unresolved::Conflict { .. } => ReasonKind::Conflict,
            Unresolved::Unsupported { .. } => ReasonKind::Unsupported,
            Unresolved::InsufficientGrade { .. } => ReasonKind::InsufficientGrade,
        }
    }

    /// `missing_evidence` with sorted, deduplicated fields.
    pub fn missing<I: IntoIterator<Item = String>>(fields: I) -> Self {
        Unresolved::MissingEvidence {
            fields: sorted(fields),
        }
    }

    /// `stale_evidence` with sorted, deduplicated fields.
    pub fn stale<I: IntoIterator<Item = String>>(fields: I) -> Self {
        Unresolved::StaleEvidence {
            fields: sorted(fields),
        }
    }

    /// `invalid_input` with sorted, deduplicated fields.
    pub fn invalid<I: IntoIterator<Item = String>>(fields: I, detail: impl Into<String>) -> Self {
        Unresolved::InvalidInput {
            fields: sorted(fields),
            detail: detail.into(),
        }
    }

    /// `insufficient_grade` with sorted, deduplicated fields.
    pub fn insufficient<I: IntoIterator<Item = String>>(fields: I) -> Self {
        Unresolved::InsufficientGrade {
            fields: sorted(fields),
        }
    }

    /// `screen_unavailable` with sorted, deduplicated field references.
    pub fn screen_unavailable<I: IntoIterator<Item = String>>(fields: I) -> Self {
        Unresolved::ScreenUnavailable {
            fields: sorted(fields),
        }
    }

    /// `conflict` with sorted, deduplicated facts.
    pub fn conflict<I: IntoIterator<Item = String>>(facts: I) -> Self {
        Unresolved::Conflict {
            facts: sorted(facts),
        }
    }
}

fn sorted<I: IntoIterator<Item = String>>(items: I) -> Vec<String> {
    let mut v: Vec<String> = items.into_iter().collect();
    v.sort();
    v.dedup();
    v
}

impl fmt::Display for Unresolved {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Unresolved::ScreenUnavailable { fields } => {
                write!(f, "screen_unavailable{{{}}}", fields.join(","))
            }
            Unresolved::MissingEvidence { fields } => {
                write!(f, "missing_evidence{{{}}}", fields.join(","))
            }
            Unresolved::StaleEvidence { fields } => {
                write!(f, "stale_evidence{{{}}}", fields.join(","))
            }
            Unresolved::InvalidInput { fields, detail } => {
                write!(f, "invalid_input{{{}}}: {detail}", fields.join(","))
            }
            Unresolved::Abstained { rule } => write!(f, "abstained{{{rule}}}"),
            Unresolved::BackendUnavailable { detail } => write!(f, "backend_unavailable: {detail}"),
            Unresolved::InvalidBackendOutput { detail } => {
                write!(f, "invalid_backend_output: {detail}")
            }
            Unresolved::BudgetExhausted { resource } => write!(f, "budget_exhausted{{{resource}}}"),
            Unresolved::DeadlineExceeded => write!(f, "deadline_exceeded"),
            Unresolved::Conflict { facts } => write!(f, "conflict{{{}}}", facts.join(",")),
            Unresolved::Unsupported { capability } => write!(f, "unsupported{{{capability}}}"),
            Unresolved::InsufficientGrade { fields } => {
                write!(f, "insufficient_grade{{{}}}", fields.join(","))
            }
        }
    }
}

/// Derivation classes (spec 001, 3.3; spec 002, 3.12).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
pub enum Derivation {
    ExactDerived,
    ModelDerived,
    MixedDerived,
}

/// What a value was computed from: input fields and steps, sorted.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Lineage {
    pub inputs: Vec<String>,
    pub steps: Vec<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "crate::screening::present"
    )]
    pub producers: Option<crate::extraction_results::Producers>,
}

#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct Notice {
    pub kind: NoticeKind,
    /// The step or policy item it concerns.
    pub subject: String,
    pub reason: String,
    /// Judgment 2: who can act on it (spec 033, 3.5.4); omitted in version 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<Action>,
    /// Entry, field, consequence and item ids only (spec 035, 3.6.4).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "crate::screening::present"
    )]
    #[schemars(with = "crate::screening::ScreeningNotice")]
    pub screening: Option<crate::screening::ScreeningNotice>,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum NoticeKind {
    UncalibratedThreshold,
    Truncation,
    Fallback,
    /// Spec 033, 3.3: a check's field-level consequences.
    FieldDropped,
    ConstraintsRelaxed,
    GradeDowngraded,
    CheckNotice,
    Screening,
}

/// A value placed in a proposal's parameters.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum OutValue {
    Attributed {
        value: Box<OutValue>,
        derivation: Derivation,
        origin: crate::extraction_results::AcceptedOrigin,
    },
    Bool(bool),
    Integer(i64),
    Decimal(Decimal),
    Text(String),
    Enum(String),
    Timestamp(Timestamp),
    Duration(DurationMs),
    /// The `none` of a `maybe` value.
    None,
    List(Vec<OutValue>),
    Record(BTreeMap<String, OutValue>),
    Filtered(Filtered),
    Shortlist(Shortlist),
    Ranking(Ranking),
    Selection(crate::ranking_result::Selection),
}

/// The result of `filter_with_reasons@1`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Filtered {
    pub eligible: Vec<String>,
    pub excluded: Vec<Excluded>,
    /// How many items each rule excluded.
    pub counts: BTreeMap<String, u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Excluded {
    pub id: String,
    pub reasons: Vec<String>,
}

/// The result of `top_k@1`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Shortlist {
    pub ids: Vec<String>,
    /// Eligible ids not kept because of `k`.
    pub truncated: u64,
    pub excluded: Vec<Excluded>,
}

/// A `RankPosition` in wire form: an order, not a probability of being best.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Ranking {
    pub entries: Vec<RankEntry>,
    /// Candidates left out because a component was unresolved.
    pub excluded: Vec<Excluded>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RankEntry {
    pub candidate: String,
    /// 1-based.
    pub position: u64,
    pub score: f64,
    pub components: BTreeMap<String, f64>,
}

impl ReasonKind {
    pub fn name(self) -> &'static str {
        match self {
            ReasonKind::ScreenUnavailable => "screen_unavailable",
            ReasonKind::Skipped => "skipped",
            ReasonKind::MissingEvidence => "missing_evidence",
            ReasonKind::StaleEvidence => "stale_evidence",
            ReasonKind::InvalidInput => "invalid_input",
            ReasonKind::Abstained => "abstained",
            ReasonKind::BackendUnavailable => "backend_unavailable",
            ReasonKind::InvalidBackendOutput => "invalid_backend_output",
            ReasonKind::BudgetExhausted => "budget_exhausted",
            ReasonKind::DeadlineExceeded => "deadline_exceeded",
            ReasonKind::Conflict => "conflict",
            ReasonKind::Unsupported => "unsupported",
            ReasonKind::InsufficientGrade => "insufficient_grade",
        }
    }
}