# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-federation-policy-engine-silently-permit-a-cross-org-data-share-that-the-source-organization-s-constraint-algebra-forbids.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-federation-policy-engine-silently-permit-a-cross-org-data-share-that-the-source-organization-s-constraint-algebra-forbids.warrant.json
# Markdown SHA-256:   8a6f9264863a9e67a75cda3f74b2360647092abba5b63e37ac97495418eb8826
# Code AST SHA-256:   cbee3ff08ff50a95eeaef2439b9d8e9c41e7c25a78dc7e3c1e589ca56314f1e1
# Verified Classes:   FederationCompositionError, Verdict, Constraint, MeshState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class FederationCompositionError(RuntimeError):
    """Raised when a federation verdict violates the non-monotone composition invariant."""


class Verdict(Enum):
    PERMIT = "permit"
    DENY = "deny"
    PROVISIONAL_PERMIT = "provisional_permit"


@dataclass(frozen=True)
class Constraint:
    org: str
    name: str
    monotone: bool
    # facts this constraint's guard depends on, keyed by owning org
    guard_dependencies: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class MeshState:
    populated_orgs: FrozenSet[str] = frozenset()
    committed: dict[str, Verdict] = field(default_factory=dict)


def evaluate_join(
    state: MeshState,
    constraints: list[Constraint],
    join_order: list[str],
) -> dict[str, Verdict]:
    """
    Evaluate constraints in the given join order. If any non-monotone
    constraint's guard dependency closure is not yet populated, its verdict
    must be PROVISIONAL, never a committed PERMIT.
    """
    results: dict[str, Verdict] = {}
    for org in join_order:
        for c in (c for c in constraints if c.org == org):
            closure_ready = c.guard_dependencies.issubset(state.populated_orgs)
            if not c.monotone and not closure_ready:
                # Fail-closed for non-monotone guards: never commit PERMIT
                # on an open dependency closure.
                results[c.name] = Verdict.PROVISIONAL_PERMIT
            else:
                results[c.name] = Verdict.PERMIT
    return results


def enforce(state: MeshState, constraints: list[Constraint], join_order: list[str]) -> None:
    results = evaluate_join(state, constraints, join_order)

    # Invariant: a non-monotone constraint must not be committed as PERMIT
    # while its guard dependency closure is open. This is the boundary
    # condition that the fail-open scheduler violated.
    for c in constraints:
        if not c.monotone:
            closure_ready = c.guard_dependencies.issubset(state.populated_orgs)
            if not closure_ready and results.get(c.name) is Verdict.PERMIT:
                raise FederationCompositionError(
                    f"non-monotone constraint {c.org}/{c.name} committed PERMIT "
                    f"with open guard closure {sorted(c.guard_dependencies - state.populated_orgs)}; "
                    f"join order {join_order} is unsafe"
                )


# Reproduce the observed failure: scheduler joins analytics/partner before
# research, so research's allowlist facts are absent when the guard runs.
constraints = [
    Constraint(
        org="research",
        name="aggregate_allowlist_guard",
        monotone=False,
        guard_dependencies=frozenset({"research", "analytics"}),
    ),
]
bad_state = MeshState(populated_orgs=frozenset({"analytics", "partner"}))
try:
    enforce(bad_state, constraints, join_order=["analytics", "partner", "research"])
except FederationCompositionError as e:
    print(f"caught: {e}")

# Safe: source-first order populates research before the guard evaluates.
good_state = MeshState(populated_orgs=frozenset({"research", "analytics", "partner"}))
enforce(good_state, constraints, join_order=["research", "analytics", "partner"])
print("source-first order: no invariant violation")
