eureka-state door: a decode refusal names the field path, never a value

Documents decode one by one through serde_path_to_error, so the refusal says
documents[i].path and what is wrong, in the schema's words: a field name, the
allowed variants, the expected type. Serde's own text quotes the input, so it
is not passed through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-04 22:45:48 +01:00
commit 51853c1ac1
5 changed files with 101 additions and 16 deletions

1
Cargo.lock generated
View file

@ -647,6 +647,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
"serde_path_to_error",
"tempfile",
"tokio",
]

View file

@ -40,6 +40,7 @@ rmp-serde = "1"
schemars = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_path_to_error = "0.1"
tokio = { version = "1", features = ["rt", "macros", "io-std"] }
# Tests run a real daemon in-process against a temporary mind, and the real

View file

@ -32,11 +32,17 @@ impl Refusal {
/// A batch: a JSON array of `{kind, value}` documents, or one such object.
pub fn documents(text: &str) -> Result<Vec<PipelineDocument>, Refusal> {
let value = parse(text)?;
let (items, typed): (&[Value], Vec<PipelineDocument>) = match &value {
Value::Array(items) => (items.as_slice(), objects(items).and_then(|()| from_text(text, "documents"))?),
Value::Object(_) => (std::slice::from_ref(&value), vec![from_text(text, "documents[0]")?]),
let items: &[Value] = match &value {
Value::Array(items) => items,
Value::Object(_) => std::slice::from_ref(&value),
_ => return Err(Refusal::invalid("the documents must be a JSON array of {kind, value} objects")),
};
objects(items)?;
let typed = items
.iter()
.enumerate()
.map(|(index, item)| decode(item, &format!("documents[{index}]")))
.collect::<Result<Vec<PipelineDocument>, Refusal>>()?;
let kept = reserialise(&typed, "documents")?;
let mut lost = Vec::new();
for (index, (given, held)) in items.iter().zip(&kept).enumerate() {
@ -51,7 +57,7 @@ pub fn selection(text: &str) -> Result<Selection, Refusal> {
if !value.is_object() {
return Err(Refusal::invalid("selection must be a JSON object"));
}
let typed: Selection = from_text(text, "selection")?;
let typed: Selection = decode(&value, "selection")?;
let kept = reserialise(std::slice::from_ref(&typed), "selection")?;
let mut lost = Vec::new();
dropped(&value, &kept[0], "selection", &mut lost);
@ -88,10 +94,32 @@ fn objects(items: &[Value]) -> Result<(), Refusal> {
}
}
/// The typed value of the text, decoded from the text itself so the failure
/// has a real line and column.
fn from_text<T: DeserializeOwned>(text: &str, at: &str) -> Result<T, Refusal> {
serde_json::from_str(text).map_err(|error| Refusal::invalid(format!("{at} does not decode: {}", place(&error))))
/// The typed value of an input, or the path of the field that does not fit and
/// what is wrong with it. Serde's own messages quote the given value, so only
/// the schema's words are kept: a field name, the allowed variants, the
/// expected type.
fn decode<T: DeserializeOwned>(input: &Value, at: &str) -> Result<T, Refusal> {
serde_path_to_error::deserialize(input).map_err(|error| {
let path = error.path().to_string();
let place = if path == "." { at.to_string() } else { format!("{at}.{path}") };
Refusal::invalid(format!("{place}: {}", schema_words(&error.into_inner().to_string())))
})
}
/// What a serde message says about the schema, without the value it was given.
fn schema_words(message: &str) -> String {
if message.starts_with("missing field `") {
return message.to_string();
}
let expected = message.rfind(", expected ").map(|at| &message[at + ", expected ".len()..]);
match (message, expected) {
(m, Some(expected)) if m.starts_with("unknown variant") => format!("unknown variant, expected {expected}"),
(m, Some(expected)) if m.starts_with("invalid type") => format!("wrong type, expected {expected}"),
(m, Some(expected)) if m.starts_with("invalid value") || m.starts_with("invalid length") => {
format!("wrong value, expected {expected}")
}
_ => "a value the schema refuses".to_string(),
}
}
/// What the typed values hold, as the JSON items to compare with the input.

View file

@ -30,6 +30,14 @@ use tempfile::TempDir;
mod common;
use common::*;
/// A well-formed research note, as a document.
fn research_json() -> Value {
json!({ "kind": "research", "value": {
"campaign": "eureka-state", "pass": "p", "label": "a", "claim": "A fact.", "detail": "",
"inferred": false, "sources": [{ "Observed": { "evidence": { "kind": "Test", "locator": "cargo test", "result": "ok" } } }],
"serves": [], "observed_on": "2026-11-04" } })
}
struct Run {
code: i32,
out: String,
@ -413,7 +421,7 @@ fn a_falsy_unknown_value_is_still_a_loss() {
fn a_document_that_does_not_decode_is_invalid_input() {
let dir = tempfile::tempdir().unwrap();
let cases = [
(json!([{ "kind": "nonsense", "value": {} }]), "documents does not decode"),
(json!([{ "kind": "nonsense", "value": {} }]), "documents[0]: unknown variant, expected"),
(json!("text"), "JSON array"),
(json!([[]]), "documents[0] must be a JSON object"),
(json!([]), "1 to 64"),
@ -444,19 +452,29 @@ fn a_document_that_does_not_decode_never_echoes_its_values() {
let unknown_kind = json!({ "kind": "CANARY-KIND", "value": {} });
let mut unknown_variant = serde_json::to_value(ruling(None)).unwrap();
unknown_variant["value"]["authority"] = json!("CANARY-VARIANT");
for (n, document) in [string_for_number, long_string_for_list, unknown_kind, unknown_variant].into_iter().enumerate() {
let file = write(&dir, &format!("canary{n}.json"), &json!([document]));
let mut second_missing_claim = research_json();
second_missing_claim["value"].as_object_mut().unwrap().remove("claim");
let cases = [
(vec![string_for_number], "documents[0].value.attempt: wrong type, expected"),
(vec![long_string_for_list], "documents[0].value.repos: wrong type, expected"),
(vec![unknown_kind], "documents[0]: unknown variant, expected"),
(vec![unknown_variant], "documents[0].value.authority: unknown variant, expected"),
(vec![campaign_json(), second_missing_claim], "documents[1].value: missing field `claim`"),
];
for (n, (documents, expected)) in cases.into_iter().enumerate() {
let file = write(&dir, &format!("canary{n}.json"), &json!(documents));
let ran = at(closed_port(), &admit_args(&file), None);
assert_eq!(ran.code, 2, "case {n}: {}", ran.err);
assert!(ran.err.starts_with("InvalidInput: documents does not decode: "), "case {n}: {}", ran.err);
assert!(ran.err.contains(" at line 1 column "), "case {n}: {}", ran.err);
assert!(ran.err.starts_with("InvalidInput: "), "case {n}: {}", ran.err);
assert!(ran.err.contains(expected), "case {n} wants {expected}: {}", ran.err);
assert!(!ran.err.contains(" at line "), "no position in JSON the client never saw: {}", ran.err);
assert!(!ran.err.contains("CANARY") && !ran.out.contains("CANARY"), "case {n}: {}", ran.err);
assert!(ran.err.len() < 300, "stderr is bounded whatever the input: {} bytes", ran.err.len());
assert!(ran.err.len() < 600, "stderr is bounded whatever the input: {} bytes", ran.err.len());
}
let ran = at(closed_port(), &["query", r#"{"limit": "CANARY-LIMIT"}"#], None);
assert_eq!(ran.code, 2);
assert!(ran.err.starts_with("InvalidInput: selection does not decode: "), "{}", ran.err);
assert!(!ran.err.contains("CANARY") && ran.err.len() < 300, "{}", ran.err);
assert!(ran.err.starts_with("InvalidInput: selection.limit: wrong type, expected"), "{}", ran.err);
assert!(!ran.err.contains("CANARY") && ran.err.len() < 600, "{}", ran.err);
let ran = at(closed_port(), &admit_args("-"), Some(r#"[{"kind": "campaign", "value": CANARY-SYNTAX}]"#));
assert_eq!(ran.code, 2);
assert!(ran.err.starts_with("InvalidInput: not JSON: syntax at line 1 column "), "{}", ran.err);

View file

@ -652,3 +652,40 @@ fn admit_refuses_keys_the_schema_does_not_know_and_stores_nothing() {
assert!(!error, "{admitted}");
assert!(admitted.get("Committed").is_some(), "{admitted}");
}
/// A document that does not decode is refused naming the path of the field to
/// fix, with the batch index, and never a value of the input or a position in
/// JSON the client did not send. Nothing is stored.
#[test]
fn admit_names_the_path_of_a_field_that_does_not_decode_and_never_a_value() {
let (root, daemon) = mind(vec![vec![stewardship()]]);
let server = serve(root, daemon);
let mut mcp = Mcp::at(INSTANCE, server.addr);
let research = json!({ "kind": "research", "value": {
"campaign": CAMPAIGN, "pass": "p", "label": "a", "claim": "A fact.", "detail": "",
"inferred": false, "sources": [{ "Observed": { "evidence": { "kind": "Test", "locator": "cargo test", "result": "ok" } } }],
"serves": [], "observed_on": "2026-11-04" } });
let mut missing_claim = research.clone();
missing_claim["value"].as_object_mut().unwrap().remove("claim");
let mut wrong_type = research.clone();
wrong_type["value"]["sources"][0]["Observed"]["evidence"]["locator"] = json!(["CANARY-TYPE"]);
let mut wrong_variant = research.clone();
wrong_variant["value"]["sources"][0]["Observed"]["evidence"]["kind"] = json!("CANARY-VARIANT");
let unknown_kind = json!({ "kind": "CANARY-KIND", "value": {} });
let cases = [
(missing_claim, "documents[1].value: missing field `claim`"),
(wrong_type, "documents[1].value.sources[0].Observed.evidence.locator: wrong type, expected"),
(wrong_variant, "documents[1].value.sources[0].Observed.evidence.kind: unknown variant, expected"),
(unknown_kind, "documents[1]: unknown variant, expected"),
];
for (document, expected) in cases {
let (error, refused) = mcp.call("admit", faculty_args(vec![campaign_json(), document]));
assert!(error, "{refused}");
assert_eq!(refused["error"], json!("InvalidInput"), "{refused}");
let detail = refused["detail"].as_str().unwrap();
assert!(detail.contains(expected), "wants {expected}: {detail}");
assert!(!detail.contains(" at line ") && !detail.contains("CANARY"), "{detail}");
}
let (_, whoami) = mcp.call("whoami", json!({}));
assert_eq!(whoami["status"]["receipts"], json!(2), "nothing stored: {whoami}");
}