1use 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#[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
31pub(crate) fn missed_proofs(run: &Run, now: &Instant) -> Result<i128> {
34 let base = run.last_proof_instant.unwrap_or(run.registered_instant);
35 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
57pub(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
82pub(crate) enum Seat {
85 Held,
87 Fall,
90}
91
92pub(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#[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#[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
163pub trait ModelTransport {
171 fn consult(&self, vignette: &str) -> Consultation;
172 fn pinned_model_name(&self) -> &str;
173}
174
175pub 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 pub fn shown(&self) -> Vec<String> {
200 self.shown.borrow().clone()
201 }
202
203 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
223pub(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
233pub(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}