# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-span-attribute-redaction-as-a-semantic-convention-violation-rather-than-a-privacy-win.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-span-attribute-redaction-as-a-semantic-convention-violation-rather-than-a-privacy-win.warrant.json
# Markdown SHA-256:   e1bfcc9213d87c910d16390750f344e5536fdb9b2446c68736578433795ef349
# Code AST SHA-256:   89ddf52803b3cfc1d408ac6a4a8e47aa708def94999c38dcc96f4339569aa323
# Verified Classes:   RedactionConformanceAmbiguity, DestructiveRedaction
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from typing import Any

ASSERTED_ATTRS = ("tool.arguments", "tool.result", "tool.name")


class RedactionConformanceAmbiguity(RuntimeError):
    """Raised when a redaction transform is composed with conformance validation,
    making the verdict uninterpretable as evidence about the agent."""
    pass


class DestructiveRedaction(RedactionConformanceAmbiguity):
    """Redaction changed the type/structure of an asserted attribute such that
    validate(redact(span)) != redact(validate(span))."""
    pass


def _type_of(v: Any) -> type:
    return type(v)


def classify_redaction(raw: dict, redacted: dict) -> str:
    """Return 'preserving' iff redaction commutes with type/structure assertions."""
    for attr in ASSERTED_ATTRS:
        if attr not in raw:
            continue
        rv, dv = raw[attr], redacted.get(attr)
        if _type_of(rv) is not _type_of(dv):
            return "destructive"
        if isinstance(rv, dict):
            if not isinstance(dv, dict) or set(dv.keys()) != set(rv.keys()):
                return "destructive"
            for k in rv:
                if _type_of(rv[k]) is not _type_of(dv[k]):
                    return "destructive"
    return "preserving"


def validate_span(span: dict) -> None:
    """Semconv conformance over the RAW attribute algebra."""
    if not isinstance(span.get("tool.arguments"), dict):
        raise RedactionConformanceAmbiguity(
            "tool.arguments must be a JSON object pre-redaction"
        )
    try:
        json.loads(json.dumps(span["tool.arguments"]))
    except (TypeError, ValueError) as e:
        raise RedactionConformanceAmbiguity(f"arguments not JSON-round-trippable: {e}")
    if span.get("status.code") == "OK" and "tool.result" not in span:
        raise RedactionConformanceAmbiguity("OK span missing tool.result")
    if span.get("status.code") != "OK" and "tool.result" in span:
        raise RedactionConformanceAmbiguity("non-OK span carries tool.result")


def admit_to_conformance(raw_span: dict, redacted_span: dict) -> str:
    """Gate: conformance must be asserted pre-redaction. If the caller passes a
    redacted span to the validator, detect the destructive composition."""
    mode = classify_redaction(raw_span, redacted_span)
    if mode == "destructive":
        touched = [a for a in ASSERTED_ATTRS
                   if a in raw_span and _type_of(raw_span[a]) is not _type_of(redacted_span.get(a))]
        raise DestructiveRedaction(
            f"redaction mutated asserted attributes {touched}; "
            f"validate(redact(span)) != redact(validate(span)). "
            f"Route to quarantine lane with redaction.destructive=true and replay.safe=false."
        )
    # Safe path: validate the RAW span, export the redacted one.
    validate_span(raw_span)
    return "conformant"


if __name__ == "__main__":
    raw = {
        "tool.name": "send_invoice",
        "tool.arguments": {"to": "a@b.com", "amount": 42, "memo": "acct 1234-5678"},
        "tool.result": {"invoice_id": "inv_9"},
        "status.code": "OK",
    }
    # Destructive redactor: whole-value substitution into a dict slot.
    bad = dict(raw)
    bad["tool.arguments"] = "[REDACTED]"
    try:
        admit_to_conformance(raw, bad)
    except DestructiveRedaction as e:
        print("QUARANTINE:", e)
    # Structure-preserving redactor: value substitution, keys and types intact.
    good = dict(raw)
    good["tool.arguments"] = {"to": "***", "amount": 42, "memo": "***"}
    print(admit_to_conformance(raw, good))
