# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-cross-org-read-grant-to-preserve-forget-propagation-integrity-in-federated-memory-namespaces.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-cross-org-read-grant-to-preserve-forget-propagation-integrity-in-federated-memory-namespaces.warrant.json
# Markdown SHA-256:   cd65367fc10029e5347097bf2c20ea0619165ac8443336feaac4f5e470ea674a
# Code AST SHA-256:   df95fdacc29985232a5c0a2d586db448511677a06144f8cfa1e868d2fbfc21a7
# Verified Classes:   ForgetPropagationError, DerivationClass, GranteeProfile, GrantRequest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ForgetPropagationError(RuntimeError):
    """Raised when a read grant would create derived state the owner's
    forget protocol cannot enumerate or revoke."""


class DerivationClass(Enum):
    RAW_EPISODIC = "raw_episodic"
    SUMMARY = "summary"
    EMBEDDING = "embedding"
    IN_FLIGHT_CONTEXT = "in_flight_context"
    SUB_GRANT = "sub_grant"


@dataclass(frozen=True)
class GranteeProfile:
    grantee_id: str
    # Derived stores the grantee will materialize from granted records.
    derivation_classes: frozenset[DerivationClass]
    # Classes for which the grantee preserves a source-record back-pointer
    # that the owner's tombstone predicate can match.
    provenance_preserving: frozenset[DerivationClass]
    # Classes for which the grantee can return effective-erasure attestation.
    attestable: frozenset[DerivationClass]
    # True iff the grantee registers downstream sub-grants against the
    # owner's forget graph at grant time.
    sub_grants_registered_upstream: bool
    # Maximum seconds granted content may reside in an agent context.
    max_context_residency_s: int


@dataclass(frozen=True)
class GrantRequest:
    owner_id: str
    grantee: GranteeProfile
    erasure_sla_s: int
    permitted_classes: frozenset[DerivationClass] = field(
        default_factory=lambda: frozenset(DerivationClass)
    )


def evaluate_grant(req: GrantRequest) -> frozenset[DerivationClass]:
    """Return the set of derivation classes the grant may cover, or raise
    ForgetPropagationError if the grant must be refused outright."""
    g = req.grantee
    requested = req.permitted_classes & g.derivation_classes
    uncovered = []

    for cls in requested:
        if cls is DerivationClass.SUB_GRANT:
            if not g.sub_grants_registered_upstream:
                uncovered.append(cls)
            continue
        if cls not in g.provenance_preserving:
            uncovered.append(cls)
            continue
        if cls not in g.attestable:
            uncovered.append(cls)
            continue
        if cls is DerivationClass.IN_FLIGHT_CONTEXT:
            if g.max_context_residency_s > req.erasure_sla_s:
                uncovered.append(cls)

    # Refuse outright when the grantee cannot even handle the raw records
    # under the owner's forget protocol: no degradation can recover this.
    if DerivationClass.RAW_EPISODIC in uncovered:
        raise ForgetPropagationError(
            f"grantee {g.grantee_id} cannot satisfy forget propagation for "
            f"raw episodic records under erasure SLA {req.erasure_sla_s}s; "
            f"refusing grant from owner {req.owner_id}"
        )

    # Otherwise degrade: exclude the unaddressable classes explicitly.
    if uncovered:
        return frozenset(requested - set(uncovered))
    return frozenset(requested)


def issue_grant(req: GrantRequest) -> dict:
    covered = evaluate_grant(req)
    excluded = req.permitted_classes - covered
    return {
        "owner": req.owner_id,
        "grantee": req.grantee.grantee_id,
        "covered_classes": sorted(c.value for c in covered),
        "excluded_classes": sorted(c.value for c in excluded),
        "degraded": bool(excluded),
        "attestation_required": True,
    }
