# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-based-eval-score-is-computed-from-spans-that-were-never-executed-in-the-graded-run-the-orphaned-span-reattributi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-based-eval-score-is-computed-from-spans-that-were-never-executed-in-the-graded-run-the-orphaned-span-reattributi.warrant.json
# Markdown SHA-256:   f352a42723efda76cc020b9187280eae0b118d75bdb2d8a1c82fcfe108b787ef
# Code AST SHA-256:   8d6a79638a624de208d785c6b546de0c497fd016f6750547104c9d96911ee9cc
# Verified Classes:   OrphanedSpanReattributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class OrphanedSpanReattributionError(RuntimeError):
    """Raised when an eval verdict resolves to a span not in the graded trace's lineage."""
    pass


def resolve_and_score(trace, eval_spec, score_cache):
    """
    trace: dict with 'root_span_id' and 'spans' {span_id: {parent_id, tool_name,
           step_index, content_hash, args}}
    eval_spec: list of rules, each {tool_name, content_hash_prefix, scorer}
    score_cache: dict keyed by (tool_name, step_index) -> cached_score (LEGACY, unsafe)
    Returns {span_id: score}. Raises on orphaned resolution or unscored safety span.
    """
    # Build lineage: span -> root via parent chain
    def lineage(span_id):
        chain, cur = [], span_id
        seen = set()
        while cur is not None:
            if cur in seen:
                raise OrphanedSpanReattributionError(
                    f"cycle in parent chain at {cur}")
            seen.add(cur)
            chain.append(cur)
            cur = trace["spans"][cur]["parent_id"]
        if chain[-1] != trace["root_span_id"]:
            raise OrphanedSpanReattributionError(
                f"span {span_id} not rooted at graded run root")
        return chain

    resolved = {}
    for span_id, span in trace["spans"].items():
        lineage(span_id)  # validates ancestry
        for rule in eval_spec:
            if span["tool_name"] != rule["tool_name"]:
                continue
            if not span["content_hash"].startswith(rule["content_hash_prefix"]):
                continue
            resolved[span_id] = rule["scorer"](span)

    # Safety-relevant spans that got no live score must fail closed
    safety_tools = {r["tool_name"] for r in eval_spec}
    for span_id, span in trace["spans"].items():
        if span["tool_name"] in safety_tools and span_id not in resolved:
            # Do NOT fall back to score_cache[(tool_name, step_index)].
            # A positional cache hit here is the reattribution bug.
            raise OrphanedSpanReattributionError(
                f"safety-relevant span {span_id} ({span['tool_name']} "
                f"at step {span['step_index']}) has no live score in graded run; "
                f"refusing positional cache fallback"
            )

    return resolved
