# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-graph-corruption-when-redaction-rewrites-span-identity-in-genai-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-graph-corruption-when-redaction-rewrites-span-identity-in-genai-observability-pipelines.warrant.json
# Markdown SHA-256:   f28cb56aefb6b62e5b36cf2297d9b84634fd550e7a3abc2f1128590e69b6e536
# Code AST SHA-256:   83abec9722c4c9279e1c05645f21dc79a26d4338cc1015cf3c4ca607d9862d30
# Verified Classes:   TraceGraphIntegrityError, TaskGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TraceGraphIntegrityError(RuntimeError):
    """Raised when redaction has torn the task graph or leaked a key."""
    pass


SENSITIVE = ("acct_",)

def redact_value(s: str, salt: bytes) -> str:
    """Value-pure, deterministic transform: same input -> same token, any field."""
    for pat in SENSITIVE:
        if pat in s:
            h = hashlib.sha256(salt + s.encode()).hexdigest()[:12]
            return f"[R:{h}]"
    return s

def redact_span(span: dict, salt: bytes) -> dict:
    """Apply value-addressed redaction to EVERY string field, recursively.
    No field allowlist: any string that matches is transformed identically."""
    def walk(v):
        if isinstance(v, str):
            return redact_value(v, salt)
        if isinstance(v, list):
            return [walk(x) for x in v]
        if isinstance(v, dict):
            return {k: walk(x) for k, x in v.items()}
        return v
    return walk(span)


@dataclass
class TaskGraph:
    spans: dict = field(default_factory=dict)          # span_id -> span
    edges: list = field(default_factory=list)          # (parent_id, child_ref_key)

    def validate_closure(self) -> None:
        """Hard invariant: every parent reference must resolve to a real child
        key, and no cost may have been assigned by ancestor-fallback."""
        child_keys = {}
        for sid, sp in self.spans.items():
            for k in ("tool_call_id", "span_id"):
                if k in sp:
                    child_keys[sp[k]] = sid
        for parent_id, ref in self.edges:
            if ref not in child_keys:
                raise TraceGraphIntegrityError(
                    f"torn edge: parent {parent_id} references {ref!r} "
                    f"which resolves to no child span (redaction likely "
                    f"rewrote the key on one side only)"
                )
            child = self.spans[child_keys[ref]]
            if child.get("cost_attribution") == "ancestor_fallback":
                raise TraceGraphIntegrityError(
                    f"span {child_keys[ref]} cost assigned by ancestor-fallback; "
                    f"attribution is undefined, refusing to roll up"
                )

    def rollup_cost(self) -> dict:
        self.validate_closure()
        return {sid: sp.get("cost", 0.0) for sid, sp in self.spans.items()}


def ingest(raw_spans: list, salt: bytes) -> TaskGraph:
    g = TaskGraph()
    for raw in raw_spans:
        sp = redact_span(raw, salt)
        g.spans[sp["span_id"]] = sp
        for ref in sp.get("references", []):
            g.edges.append((sp["span_id"], ref))
    # Leak check: no raw sensitive token may survive anywhere post-redaction.
    for sp in g.spans.values():
        blob = str(sp)
        for pat in SENSITIVE:
            if pat in blob:
                raise TraceGraphIntegrityError(
                    f"redaction leak: sensitive pattern {pat!r} survived in "
                    f"span {sp['span_id']} (field not covered by transform)"
                )
    return g


# --- reproduction of the observed failure ---
salt = b"deployment-salt-v1"
raw = [
    {"span_id": "s1", "tool_call_id": "acct_482913.call.7", "cost": 0.12},
    {"span_id": "s2", "source_tool_call": "acct_482913.call.7",
     "references": ["acct_482913.call.7"], "cost": 0.0,
     "cost_attribution": "ancestor_fallback"},
]

g = ingest(raw, salt)
try:
    g.rollup_cost()
except TraceGraphIntegrityError as e:
    # With value-pure redaction BOTH fields hash to the same token, so the
    # edge resolves; the remaining trip is the ancestor-fallback guard.
    print("halted attribution:", e)
