# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoning-persistence-across-hot-reload-cycles-in-a-plugin-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoning-persistence-across-hot-reload-cycles-in-a-plugin-registry.warrant.json
# Markdown SHA-256:   0085766734b84cf26150b1b6bc593550b4ec503f820e66fa7c8a563cee316c90
# Code AST SHA-256:   99f48b8dff7d15a0365ac1658cdc01376a2712eb9c961d67a391d60efc682816
# Verified Classes:   RevocationLeakError, DerivedArtifacts
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class RevocationLeakError(RuntimeError):
    """Raised when derived registry state references a tool ID absent from the live manifest."""
    pass


@dataclass
class DerivedArtifacts:
    # Each derived artifact is a set of tool IDs it can route to.
    selection_index_ids: set[str] = field(default_factory=set)
    alias_table_ids: set[str] = field(default_factory=set)
    capability_cache_ids: set[str] = field(default_factory=set)

    def all_reachable_ids(self) -> set[str]:
        return self.selection_index_ids | self.alias_table_ids | self.capability_cache_ids


def apply_manifest_reload(
    live_manifest_ids: Iterable[str],
    derived: DerivedArtifacts,
    *,
    fail_closed: bool = True,
) -> None:
    """
    Enforce the revocation-completeness invariant at reload time.

    Invariant: every tool ID reachable through any derived artifact must be
    present in the live manifest. A violation means a removed (or never-
    authorized) tool can still influence routing — the persistence channel.
    """
    live = set(live_manifest_ids)
    reachable = derived.all_reachable_ids()
    leaked = reachable - live

    if leaked:
        if fail_closed:
            # Do not silently purge: a leak indicates either a reload bug or
            # an active poisoning attempt. Both warrant halting the reload.
            raise RevocationLeakError(
                f"revocation leak: derived state references non-live tool IDs "
                f"{sorted(leaked)}; live manifest has {sorted(live)}"
            )
        # Explicit, logged purge path for operators who choose availability
        # over fail-closed semantics. Still must be recorded.
        derived.selection_index_ids -= leaked
        derived.alias_table_ids -= leaked
        derived.capability_cache_ids -= leaked


def reload_with_guard(
    new_manifest_ids: Iterable[str],
    derived: DerivedArtifacts,
) -> None:
    # Bind derived artifacts to the new manifest version BEFORE the next
    # selection cycle, not on a separate cadence.
    live = set(new_manifest_ids)
    # Simulate a delta reload that forgot to prune the alias table:
    # derived.alias_table_ids still contains a removed tool ID.
    try:
        apply_manifest_reload(live, derived, fail_closed=True)
    except RevocationLeakError:
        # Fail closed: reload aborted, previous manifest remains authoritative,
        # and the leak is surfaced rather than allowed to persist.
        raise
    # Only reached when invariant holds.
    assert derived.all_reachable_ids() <= live
