# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-its-a2a-artifact-schema-mid-task-and-the-delegating-agent-has-already-committed-a-typed-dependency.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-its-a2a-artifact-schema-mid-task-and-the-delegating-agent-has-already-committed-a-typed-dependency.warrant.json
# Markdown SHA-256:   517965b6d93fed6383f6d18bdcc4ff597b51c129285eb12752afb0967cec5c0b
# Code AST SHA-256:   a306b1dddc1e62f1c29282dd58467e90908f30fcb62d18304de289aa273cc53c
# Verified Classes:   ArtifactSchemaDriftError, Binding, DelegatorState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ArtifactSchemaDriftError(RuntimeError):
    """Raised when a re-emitted artifact under a bound artifactId carries a
    different schema revision than the one the delegator committed to."""


@dataclass
class Binding:
    artifact_id: str
    schema_ref: str
    content_hash: str


@dataclass
class DelegatorState:
    # Distilled reasoning state, keyed on COMPOSITE identity, never bare artifactId.
    distilled: dict[tuple[str, str], Any] = field(default_factory=dict)
    ledger: dict[str, Binding] = field(default_factory=dict)

    def consume(self, event: dict) -> None:
        artifact_id = event["artifactId"]
        schema_ref = event["part"]["metadata"]["schema"]
        content_hash = event["part"].get("contentHash", "")

        prior = self.ledger.get(artifact_id)
        if prior is not None and prior.schema_ref != schema_ref:
            # Re-emission under a new schema revision: the v1-derived state is
            # now unsound. Refuse to merge; force re-derivation.
            self.distilled.pop((artifact_id, prior.schema_ref), None)
            raise ArtifactSchemaDriftError(
                f"artifactId={artifact_id!r} re-emitted with schema "
                f"{schema_ref!r} but was bound to {prior.schema_ref!r}; "
                f"distilled state invalidated, re-derive required"
            )

        self.ledger[artifact_id] = Binding(artifact_id, schema_ref, content_hash)
        self.distilled[(artifact_id, schema_ref)] = self._distill(event, schema_ref)

    def _distill(self, event: dict, schema_ref: str) -> Any:
        # Schema-revision-aware distillation; never assumes v1 field names.
        payload = event["part"]["payload"]
        if schema_ref == "extraction/v1":
            return {"entities": payload["entities"], "confidence": payload["confidence"]}
        if schema_ref == "extraction/v2":
            return {
                "entities": [
                    {"name": e["label"], "type": e["category"]} for e in payload["entities"]
                ],
                "confidence": min((e["score"] for e in payload["entities"]), default=0.0),
            }
        raise ArtifactSchemaDriftError(f"unhandled schema revision {schema_ref!r}")


def run_trace() -> None:
    d = DelegatorState()
    d.consume({"artifactId": "a1", "part": {
        "metadata": {"schema": "extraction/v1"},
        "payload": {"entities": [{"name": "x", "type": "org"}], "confidence": 0.9},
    }})
    # Delegatee re-plans and replaces a1 with a v2 payload.
    d.consume({"artifactId": "a1", "part": {
        "metadata": {"schema": "extraction/v2"},
        "payload": {"entities": [{"label": "x", "category": "org", "score": 0.4}]},
    }})


if __name__ == "__main__":
    run_trace()
