1use crate::bounded::ParseLimits;
8use crate::{Document, schema};
9
10pub(crate) fn digest_schema() -> schemars::Schema {
12 schemars::json_schema!({
13 "type": "string",
14 "pattern": "^sha256:[0-9a-f]{64}$"
15 })
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct EmittedSchema {
22 pub file: String,
23 pub bytes: Vec<u8>,
24}
25
26const COMMENT: &str = "Descriptive, derived from the types the bounded parser reads; the parser \
39is the only authority on validity. Where the parser reads two versions of a document with one \
40type, this schema admits what that type admits, including members the later version adds. \
41Byte, depth and count bounds are recorded in x-rustev-parse-limits (a string length here counts \
42characters, the parser counts bytes), and rules applied when a plan is compiled are stated in \
43field descriptions, not enforced here.";
44
45fn emit<T: schemars::JsonSchema + Document>(version: &str, part: Option<&str>) -> EmittedSchema {
46 emit_adjusted::<T>(version, part, |_| {})
47}
48
49fn emit_adjusted<T: schemars::JsonSchema + Document>(
53 version: &str,
54 part: Option<&str>,
55 adjust: impl FnOnce(&mut serde_json::Value),
56) -> EmittedSchema {
57 let generator = schemars::generate::SchemaSettings::draft2020_12().into_generator();
58 let root = generator.into_root_schema_for::<T>();
59 let mut v = serde_json::to_value(&root).expect("a schema is JSON");
60 adjust(&mut v);
61 let title = match part {
62 Some(p) => format!("{version} {p}"),
63 None => version.to_string(),
64 };
65 v["title"] = title.clone().into();
66 v["$comment"] = COMMENT.into();
67 v.get_mut("properties")
72 .and_then(|p| p.as_object_mut())
73 .unwrap_or_else(|| panic!("{title}: the derived schema has no properties"))
74 .insert(
75 "schema".into(),
76 serde_json::json!({ "type": "string", "const": version }),
77 );
78 v["x-rustev-parse-limits"] = limits(&T::LIMITS);
79 let file = format!(
80 "{}{}.schema.json",
81 version.replace('/', "-"),
82 part.map(|p| format!(".{p}")).unwrap_or_default()
83 );
84 let bytes = crate::canonical::canonical_value_bytes(&v).expect("a schema has canonical bytes");
85 EmittedSchema { file, bytes }
86}
87
88const RUN_V2_MEMBERS: [&str; 2] = ["remote_evidence", "remote_evidence_truncated"];
92
93fn run_members(version: &str) -> impl FnOnce(&mut serde_json::Value) + '_ {
94 move |v| {
95 if version != schema::RUN_V3 {
96 extraction_v1(v, "/$defs/EvidenceRecord/properties");
97 v["$defs"]["EvidenceRecord"]["properties"]
98 .as_object_mut()
99 .unwrap()
100 .remove("generation");
101 v["$defs"]["EvidenceRecord"]["properties"]
102 .as_object_mut()
103 .unwrap()
104 .remove("acquisitions");
105 v["$defs"]["StepEvidence"]["properties"]
106 .as_object_mut()
107 .unwrap()
108 .remove("constructed");
109 if let Some(p) = v["$defs"]["StepEvidence"]["properties"].as_object_mut() {
111 p.remove("ranking");
112 p.remove("selection");
113 }
114 v["$defs"]["StepStatus"]["oneOf"]
115 .as_array_mut()
116 .unwrap()
117 .retain(|v| v["properties"].get("skipped").is_none());
118 v["properties"]
119 .as_object_mut()
120 .unwrap()
121 .remove("acquisitions");
122 v["$defs"]["RequestRecord"]["properties"]
123 .as_object_mut()
124 .unwrap()
125 .remove("screen");
126 v["$defs"]["RequestResult"]["oneOf"]
127 .as_array_mut()
128 .unwrap()
129 .retain(|variant| variant["const"] != "withdrawn");
130 prune_defs(v);
131 }
132 if version == schema::RUN_V2 {
133 v["required"]
136 .as_array_mut()
137 .expect("the run record has required members")
138 .push(RUN_V2_MEMBERS[0].into());
139 let list = &mut v["properties"][RUN_V2_MEMBERS[0]];
140 assert_eq!(
141 list["type"],
142 serde_json::json!(["array", "null"]),
143 "the remote evidence list is derived as an optional array"
144 );
145 list["type"] = "array".into();
146 return;
147 }
148 let props = v["properties"]
149 .as_object_mut()
150 .expect("the run record has properties");
151 for m in RUN_V2_MEMBERS {
152 props
153 .remove(m)
154 .unwrap_or_else(|| panic!("the run record has no {m} member"));
155 }
156 prune_defs(v);
157 }
158}
159
160fn plan_members(version: &str) -> impl FnOnce(&mut serde_json::Value) + '_ {
163 move |v| {
164 if version != schema::PLAN_V3 {
165 if let Some(variants) = v["$defs"]["PlanStepDetail"]["oneOf"].as_array_mut() {
166 variants.retain(|v| {
167 [
168 "generate",
169 "extract",
170 "accept_model_derived",
171 "rank",
172 "select",
173 ]
174 .iter()
175 .all(|key| v["properties"].get(*key).is_none())
176 });
177 }
178 v["properties"]
179 .as_object_mut()
180 .unwrap()
181 .remove("acquisitions");
182 v["properties"]
183 .as_object_mut()
184 .expect("the plan has properties")
185 .remove("instantiation")
186 .expect("the plan has an instantiation member");
187 v["properties"]
188 .as_object_mut()
189 .unwrap()
190 .remove("screening")
191 .expect("the plan has a screening member");
192 prune_defs(v);
193 }
194 }
195}
196
197fn extract_rules_v1(v: &mut serde_json::Value) {
201 v["properties"]
202 .as_object_mut()
203 .expect("the program has properties")
204 .remove("month_tables")
205 .expect("the program has a month_tables member");
206 for (ty, added) in [
207 ("ExtractionCondition", &["equals", "one_of"][..]),
208 (
209 "ExtractionValue",
210 &["token_after", "token_matching", "date", "vocabulary_after"][..],
211 ),
212 ] {
213 let variants = v["$defs"][ty]["oneOf"]
214 .as_array_mut()
215 .unwrap_or_else(|| panic!("{ty} is a oneOf"));
216 let before = variants.len();
217 variants.retain(|v| added.iter().all(|key| v["properties"].get(*key).is_none()));
218 assert_eq!(
219 before - variants.len(),
220 added.len(),
221 "{ty}: version 2 variants"
222 );
223 }
224 prune_defs(v);
225}
226
227fn extraction_v1(v: &mut serde_json::Value, evidence_properties: &str) {
229 if let Some(props) = v
230 .pointer_mut(evidence_properties)
231 .and_then(|p| p.as_object_mut())
232 {
233 props.remove("extraction");
234 props.remove("acceptance");
235 }
236 for (ty, member) in [("Lineage", "producers"), ("InputEvidence", "producer")] {
237 if let Some(props) = v["$defs"][ty]["properties"].as_object_mut() {
238 props.remove(member);
239 }
240 }
241 if let Some(variants) = v["$defs"]["OutValue"]["oneOf"].as_array_mut() {
242 variants.retain(|v| v["properties"].get("attributed").is_none());
243 }
244}
245
246fn prune_defs(v: &mut serde_json::Value) {
249 fn refs(v: &serde_json::Value, out: &mut Vec<String>) {
250 match v {
251 serde_json::Value::Object(m) => {
252 if let Some(r) = m.get("$ref").and_then(|r| r.as_str())
253 && let Some(name) = r.strip_prefix("#/$defs/")
254 {
255 out.push(name.to_string());
256 }
257 m.values().for_each(|x| refs(x, out));
258 }
259 serde_json::Value::Array(a) => a.iter().for_each(|x| refs(x, out)),
260 _ => {}
261 }
262 }
263 let Some(defs) = v.get("$defs").cloned() else {
264 return;
265 };
266 let mut root = v.clone();
267 root.as_object_mut().unwrap().remove("$defs");
268 let mut pending = Vec::new();
269 refs(&root, &mut pending);
270 let mut reached = std::collections::BTreeSet::new();
271 while let Some(name) = pending.pop() {
272 if reached.insert(name.clone())
273 && let Some(d) = defs.get(&name)
274 {
275 refs(d, &mut pending);
276 }
277 }
278 let kept: serde_json::Map<String, serde_json::Value> = defs
279 .as_object()
280 .unwrap()
281 .iter()
282 .filter(|(k, _)| reached.contains(*k))
283 .map(|(k, d)| (k.clone(), d.clone()))
284 .collect();
285 v["$defs"] = kept.into();
286}
287
288fn limits(l: &ParseLimits) -> serde_json::Value {
289 serde_json::json!({
290 "max_bytes": l.max_bytes,
291 "max_depth": l.max_depth,
292 "max_string_bytes": l.max_string_bytes,
293 "max_collection_len": l.max_collection_len,
294 "max_total_values": l.max_total_values,
295 "max_number_bytes": l.max_number_bytes,
296 "allow_fractional_numbers": l.allow_fractional_numbers,
297 })
298}
299
300pub fn document_schemas() -> Vec<EmittedSchema> {
302 use crate::{
303 calibration::CalibrationArtifact, definition::Definition, descriptor::BackendDescriptor,
304 eval_report::EvalReport, evidence::EvidenceRecord, execution::ExecutionPolicy,
305 judgment::Judgment, output::BackendOutputDoc, plan::Plan, reason::RuntimeReasonDoc, remote,
306 replay::ReplayBundle, request::RequestDoc, run::RunRecord, snapshot::Snapshot,
307 source::SourceDescriptor,
308 };
309 use crate::{
312 dynamic::{DynamicCapability, DynamicOutcome, DynamicQuestion},
313 live::LiveReexecution,
314 redaction::{REDACTION, RedactionPolicy},
315 trace::{TRACE, TraceLine},
316 };
317 let mut out = vec![
318 emit::<crate::explanation::Explanation>(schema::EXPLANATION, None),
319 emit::<crate::generation_result::TextResult>(schema::TEXT_RESULT, None),
320 emit::<crate::generation::PromptTemplate>(schema::PROMPT_TEMPLATE, None),
321 emit::<crate::generation::GenerateRequest>(schema::GENERATE_REQUEST, None),
322 emit_adjusted::<crate::extraction_documents::ExtractRules>(
323 schema::EXTRACT_RULES,
324 None,
325 extract_rules_v1,
326 ),
327 emit::<crate::extraction_documents::ExtractRules>(schema::EXTRACT_RULES_V2, None),
328 emit::<crate::extraction_documents::ExtractRequest>(schema::EXTRACT_REQUEST, None),
329 emit::<crate::profile::Profile>(schema::PROFILE, None),
330 emit::<crate::plan_diff::PlanDiff>(schema::PLAN_DIFF, None),
331 emit::<Definition>(schema::DEFINITION, None),
332 emit::<Definition>(schema::DEFINITION_V2, None),
333 emit_adjusted::<Plan>(schema::PLAN, None, plan_members(schema::PLAN)),
334 emit_adjusted::<Plan>(schema::PLAN_V3, None, plan_members(schema::PLAN_V3)),
335 emit::<Snapshot>(schema::SNAPSHOT, None),
336 emit::<Snapshot>(schema::SNAPSHOT_V2, None),
337 emit_adjusted::<EvidenceRecord>(schema::EVIDENCE, None, |v| {
338 extraction_v1(v, "/properties");
339 v["properties"].as_object_mut().unwrap().remove("screening");
340 v["properties"]
341 .as_object_mut()
342 .unwrap()
343 .remove("generation");
344 v["properties"]
345 .as_object_mut()
346 .unwrap()
347 .remove("acquisitions");
348 v["$defs"]["StepEvidence"]["properties"]
349 .as_object_mut()
350 .unwrap()
351 .remove("constructed");
352 if let Some(p) = v["$defs"]["StepEvidence"]["properties"].as_object_mut() {
354 p.remove("ranking");
355 p.remove("selection");
356 }
357 v["$defs"]["StepStatus"]["oneOf"]
358 .as_array_mut()
359 .unwrap()
360 .retain(|v| v["properties"].get("skipped").is_none());
361 prune_defs(v);
362 }),
363 emit::<EvidenceRecord>(schema::EVIDENCE_V2, None),
364 emit_adjusted::<RunRecord>(schema::RUN, None, run_members(schema::RUN)),
365 emit_adjusted::<RunRecord>(schema::RUN_V2, None, run_members(schema::RUN_V2)),
366 emit_adjusted::<RunRecord>(schema::RUN_V3, None, run_members(schema::RUN_V3)),
367 emit_adjusted::<Judgment>(schema::JUDGMENT, None, |v| {
368 extraction_v1(v, "/properties");
369 prune_defs(v);
370 }),
371 emit::<Judgment>(schema::JUDGMENT_V2, None),
372 emit::<BackendDescriptor>(schema::BACKEND, None),
373 emit::<CalibrationArtifact>(schema::CALIBRATION, None),
374 emit::<BackendOutputDoc>(schema::BACKEND_OUTPUT, None),
375 emit::<EvalReport>(schema::EVAL_REPORT, None),
376 emit::<ExecutionPolicy>(schema::EXECUTION, None),
377 emit_adjusted::<ReplayBundle>(schema::REPLAY, None, |v| {
378 for key in ["sources", "acquisition_pages"] {
379 v["properties"].as_object_mut().unwrap().remove(key);
380 }
381 v["$defs"]["SupplyEntry"]["properties"]
382 .as_object_mut()
383 .unwrap()
384 .remove("failure_context");
385 prune_defs(v);
386 }),
387 emit::<ReplayBundle>(schema::REPLAY_V2, None),
388 emit::<RequestDoc>(schema::REQUEST, None),
389 emit::<RuntimeReasonDoc>(schema::RUNTIME_REASON, None),
390 emit::<crate::acquisition::AcquisitionRequest>(schema::ACQUISITION_REQUEST, None),
391 emit::<crate::acquisition::AcquisitionPage>(schema::ACQUISITION_PAGE, None),
392 emit::<SourceDescriptor>(schema::SOURCE, None),
393 emit::<remote::DescribeRequest>(schema::REMOTE_DESCRIBE, Some("request")),
394 emit::<remote::DescribeResponse>(schema::REMOTE_DESCRIBE, Some("response")),
395 emit::<remote::InferRequest>(schema::REMOTE_INFER, Some("request")),
396 emit::<remote::InferResponse>(schema::REMOTE_INFER, Some("response")),
397 emit::<remote::CancelRequest>(schema::REMOTE_CANCEL, Some("request")),
398 emit::<remote::CancelResponse>(schema::REMOTE_CANCEL, Some("response")),
399 emit::<remote::ExchangeRecord>(schema::REMOTE_EXCHANGE, None),
400 emit::<DynamicQuestion>(schema::DYNAMIC_QUESTION, None),
401 emit::<DynamicCapability>(schema::DYNAMIC_CAPABILITY, None),
402 emit::<DynamicOutcome>(schema::DYNAMIC_OUTCOME, None),
403 emit::<LiveReexecution>(schema::LIVE_REEXECUTION, None),
404 emit::<crate::cache_entry::CacheEntry>(schema::CACHE_ENTRY, None),
405 emit::<RedactionPolicy>(REDACTION, None),
406 emit::<TraceLine>(TRACE, None),
407 ];
408 out.extend([
409 emit::<crate::remote_context::DescribeRequest>(
410 crate::remote_context::DESCRIBE,
411 Some("request"),
412 ),
413 emit::<crate::remote_context::DescribeResponse>(
414 crate::remote_context::DESCRIBE,
415 Some("response"),
416 ),
417 emit::<crate::remote_context::FetchRequest>(crate::remote_context::FETCH, Some("request")),
418 emit::<crate::remote_context::FetchResponse>(
419 crate::remote_context::FETCH,
420 Some("response"),
421 ),
422 emit::<crate::remote_context::CancelRequest>(
423 crate::remote_context::CANCEL,
424 Some("request"),
425 ),
426 emit::<crate::remote_context::CancelResponse>(
427 crate::remote_context::CANCEL,
428 Some("response"),
429 ),
430 emit::<crate::remote_context::Invalidation>(crate::remote_context::INVALIDATION, None),
431 emit::<crate::remote_context::InvalidationsRequest>(
432 crate::remote_context::INVALIDATIONS,
433 Some("request"),
434 ),
435 emit::<crate::remote_context::InvalidationsResponse>(
436 crate::remote_context::INVALIDATIONS,
437 Some("response"),
438 ),
439 emit::<crate::remote_context::ExchangeRecord>(crate::remote_context::EXCHANGE, None),
440 emit::<crate::remote_context::AcquireRequest>(
441 crate::remote_context::ACQUIRE,
442 Some("request"),
443 ),
444 emit::<crate::remote_context::AcquireResponse>(
445 crate::remote_context::ACQUIRE,
446 Some("response"),
447 ),
448 emit::<crate::remote_sink::DescribeRequest>(crate::remote_sink::DESCRIBE, Some("request")),
449 emit::<crate::remote_sink::DescribeResponse>(
450 crate::remote_sink::DESCRIBE,
451 Some("response"),
452 ),
453 emit::<crate::remote_sink::DeliverRequest>(crate::remote_sink::DELIVER, Some("request")),
454 emit::<crate::remote_sink::DeliverResponse>(crate::remote_sink::DELIVER, Some("response")),
455 emit::<crate::serve::Serve>(crate::serve::Serve::SCHEMA, None),
456 emit::<crate::serve::ServeConfig>(crate::serve::ServeConfig::SCHEMA, None),
457 emit::<crate::serve::ServeService>(crate::serve::ServeService::SCHEMA, None),
458 emit::<crate::serve::ServeRegister>(crate::serve::ServeRegister::SCHEMA, None),
459 emit::<crate::serve::ServeDecide>(crate::serve::ServeDecide::SCHEMA, None),
460 emit::<crate::serve::ServeDecision>(crate::serve::ServeDecision::SCHEMA, None),
461 emit::<crate::serve::ServeDecisionState>(crate::serve::ServeDecisionState::SCHEMA, None),
462 emit::<crate::serve::ServeCancel>(crate::serve::ServeCancel::SCHEMA, None),
463 emit::<crate::serve::ServeEvent>(crate::serve::ServeEvent::SCHEMA, None),
464 emit::<crate::serve::ServeRefusal>(crate::serve::ServeRefusal::SCHEMA, None),
465 emit::<crate::serve::ServeReplay>(crate::serve::ServeReplay::SCHEMA, None),
466 emit::<crate::serve::ServeEvaluate>(crate::serve::ServeEvaluate::SCHEMA, None),
467 emit::<crate::serve::ServeExplain>(crate::serve::ServeExplain::SCHEMA, None),
468 emit::<crate::serve::ServeExplanation>(crate::serve::ServeExplanation::SCHEMA, None),
469 emit::<crate::serve::ServeReadiness>(crate::serve::ServeReadiness::SCHEMA, None),
470 emit::<crate::serve::ServeShutdown>(crate::serve::ServeShutdown::SCHEMA, None),
471 emit::<crate::serve::ServeInvalidations>(crate::serve::ServeInvalidations::SCHEMA, None),
472 emit::<crate::serve::ServeInvalidationsAck>(
473 crate::serve::ServeInvalidationsAck::SCHEMA,
474 None,
475 ),
476 emit::<crate::plan_bundle::PlanBundle>(crate::plan_bundle::PlanBundle::SCHEMA, None),
477 emit::<crate::plan_bundle::PlanBundleSignature>(
478 crate::plan_bundle::PlanBundleSignature::SCHEMA,
479 None,
480 ),
481 emit::<crate::plan_bundle::PlanRegistration>(
482 crate::plan_bundle::PlanRegistration::SCHEMA,
483 None,
484 ),
485 ]);
486 out.sort_by(|a, b| a.file.cmp(&b.file));
487 out
488}