# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-label-laundering-across-a-tool-sandbox-boundary-when-an-agent-re-derives-privileged-data-from-a-low-privilege-d.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-label-laundering-across-a-tool-sandbox-boundary-when-an-agent-re-derives-privileged-data-from-a-low-privilege-d.warrant.json
# Markdown SHA-256:   63f5f6a948c68030c1ef2c58fb5ad1a36c58729ce849f4996949d198c1da4fb1
# Code AST SHA-256:   0db2a4d2d26218c0824e71bdd18bc126bf50e1ea3c40419dc37e08a6363cbf04
# Verified Classes:   Label, TaintJoinViolation, DeclassificationUnsound, Value, SessionContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum


class Label(IntEnum):
    PUBLIC = 0
    SECRET = 1


class TaintJoinViolation(RuntimeError):
    """Raised when a context's join label would permit a flow the lattice forbids."""


class DeclassificationUnsound(RuntimeError):
    """Raised when a declassifier's measured output support contradicts its guarantee."""


@dataclass
class Value:
    payload: object
    label: Label
    source: str


@dataclass
class SessionContext:
    session_id: str
    cleared_for: set[str]
    held: list[Value] = field(default_factory=list)

    def join_label(self) -> Label:
        # The load-bearing invariant: context label is the MAX over co-resident
        # values, never the session default. Inverting this is the laundering bug.
        if not self.held:
            return Label.PUBLIC
        return max(v.label for v in self.held)

    def admit(self, v: Value) -> None:
        self.held.append(v)


def declassify(
    value: Value,
    asserted_k: int,
    measured_output_support: int,
    input_cardinality: int,
) -> Value:
    """Downgrade a SECRET value to PUBLIC only if the guarantee survives measurement."""
    if value.label != Label.SECRET:
        return value
    # A k-anonymous claim implies output support should be <= input_cardinality / k.
    max_permitted_support = max(1, input_cardinality // asserted_k)
    if measured_output_support > max_permitted_support:
        raise DeclassificationUnsound(
            f"declassifier claims k={asserted_k} but output support "
            f"{measured_output_support} exceeds permitted {max_permitted_support} "
            f"for input cardinality {input_cardinality}; output is a sufficient "
            f"statistic, not an anonymized summary"
        )
    return Value(payload=value.payload, label=Label.PUBLIC, source=f"declass({value.source})")


def emit(ctx: SessionContext, v: Value, sink_cleared_for: set[Label]) -> Value:
    """Emit a value from a context to a sink, enforcing the join label."""
    ctx.admit(v)
    effective = ctx.join_label()
    if effective not in sink_cleared_for:
        raise TaintJoinViolation(
            f"session {ctx.session_id}: context join label {effective.name} "
            f"(from co-resident values) exceeds sink clearance "
            f"{[l.name for l in sink_cleared_for]}; "
            f"reconstruction-via-correlation blocked at the join, not the egress"
        )
    return v


def reconstruct_and_emit(billing_ctx: SessionContext, artifact: Value, vault_value: Value) -> Value:
    """The laundering path: low session joins a downgraded artifact with its own read."""
    # Billing session legitimately holds a PUBLIC artifact and reads its own vault.
    billing_ctx.admit(artifact)          # PUBLIC
    billing_ctx.admit(vault_value)       # SECRET, but in a session that "owns" it
    # The join label is now SECRET; emission to a PUBLIC sink must fail.
    return emit(billing_ctx, vault_value, sink_cleared_for={Label.PUBLIC})
