# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-evict-a-context-segment-whose-marginal-value-is-negative-but-whose-removal-cost-exceeds-its-token-bud.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-evict-a-context-segment-whose-marginal-value-is-negative-but-whose-removal-cost-exceeds-its-token-bud.warrant.json
# Markdown SHA-256:   bf5a15fc7b5cb3d0311c283ec9f47eb1185c5d0514ff6cf2069f4482846c2ded
# Code AST SHA-256:   2bc689e73b549e58b1706ad031a829924acd97f4123557b853712ef1eda4de72
# Verified Classes:   PinnedLiabilityBudgetExhausted, Segment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class PinnedLiabilityBudgetExhausted(RuntimeError):
    """Raised when no evictable segment remains and the budget is still exceeded."""
    pass


@dataclass
class Segment:
    seg_id: str
    tokens: int
    marginal_value: float
    dependents: Set[str] = field(default_factory=set)  # live segments referencing this one
    rederivation_multiplier: float = 2.0


def assemble(segments: Dict[str, Segment], budget: int) -> list:
    """Budget-aware assembly that refuses to evict pinned liabilities.

    Eviction is permitted only when the segment has no live dependents and
    reconstruction cost does not exceed the token savings.
    """
    total = sum(s.tokens for s in segments.values())
    if total <= budget:
        return list(segments.values())

    # Candidate evictions, cheapest-to-evict first (most negative MV, no dependents).
    evictable = [
        s for s in segments.values()
        if s.marginal_value < 0 and not s.dependents
    ]
    evictable.sort(key=lambda s: s.marginal_value)  # most negative first

    retained = dict(segments)
    freed = 0
    for seg in evictable:
        if total - freed <= budget:
            break
        reconstruction_cost = seg.tokens * seg.rederivation_multiplier
        if reconstruction_cost > seg.tokens:  # savings vs. re-derivation
            # Net-negative to evict: compress instead of dropping.
            surrogate_tokens = max(1, seg.tokens // 8)
            freed += seg.tokens - surrogate_tokens
            retained[seg.seg_id] = Segment(
                seg_id=seg.seg_id + ":stub",
                tokens=surrogate_tokens,
                marginal_value=seg.marginal_value,
                dependents=set(),
                rederivation_multiplier=seg.rederivation_multiplier,
            )
        else:
            freed += seg.tokens
            del retained[seg.seg_id]

    if total - freed > budget:
        pinned = [s.seg_id for s in segments.values() if s.dependents]
        raise PinnedLiabilityBudgetExhausted(
            f"Budget {budget} unreachable without evicting pinned segments: {pinned}"
        )
    return list(retained.values())
