Skip to main content

arvin/
evaluate.rs

1//! The switch.
2
3use std::cmp::Ordering;
4
5use crate::instant::Instant;
6use crate::join::{missed_count, missed_warrant_index, model_name_shape_ok, Record, Run};
7use crate::value::{Error, JsonInt, Result};
8use crate::{PROOF_INTERVAL_MAX_SECONDS, STAGES};
9
10/// The outcome of one evaluation of one run. The appended
11/// field carries the record the evaluation appended, or
12/// stands empty where it appended none, so a caller
13/// reporting the consultation of a model evaluation reads
14/// that record from the report itself and never reads the
15/// log back to find it.
16#[derive(Clone, Debug, PartialEq)]
17pub struct StageReport {
18    pub run: String,
19    pub stage: String,
20    pub reasons: Vec<String>,
21    pub appended: Option<Record>,
22}
23
24pub(crate) fn stage_index(stage: &str) -> usize {
25    STAGES
26        .iter()
27        .position(|candidate| *candidate == stage)
28        .expect("a stored stage stands in the ladder")
29}
30
31/// Whole proof intervals missed at the instant, deadline exact
32/// counts zero.
33pub(crate) fn missed_proofs(run: &Run, now: &Instant) -> Result<i128> {
34    let base = run.last_proof_instant.unwrap_or(run.registered_instant);
35    // The interval as a duration overflows the representable
36    // range past the largest whole second count a duration of
37    // 999999999 days holds, which is the check the Python
38    // timedelta construction raises as its overflow error.
39    if run
40        .proof_interval_seconds
41        .cmp_i128(PROOF_INTERVAL_MAX_SECONDS as i128)
42        == Ordering::Greater
43    {
44        return Err(Error::InvalidRequest(
45            "the missed proof count at this instant stands outside the range the \
46             switch can represent"
47                .to_string(),
48        ));
49    }
50    let interval_seconds = match &run.proof_interval_seconds {
51        JsonInt::Small(value) => *value,
52        JsonInt::Big(_) => unreachable!("the bound check above refuses a big interval"),
53    };
54    Ok(missed_count(&base, now, interval_seconds))
55}
56
57/// The warranted stage index and the live trigger names at the
58/// instant, the triggers in the order DM-3 names them.
59pub(crate) fn warrant(run: &Run, now: &Instant) -> Result<(usize, Vec<&'static str>)> {
60    let mut index = 0usize;
61    let mut reasons: Vec<&'static str> = Vec::new();
62    if let Some(hard) = run.hard_ceiling {
63        if run.spend_total >= hard {
64            index = stage_index("kill");
65            reasons.push("hard ceiling");
66        }
67    }
68    if let Some(soft) = run.soft_ceiling {
69        if run.spend_total >= soft {
70            index = index.max(stage_index("cut budget"));
71            reasons.push("soft ceiling");
72        }
73    }
74    let missed = missed_proofs(run, now)?;
75    if missed >= 1 {
76        reasons.push("missed proofs");
77    }
78    index = index.max(missed_warrant_index(missed, run.missed_proof_limit));
79    Ok((index, reasons))
80}
81
82/// Which seat of DM-13 an evaluation stands at, where a seat
83/// stands open at all.
84pub(crate) enum Seat {
85    /// The warranted stage stands equal to the recorded stage.
86    Held,
87    /// The warranted stage stands below the recorded stage and
88    /// the standing clear streak stands at 1.
89    Fall,
90}
91
92/// The reference instant of DM-19, the latest of the
93/// registration instant and the standing last proof instant
94/// where one stands and the instant of the latest stage
95/// record in sequence order where one stands, each taken from
96/// the run as recorded.
97pub(crate) fn reference_instant(run: &Run) -> Instant {
98    let mut reference = run.registered_instant;
99    if let Some(proof) = run.last_proof_instant {
100        if proof > reference {
101            reference = proof;
102        }
103    }
104    for record in run.log.iter().rev() {
105        if record.kind == "stage" {
106            if record.instant > reference {
107                reference = record.instant;
108            }
109            break;
110        }
111    }
112    reference
113}
114
115/// A verdict of the decision model, one of the three labels
116/// of DM-17.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum Verdict {
119    Hold,
120    Escalate,
121    DeEscalate,
122}
123
124impl Verdict {
125    pub fn label(&self) -> &'static str {
126        match self {
127            Verdict::Hold => "hold",
128            Verdict::Escalate => "escalate",
129            Verdict::DeEscalate => "de-escalate",
130        }
131    }
132
133    pub(crate) fn from_label(text: &str) -> Option<Verdict> {
134        match text {
135            "hold" => Some(Verdict::Hold),
136            "escalate" => Some(Verdict::Escalate),
137            "de-escalate" => Some(Verdict::DeEscalate),
138            _ => None,
139        }
140    }
141}
142
143/// The outcome of one consultation, a verdict or one of the
144/// fallback classes of DM-16 in typed form. A transport
145/// returns this and judges nothing beyond the parsing its own
146/// shape states.
147#[derive(Clone, Debug, PartialEq)]
148pub enum Consultation {
149    Verdict {
150        model_name: String,
151        verdict: Verdict,
152        confidence: f64,
153        score: f64,
154    },
155    Abstention {
156        model_name: String,
157    },
158    CallFailed,
159    Silence,
160    MalformedReply,
161}
162
163/// A caller supplied model transport under DM-20. The one
164/// operation takes the rendered vignette and returns the
165/// consultation outcome. The pinned model name stands beside
166/// it because the fallback pattern of DM-17 records the name
167/// of the model the transport stands pinned to, and a
168/// fallback outcome carries no reply a name could be read
169/// from.
170pub trait ModelTransport {
171    fn consult(&self, vignette: &str) -> Consultation;
172    fn pinned_model_name(&self) -> &str;
173}
174
175/// A fixture transport, shipped in the crate because the gate
176/// and the recording harness and any rehearsing host need the
177/// same shape, and a test only copy would fork it. It answers
178/// canned consultations in the order supplied and records
179/// every vignette it was shown, and it performs no network
180/// access and spawns no process. A consultation asked past
181/// the supplied replies is a call failure, the class a script
182/// that has run out has honestly earned.
183pub struct FixtureTransport {
184    model_name: String,
185    replies: std::cell::RefCell<std::collections::VecDeque<Consultation>>,
186    shown: std::cell::RefCell<Vec<String>>,
187}
188
189impl FixtureTransport {
190    pub fn new(model_name: &str, replies: Vec<Consultation>) -> FixtureTransport {
191        FixtureTransport {
192            model_name: model_name.to_string(),
193            replies: std::cell::RefCell::new(replies.into()),
194            shown: std::cell::RefCell::new(Vec::new()),
195        }
196    }
197
198    /// Every vignette this transport was shown, in order.
199    pub fn shown(&self) -> Vec<String> {
200        self.shown.borrow().clone()
201    }
202
203    /// How many canned replies stand unspent.
204    pub fn remaining(&self) -> usize {
205        self.replies.borrow().len()
206    }
207}
208
209impl ModelTransport for FixtureTransport {
210    fn consult(&self, vignette: &str) -> Consultation {
211        self.shown.borrow_mut().push(vignette.to_string());
212        self.replies
213            .borrow_mut()
214            .pop_front()
215            .unwrap_or(Consultation::CallFailed)
216    }
217
218    fn pinned_model_name(&self) -> &str {
219        &self.model_name
220    }
221}
222
223/// The model fields one consultation record carries, in one
224/// of the patterns of DM-17.
225pub(crate) struct ConsultationFields {
226    pub(crate) model_name: Option<String>,
227    pub(crate) model_verdict: Option<String>,
228    pub(crate) model_confidence: Option<f64>,
229    pub(crate) model_score: Option<f64>,
230    pub(crate) fallback_taken: Option<String>,
231}
232
233/// Turn a consultation outcome into the fields its record
234/// carries. An outcome whose values stand outside the shapes
235/// DM-17 records lands in the malformed reply class on the
236/// pinned name, because a record the reader would refuse must
237/// never be written by the switch's own hand.
238pub(crate) fn consultation_fields(outcome: Consultation, pinned: &str) -> ConsultationFields {
239    fn fallback(class: &str, name: &str) -> ConsultationFields {
240        ConsultationFields {
241            model_name: Some(name.to_string()),
242            model_verdict: None,
243            model_confidence: None,
244            model_score: None,
245            fallback_taken: Some(class.to_string()),
246        }
247    }
248    match outcome {
249        Consultation::Verdict {
250            model_name,
251            verdict,
252            confidence,
253            score,
254        } if model_name_shape_ok(&model_name)
255            && model_name == pinned
256            && (0.0..=1.0).contains(&confidence)
257            && (0.0..=1.0).contains(&score) =>
258        {
259            ConsultationFields {
260                model_name: Some(model_name),
261                model_verdict: Some(verdict.label().to_string()),
262                model_confidence: Some(confidence),
263                model_score: Some(score),
264                fallback_taken: None,
265            }
266        }
267        Consultation::Abstention { model_name }
268            if model_name_shape_ok(&model_name) && model_name == pinned =>
269        {
270            fallback("abstention", &model_name)
271        }
272        Consultation::CallFailed => fallback("call failed", pinned),
273        Consultation::Silence => fallback("silence", pinned),
274        _ => fallback("malformed reply", pinned),
275    }
276}