# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-an-a2a-artifact-whose-parts-hash-matches-but-whose-mimetype-declared-decoder-disagrees-with-the-sender-s-schema-dialect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-an-a2a-artifact-whose-parts-hash-matches-but-whose-mimetype-declared-decoder-disagrees-with-the-sender-s-schema-dialect.warrant.json
# Markdown SHA-256:   f57b40ade7565065aa9ec6add7e81b7a8c348aa627656b4ae77c5432ae588757
# Code AST SHA-256:   92d98e71505a96c8b852ee37a6fb7afb6da7d4c2324559d85654303fc90339a3
# Verified Classes:   ArtifactDecodeDivergence, Artifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ArtifactDecodeDivergence(RuntimeError):
    """Raised when an A2A artifact passes hash-integrity but fails decode-consistency."""


# Decoders that coerce types are dialect-sensitive and cannot serve as a semantic gate.
LOSSY_DECODERS = {"application/json"}


@dataclass
class Artifact:
    parts_text: str
    mime_type: str
    sha256: str
    schema_dialect: str | None = None


def _canonical(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def _decode_preserving(text: str):
    # Lossless: parse but do not coerce; caller binds types explicitly.
    return json.loads(text)


def _decode_coercing(text: str):
    # Simulates a strict decoder that silently coerces numeric-looking strings.
    raw = json.loads(text)
    out = {}
    for k, v in raw.items():
        if isinstance(v, str) and v.isdigit():
            out[k] = int(v)  # drops leading zeros -- the observed bug
        else:
            out[k] = v
    return out


def admit_artifact(art: Artifact) -> dict:
    # Gate 1: integrity.
    actual = hashlib.sha256(art.parts_text.encode("utf-8")).hexdigest()
    if actual != art.sha256:
        raise ArtifactDecodeDivergence(
            f"integrity mismatch: expected {art.sha256}, got {actual}"
        )

    # Gate 2: semantic / decode-consistency.
    if art.mime_type in LOSSY_DECODERS and art.schema_dialect is None:
        raise ArtifactDecodeDivergence(
            f"cannot admit {art.mime_type!r} artifact: lossy decoder and no "
            f"schema_dialect declared inside hashed envelope; refusing to guess"
        )

    preserved = _decode_preserving(art.parts_text)
    coerced = _decode_coercing(art.parts_text)

    # Round-trip check: if the coercing decoder changes the canonical form,
    # the decoder is not a valid semantic gate for this payload.
    if _canonical(preserved) != _canonical(coerced):
        raise ArtifactDecodeDivergence(
            "decode divergence: coercing decoder altered canonical form "
            f"(preserved={_canonical(preserved)} coerced={_canonical(coerced)}); "
            "refuse and renegotiate dialect with sender"
        )

    return preserved


if __name__ == "__main__":
    payload = '{"id": "00123", "due": "2025-04-11"}'
    digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()
    bad = Artifact(parts_text=payload, mime_type="application/json", sha256=digest)
    # Hash matches, but the coercing decoder destroys the leading-zero key.
    admit_artifact(bad)  # raises ArtifactDecodeDivergence
