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
//! The question set as the evaluator sees it at run time.
//!
//! Every check here is local. A question the route's declared limits refuse is
//! refused before dispatch, so the caller gets `question_invalid` having made
//! zero provider requests and paid nothing. The checker already proved the set
//! is a literal; this layer proves it fits the route.
use crate::value::VmValue;
use super::contract::{DecisionContract, DecisionQuestionKind};
/// Why a question set cannot be dispatched. These are the closed reasons of
/// the `question_invalid` outcome arm.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuestionRefusal {
/// The offending question's id, or the empty string when the whole set is.
pub question: String,
pub reason: QuestionRefusalReason,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QuestionRefusalReason {
TooManyOptions,
TooFewLevels,
TooManyLevels,
EmptyInstructions,
TooManyQuestions,
UnsupportedQuestionKind,
}
impl QuestionRefusalReason {
pub fn as_str(self) -> &'static str {
match self {
Self::TooManyOptions => "too_many_options",
Self::TooFewLevels => "too_few_levels",
Self::TooManyLevels => "too_many_levels",
Self::EmptyInstructions => "empty_instructions",
Self::TooManyQuestions => "too_many_questions",
Self::UnsupportedQuestionKind => "unsupported_question_kind",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub enum QuestionBody {
Boolean,
/// Label to the description the model judges against, in declared order.
Choice(Vec<(String, String)>),
/// Ordered levels, lowest first.
Score(Vec<String>),
}
impl QuestionBody {
pub fn kind(&self) -> DecisionQuestionKind {
match self {
Self::Boolean => DecisionQuestionKind::Boolean,
Self::Choice(_) => DecisionQuestionKind::Choice,
Self::Score(_) => DecisionQuestionKind::Score,
}
}
/// The labels an answer's probability map is keyed by. A boolean answer
/// carries one probability rather than a map, so it has none.
pub fn labels(&self) -> Vec<String> {
match self {
Self::Boolean => Vec::new(),
Self::Choice(criteria) => criteria.iter().map(|(label, _)| label.clone()).collect(),
Self::Score(levels) => levels.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Question {
pub id: String,
pub instructions: String,
pub body: QuestionBody,
}
/// A whole question set, in declared order. Order is significant: it is part
/// of the request and part of the cache identity.
#[derive(Clone, Debug, PartialEq, Eq, Default, serde::Serialize)]
pub struct QuestionSet {
pub questions: Vec<Question>,
}
fn text(value: Option<&VmValue>) -> Option<String> {
match value? {
VmValue::String(text) => Some(text.to_string()),
_ => None,
}
}
impl QuestionSet {
/// Read the question set out of the argument the VM passed.
///
/// A shape the contract does not describe is a runtime type error, not a
/// `question_invalid`: the checker owns the shape and only a caller
/// bypassing it can get here.
pub fn from_value(value: &VmValue) -> Result<Self, String> {
let Some(entries) = value.as_dict() else {
return Err(format!(
"evaluation questions must be a dict of question id to question, got {}",
value.type_name()
));
};
let mut questions = Vec::with_capacity(entries.len());
for (id, question) in entries.iter() {
let id = id.to_string();
let Some(fields) = question.as_dict() else {
return Err(format!("question `{id}` is not a question record"));
};
let instructions = text(fields.get("instructions"))
.ok_or_else(|| format!("question `{id}` has no string instructions"))?;
let kind = text(fields.get("kind"))
.ok_or_else(|| format!("question `{id}` has no question kind"))?;
let body = match kind.as_str() {
"boolean" => QuestionBody::Boolean,
"choice" => {
let criteria = fields
.get("criteria")
.and_then(VmValue::as_dict)
.ok_or_else(|| format!("choice question `{id}` has no criteria"))?;
QuestionBody::Choice(
criteria
.iter()
.map(|(label, description)| {
Ok((
label.to_string(),
text(Some(description)).ok_or_else(|| {
format!("choice question `{id}` has a non-string criterion")
})?,
))
})
.collect::<Result<Vec<_>, String>>()?,
)
}
"score" => {
let VmValue::List(levels) = fields
.get("levels")
.ok_or_else(|| format!("score question `{id}` has no levels"))?
else {
return Err(format!("score question `{id}` has non-list levels"));
};
QuestionBody::Score(
levels
.iter()
.map(|level| {
text(Some(level)).ok_or_else(|| {
format!("score question `{id}` has a non-string level")
})
})
.collect::<Result<Vec<_>, String>>()?,
)
}
other => return Err(format!("question `{id}` has unknown kind `{other}`")),
};
questions.push(Question {
id,
instructions,
body,
});
}
Ok(Self { questions })
}
pub fn is_empty(&self) -> bool {
self.questions.is_empty()
}
/// The declared ids, in order. Read by the mock backend's request log.
#[cfg(test)]
pub fn ids(&self) -> Vec<String> {
self.questions
.iter()
.map(|question| question.id.clone())
.collect()
}
/// Check the set against what the route declared. The first refusal wins,
/// and it is returned rather than thrown so the caller gets a typed
/// outcome instead of an error to catch.
pub fn admit(&self, contract: &DecisionContract) -> Result<(), QuestionRefusal> {
let limits = &contract.limits;
if let Some(max) = limits.max_questions {
if self.questions.len() > max {
return Err(QuestionRefusal {
question: String::new(),
reason: QuestionRefusalReason::TooManyQuestions,
});
}
}
for question in &self.questions {
let refuse = |reason| {
Err(QuestionRefusal {
question: question.id.clone(),
reason,
})
};
if question.instructions.trim().is_empty() {
return refuse(QuestionRefusalReason::EmptyInstructions);
}
if !contract.supports(question.body.kind()) {
return refuse(QuestionRefusalReason::UnsupportedQuestionKind);
}
match &question.body {
QuestionBody::Boolean => {}
QuestionBody::Choice(criteria) => {
if criteria.len() > limits.max_choice_options {
return refuse(QuestionRefusalReason::TooManyOptions);
}
// A degenerate one-label choice is not refused here. The
// union has no `too_few_options` reason, and labelling it
// `too_many_options` would put a false cause on the
// receipt. The checker already refuses a choice with no
// labels at all, which is the case that types no answer.
}
QuestionBody::Score(levels) => {
if levels.len() < limits.score_levels_min {
return refuse(QuestionRefusalReason::TooFewLevels);
}
if levels.len() > limits.score_levels_max {
return refuse(QuestionRefusalReason::TooManyLevels);
}
}
}
}
Ok(())
}
}