# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-learned-context-budget-allocation-as-a-hard-constraint-rather-than-an-advisory-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-learned-context-budget-allocation-as-a-hard-constraint-rather-than-an-advisory-hint.warrant.json
# Markdown SHA-256:   e13c4958ee4bbfb5c313d2edcb9d2ac7be996d85895fd21d0998761b9b83615e
# Code AST SHA-256:   8b166244fa3f9605b1d7174439adc51fb4361f97de05ee52044acc47296c3d5d
# Verified Classes:   BudgetInvariantViolation, Segment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class BudgetInvariantViolation(RuntimeError):
    """Raised when a learned budget would force unrecoverable truncation."""
    pass


@dataclass
class Segment:
    kind: str          # "system" | "memory" | "tool_schema"
    payload: str
    allotted_tokens: int


STRUCTURED_KINDS = {"tool_schema", "memory_json"}


def enforce_budget(segment: Segment, tokenizer) -> str:
    actual = len(tokenizer.encode(segment.payload))
    if actual <= segment.allotted_tokens:
        return segment.payload

    if segment.kind in STRUCTURED_KINDS:
        # Never truncate structured payloads: re-allocate instead.
        raise BudgetInvariantViolation(
            f"segment kind={segment.kind!r} needs {actual} tokens "
            f"but allocator granted {segment.allotted_tokens}; "
            f"re-allocation required, truncation prohibited"
        )

    # Prose is recoverable: truncate at tokenizer boundary.
    return tokenizer.decode(tokenizer.encode(segment.payload)[: segment.allotted_tokens])


def assemble(segments, tokenizer):
    out = []
    for seg in segments:
        out.append(enforce_budget(seg, tokenizer))
    return "\n".join(out)
