# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-propagation-as-a-session-scoped-invariant-rather-than-a-process-scoped-one.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-propagation-as-a-session-scoped-invariant-rather-than-a-process-scoped-one.warrant.json
# Markdown SHA-256:   4065c5813b5c7e8790adf47c2effffe4a57b73cfac90a2020cf03dbc8e0d4cb9
# Code AST SHA-256:   cb38c49538b948e5d0f5fbd1bf4c495a0eac9a1c8abd8be0538ffecc153cb038
# Verified Classes:   CrossSessionTaintPersistenceError, Page, Allocator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

"""Session-boundary taint persistence guard.

Demonstrates the page-generation invariant: an allocation may only be
considered untainted if the page it lives on has been sanitized since the
last session that wrote to it. Allocation-scoped shadow bits alone are
insufficient and must be cross-checked against page generation.
"""

from dataclasses import dataclass, field


class CrossSessionTaintPersistenceError(RuntimeError):
    """Raised when an allocation reuses a page still tainted from a prior session."""
    pass


@dataclass
class Page:
    page_id: int
    generation: int = 0          # bumped at every session boundary that touched it
    sanitized_generation: int = 0  # last generation that was explicitly zeroed
    tainted: bool = False


@dataclass
class Allocator:
    pages: dict[int, Page] = field(default_factory=dict)

    def page_for(self, addr: int) -> Page:
        pid = addr >> 12  # 4 KiB pages
        if pid not in self.pages:
            self.pages[pid] = Page(page_id=pid)
        return self.pages[pid]

    def mark_tainted(self, addr: int) -> None:
        self.page_for(addr).tainted = True

    def sanitize(self, addr: int) -> None:
        p = self.page_for(addr)
        p.sanitized_generation = p.generation
        p.tainted = False

    def end_session(self, touched_addrs: list[int]) -> None:
        for addr in touched_addrs:
            p = self.page_for(addr)
            if p.tainted:
                p.generation += 1  # invalidate reuse until sanitized

    def allocate(self, addr: int, session_id: str) -> None:
        p = self.page_for(addr)
        if p.tainted and p.sanitized_generation < p.generation:
            raise CrossSessionTaintPersistenceError(
                f"alloc at {addr:#x} (page {p.page_id}) in session {session_id} "
                f"reuses page tainted at generation {p.generation}, "
                f"last sanitized at {p.sanitized_generation}; "
                f"zero-on-reuse not performed"
            )


def run_worker_cycle(alloc: Allocator, session_a: str, session_b: str) -> None:
    """Simulate two sessions sharing a warm worker without sanitization."""
    tool_result_addr = 0x7F00_0010
    alloc.mark_tainted(tool_result_addr)          # session A injects tainted bytes
    alloc.end_session([tool_result_addr])         # session ends; shadow bits cleared

    # Session B reuses the same page from the thread-local free list.
    # Allocation-scoped taint would report clean here; page-scoped does not.
    alloc.allocate(tool_result_addr, session_b)


if __name__ == "__main__":
    alloc = Allocator()
    try:
        run_worker_cycle(alloc, session_a="sess-A", session_b="sess-B")
    except CrossSessionTaintPersistenceError as exc:
        print(f"BLOCKED: {exc}")
