# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-attribute-latency-and-token-cost-when-a-task-graph-s-critical-path-is-not-the-path-that-consumed-the-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-attribute-latency-and-token-cost-when-a-task-graph-s-critical-path-is-not-the-path-that-consumed-the-budget.warrant.json
# Markdown SHA-256:   07e3cd2a9f36e9edd8dd849073b0c4affb1d1b9a90ec5b3da95827c82c3c0283
# Code AST SHA-256:   b0ed3ebcdba60de907356406b1edf6984978909bb123cea9b66888750e9aef54
# Verified Classes:   MisattributedSLOTelemetry, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from dataclasses import dataclass, field
from typing import Optional


class MisattributedSLOTelemetry(RuntimeError):
    """Raised when an SLO breach cannot be attributed to a single span
    because the telemetry lacks own-vs-descendant cost separation or
    join semantics, or because the breach is structural (chain/fanout)."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    duration_s: float
    own_tokens: int
    rolled_tokens: int          # includes descendants; -1 if not rolled up
    join: str = "serial"        # "serial" | "parallel" at this node
    children: list = field(default_factory=list)


def attribute_latency_breach(root: Span, slo_s: float) -> str:
    # Critical path = max root-to-leaf cumulative duration.
    def critical_path(span, acc):
        acc = acc + span.duration_s
        if not span.children:
            return acc, [span.span_id]
        best = (0.0, [])
        for c in span.children:
            d, path = critical_path(c, acc)
            if d > best[0]:
                best = (d, path)
        return best

    total, path = critical_path(root, 0.0)
    if total <= slo_s:
        return "no-breach"

    # Concentration test: is the breach owned by a single span on the path?
    span_by_id = {s.span_id: s for s in _walk(root)}
    leaf = span_by_id[path[-1]]
    if leaf.duration_s >= (total - slo_s) and len(path) == 2:
        return f"span-concentrated:{leaf.span_id}"

    # If the path passes through a serial chain of length > 2, the breach
    # is owned by the chain's parent join node, not any leaf.
    if len(path) > 2:
        parent = span_by_id[path[-2]]
        if parent.join == "serial":
            raise MisattributedSLOTelemetry(
                f"latency breach on serial chain of length {len(path)}; "
                f"owning node is join {parent.span_id}, not leaf {leaf.span_id}"
            )
    return f"fanout-distributed:path={path}"


def attribute_token_breach(root: Span, budget: int) -> str:
    if root.rolled_tokens < 0:
        raise MisattributedSLOTelemetry(
            "token rollup missing; cannot separate own vs descendant cost"
        )
    spans = _walk(root)
    top = max(spans, key=lambda s: s.own_tokens)
    overrun = root.rolled_tokens - budget
    if overrun <= 0:
        return "no-breach"
    if top.own_tokens >= overrun:
        # Check for re-fetch pathology: same span_id prefix fetched twice.
        return f"span-concentrated:{top.span_id}:own={top.own_tokens}"
    if top.own_tokens < 0.3 * budget:
        raise MisattributedSLOTelemetry(
            f"token overrun {overrun} is diffuse; top span {top.span_id} "
            f"owns only {top.own_tokens}/{budget}; remediation is subtree "
            f"context discipline, not a single-call cap"
        )
    return f"chain-distributed:top={top.span_id}"


def _walk(span):
    yield span
    for c in span.children:
        yield from _walk(c)
