# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-rewrite-compaction-as-a-lossy-transaction-rather-than-an-idempotent-edit.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-rewrite-compaction-as-a-lossy-transaction-rather-than-an-idempotent-edit.warrant.json
# Markdown SHA-256:   8bd592d8f7bc6c46f132073a5aac99d2c790b0777ab4606eed50a0428474572d
# Code AST SHA-256:   53d2a8b712a7be7e39ddc0014cb4e41846604ed2c8a9c372b3274fcf7473135d
# Verified Classes:   ProjectionIntegrityError, Region, WorkingMemory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ProjectionIntegrityError(RuntimeError):
    """Raised when a compacted region is used as a source for re-derivation or re-compaction."""
    pass


class Region:
    def __init__(self, region_id: str, tokens: int, is_projection: bool = False, provenance: str | None = None):
        self.region_id = region_id
        self.tokens = tokens
        self.is_projection = is_projection
        self.provenance = provenance
        self.retired = False


class WorkingMemory:
    def __init__(self, budget: int):
        self.budget = budget
        self.regions: dict[str, Region] = {}
        self.head: str | None = None

    def used_tokens(self) -> int:
        # Retired regions do not count against budget only if they were fully replaced.
        return sum(r.tokens for r in self.regions.values() if not r.retired)

    def compact(self, region_id: str, summary_tokens: int, external_source: str) -> Region:
        region = self.regions[region_id]

        # Invariant 1: a projection may never be an input to another compaction.
        if region.is_projection:
            raise ProjectionIntegrityError(
                f"region {region_id} is a projection (provenance={region.provenance}); "
                f"re-compacting it would compound paraphrase error. Compact a fresh region "
                f"or read from the external source {region.provenance!r} instead."
            )

        # Invariant 2: compaction must fit the budget after retirement.
        projected_used = self.used_tokens() - region.tokens + summary_tokens
        if projected_used > self.budget:
            raise ProjectionIntegrityError(
                f"compaction of {region_id} would leave {projected_used} tokens > budget "
                f"{self.budget}; defer to a turn boundary rather than orphaning the region."
            )

        # Invariant 3: atomic retire + replace. If anything below fails, nothing changes.
        new_id = f"{region_id}::proj"
        projection = Region(
            region_id=new_id,
            tokens=summary_tokens,
            is_projection=True,
            provenance=external_source,
        )
        region.retired = True
        self.regions[new_id] = projection
        if self.head == region_id:
            self.head = new_id
        return projection

    def read_for_rederivation(self, region_id: str) -> str:
        region = self.regions[region_id]
        # Invariant 4: re-derivation must go to the external source, never the projection.
        if region.is_projection:
            raise ProjectionIntegrityError(
                f"re-derivation requested from projection {region_id}; "
                f"read external source {region.provenance!r} instead."
            )
        return region_id


def safe_compact(wm: WorkingMemory, region_id: str, summary_tokens: int, source: str) -> Region:
    try:
        return wm.compact(region_id, summary_tokens, source)
    except ProjectionIntegrityError:
        raise
    except KeyError as e:
        raise ProjectionIntegrityError(f"unknown region {region_id!r}") from e
