Skip to content

impl(042): increment 6 part 2, the explanation handler - #430

Merged
bartekus merged 1 commit into
mainfrom
impl/042-explain-handler
Oct 31, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/042-explain-handler

Conversation

@bartekus

Copy link
Copy Markdown
Contributor

Spec 042 increment 6 part 2: the explanation handler (3.8.3, as amended by #404; documents from #411).

  • POST /v1/explain and gRPC Explain run on the blocking pool and honor the deadline header.
  • The request's options.scope must equal the scope the host resolves for the caller's principal; otherwise the answer is decision_not_found and nothing is resolved or explained.
  • scope or now_ms given without a bundle side, or missing with one, is invalid_request.
  • Evidence references resolve only under the configured roots; a .. reference or a missing file is refused.
  • The redaction policy is the one the listener the request arrived on names; a listener with none explains unredacted.
  • Spec 040 refusals answer invalid_document, with spec 040's code in detail.
  • The service lists explain among its available endpoints.

Contract fix: the request documents merged in #411 could not parse evidence embedded as a document (only references parsed). crates/rustev-contract now parses evidence and diff queries in both forms; the accepted shapes and the committed JSON Schema are unchanged. A contract test covers embedded documents.

Tests: every explain golden that does not pass the library its own resolver runs through HTTP/2 JSON and gRPC, byte-identical to the golden, including the two redaction cases; a scope and reference test covers a scope mismatch, a reference under a configured root, a .. reference and a missing file.

Local checks: make gate, cargo fmt --all --check, clippy -D warnings, the full rustev-serve and rustev-contract test suites, spec-spine couple and scripts/check-authored-content.sh.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Looking at the PR diff, I'll review the changes for the explanation handler implementation across serve.rs, offline.rs, transport.rs, service.rs, and the handler tests.

serve.rs — Custom Deserialize for ExplainEvidence and ExplainQuery

The EvidenceMembers struct and the manual Deserialize impl for ExplainEvidence correctly use #[serde(default, deserialize_with = "present")] to distinguish "field absent" from "field present". The match arm (Some(record), plan, None) accepts {record} and {record, plan} in any key order (struct-field matching is order-independent). The ExplainQuery visitor enforces "one member" and correctly reconstructs a serde_json::Value for non-diff keys. Both implementations preserve the same JSON Schema surface. No issues here.

offline.rs — explain function

The scope-check logic is correct: bundle cases require both scope and now_ms matching the caller's resolved scope (DecisionNotFound on mismatch, InvalidRequest otherwise); non-bundle cases require both absent. The side helper namespaces keys as "a.member" / "b.member" before handing them to rustev_surface::explain. The explain_refusal path uses expect on a library-defined enum's as_str(); this is safe for fixed short strings.

transport.rs and service.rs

Explain is correctly added to needs_principal and has_body match arms, and the filter excluding Explain from available_endpoints is removed. The redaction policy is forwarded from the listener to offline::run.

Test bug — form lambda in every_explain_golden_through_both_transports

// handlers.rs, inside explain_goldens()
let form = |v: &Value| {
    let keys: Vec<&str> = v.as_object().unwrap().keys().map(String::as_str).collect();
    matches!(
        keys.as_slice(),
        ["bundle"] | ["record"] | ["plan", "record"]   // ← order-sensitive
    )
};

serde_json::Value::Object preserves key insertion order. A conformance case JSON file with {"record": ..., "plan": ...} (record before plan) produces keys = ["record", "plan"], which does not match ["plan", "record"]. The test then sets forms = false and calls refused(&answer, RefusalCode::InvalidDocument, ""), but the handler would return a successful explanation because EvidenceMembers deserializes order-independently. Any such conformance case would cause a spurious test failure; the check contradicts the deserialization semantics it is meant to model.

{"head": "c0b9051a8e8c0b50426a4eee4c4119eea7c60e60", "verdict": "findings", "findings": [{"path": "integrations/rustev-serve/tests/handlers.rs", "line": null, "summary": "The `form` closure in `every_explain_golden_through_both_transports` uses `matches!(keys.as_slice(), … | [\"plan\", \"record\"])`, which is order-sensitive; a conformance case with keys in `[\"record\", \"plan\"]` order is misclassified as invalid form and the test asserts `InvalidDocument` when the handler would return a successful explanation."}]}

Subject: 682bde9...c0b9051, diff digest 93b8e341ba84185d43f0741e452e35e17916b13077900e440f3a05d8a63ecc9f, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 31, 2026 01:36 — with GitHub Actions Error
Spec 042 3.8.3: POST /v1/explain and gRPC Explain run the library's
explanation through rustev-surface on the blocking pool, with the caller's
scope checked, references read under the configured roots, the listener's
redaction policy, and spec 040 refusals as invalid_document. The request
documents now parse embedded evidence, which the untagged enums never
could.
@bartekus
bartekus force-pushed the impl/042-explain-handler branch from c0b9051 to d587104 Compare October 31, 2026 01:37
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff carefully across all changed files.

crates/rustev-contract/src/serve.rs — Custom Deserialize impls for ExplainEvidence and ExplainQuery replace the buffering untagged-enum approach. The EvidenceMembers struct correctly uses deny_unknown_fields and present to distinguish absent from present fields; the match arm (Some(record), plan, None) correctly binds the optional plan. The ExplainQuery visitor correctly implements visit_str and visit_map, enforces a single-key constraint, and reconstructs non-diff queries into a serde_json::Value::Object before delegating to explanation::Query::deserialize. Both custom impls preserve the same accepted shapes and JSON Schema.

integrations/rustev-serve/src/offline.rs — The explain function scope/bundle guard is:

(true, Some(given), Some(now_ms)) if *given == scope => Some(now_ms),
(true, Some(_), Some(_))                             => DecisionNotFound,
(false, None, None)                                  => None,
_                                                    => InvalidRequest,

This correctly enforces spec 040 3.16.2: scope+nowMs required exactly when a bundle side is present, scope mismatch is decision_not_found, and any other combination of given/missing is invalid_request. The side helper correctly keys file entries by name ("a.record", "a.plan", "b.bundle", "redaction") and produces the JSON reference structure the surface library expects. The explain_refusal path uses expect("a refusal code is short text") on known string constants from RefusalCode::as_str(), which will not panic in practice; any panic in spawn_blocking would surface as InternalError via the JoinHandle path, which is acceptable.

integrations/rustev-serve/src/transport.rs — Operation::Explain is added to needs_principal and has_body matches, correctly requiring authentication and a body. The early EndpointUnavailable guard for Explain is correctly removed. Redaction bytes are extracted from listener.redaction_policy and forwarded to offline::run.

integrations/rustev-serve/src/service.rs — The filter excluding Explain from available_endpoints is removed. Correct now that the handler is implemented.

integrations/rustev-serve/tests/handlers.rs — explain_goldens correctly filters conformance cases with resolve/probeResolve (bundle-resolver cases the service cannot handle), maps camelCase conformance keys to snake_case serve-request keys, and gates expectations on forms and given == (bundle, bundle). explain_scope_and_references covers the scope-mismatch, reference-equals-embedded, parent-component rejection, and absent-file cases. The assert!(ran >= 140) guard is a reasonable lower bound.

No concrete defects found in any changed file.

{"head": "d5871049a1ccfc9aa1070916b9ff54d3cb3286cd", "verdict": "no-findings", "findings": []}

Subject: 682bde9...d587104, diff digest 8e8641439301632f539eb26a0ef8de3202bea4fcae8f23cbec606637db397699, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Oct 31, 2026
Merged via the queue into main with commit bc1484c Oct 31, 2026
30 checks passed
@bartekus
bartekus deleted the impl/042-explain-handler branch October 31, 2026 02:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant