# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-closure-after-an-egress-allowlist-widens-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-closure-after-an-egress-allowlist-widens-mid-session.warrant.json
# Markdown SHA-256:   cc0d2e94e886ac5bdf52efa3dca7a4fc5b3bbbf0f5cad1224fc273a0e58063b0
# Code AST SHA-256:   3d16afba29ca3acd4ac099a58acdd3c8258011a7ab8f55bfb8a1dd73cc7ea84e
# Verified Classes:   StaleTaintClosureError, PolicyGeneration, TaintStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleTaintClosureError(RuntimeError):
    """Raised when egress is attempted from a value whose taint label was
    computed under an older policy generation than the current allowlist."""
    pass


class PolicyGeneration:
    def __init__(self):
        self.gen = 0

    def widen(self):
        # Any widening (or sensitive->public reclassification) bumps the generation.
        self.gen += 1
        return self.gen


class TaintStore:
    def __init__(self, policy: PolicyGeneration):
        self.policy = policy
        self._labels = {}  # value_id -> (label, generation)

    def label(self, value_id, label):
        self._labels[value_id] = (label, self.policy.gen)

    def relearn(self, value_id, label):
        # Re-derivation under current policy generation.
        self._labels[value_id] = (label, self.policy.gen)

    def get(self, value_id):
        return self._labels.get(value_id)


def admit_egress(value_id, target, allowlist, store: TaintStore, rederive):
    entry = store.get(value_id)
    if entry is None:
        raise StaleTaintClosureError(f"no taint label for {value_id!r}; cannot admit egress")
    label, gen = entry
    if target not in allowlist:
        return False  # blocked by allowlist, not a closure issue
    if gen < store.policy.gen:
        # Allowlist widened since this label was computed. Re-derive before admitting.
        new_label = rederive(value_id)
        store.relearn(value_id, new_label)
        label, gen = store.get(value_id)
        if label == "SECRET":
            return False
        if gen < store.policy.gen:
            raise StaleTaintClosureError(
                f"re-derivation of {value_id!r} did not advance to current "
                f"generation {store.policy.gen}; refusing egress"
            )
    return label != "SECRET"
