# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-orphaned-a-tool-call-dependency.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-hierarchical-compaction-has-silently-orphaned-a-tool-call-dependency.warrant.json
# Markdown SHA-256:   e91461ca32c29434bc8e8d32ee2b54fd83868a43c9f693642dc105178dff79bd
# Code AST SHA-256:   f76070936089fff5026f3103712dda697058a0dfc29355f1a6af43ec4ba02282
# Verified Classes:   CompactionOrphanError, Block, AssembledContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionOrphanError(RuntimeError):
    """Raised when a tool_result survives compaction without its tool_use partner."""


@dataclass
class Block:
    kind: str          # "tool_use" | "tool_result" | "text"
    call_id: str | None = None
    payload: str = ""


@dataclass
class AssembledContext:
    blocks: list[Block] = field(default_factory=list)


def validate_pairing(ctx: AssembledContext, *, allow_rehydrate: bool = False) -> None:
    use_ids = {b.call_id for b in ctx.blocks if b.kind == "tool_use" and b.call_id}
    result_ids = {b.call_id for b in ctx.blocks if b.kind == "tool_result" and b.call_id}

    orphans = result_ids - use_ids
    if not orphans:
        return

    if allow_rehydrate:
        # Caller is expected to have already attempted rehydration upstream.
        # Reaching here means the raw store could not satisfy the dependency.
        raise CompactionOrphanError(
            f"unrehydratable orphaned tool_results: {sorted(orphans)}; "
            f"evict these results or abort the turn"
        )

    raise CompactionOrphanError(
        f"tool_result(s) {sorted(orphans)} have no resident tool_use partner; "
        f"compaction broke the pairing invariant — do not infer on this context"
    )


def compact_and_assemble(
    raw_blocks: Iterable[Block],
    *,
    evictable_chunks: set[int],
    raw_store: dict[str, Block] | None = None,
) -> AssembledContext:
    ctx = AssembledContext()
    for i, block in enumerate(raw_blocks):
        if i in evictable_chunks and block.kind == "tool_use":
            # Refuse to evict a request half whose result half is still live.
            partner_live = any(
                b.kind == "tool_result" and b.call_id == block.call_id
                for j, b in enumerate(raw_blocks) if j not in evictable_chunks
            )
            if partner_live:
                if raw_store and block.call_id in raw_store:
                    ctx.blocks.append(raw_store[block.call_id])  # rehydrate pair
                    continue
                raise CompactionOrphanError(
                    f"cannot evict tool_use {block.call_id}: live result would be orphaned"
                )
        ctx.blocks.append(block)

    validate_pairing(ctx)
    return ctx
