# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-delegated-scope-attenuation-when-an-aaif-credential-chain-crosses-a-re-issuing-hop-with-a-stale-scope-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-delegated-scope-attenuation-when-an-aaif-credential-chain-crosses-a-re-issuing-hop-with-a-stale-scope-cache.warrant.json
# Markdown SHA-256:   8c7b27e9083e7aacfb8fddd748afbc12368aef4d6c8f54960a9cbce544822038
# Code AST SHA-256:   7fbaf422707e6511d26b8db1a06a65c3e75409f5febc3251a5e3e8fa5489603f
# Verified Classes:   ScopeLaunderingError, Credential, ScopeCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeLaunderingError(RuntimeError):
    """Raised when a delegated credential's scope is attenuated against a
    parent scope that does not match the presented parent credential instance.
    Indicates stale scope-cache resolution across a re-issuing hop."""


@dataclass(frozen=True)
class Credential:
    issuer_id: str
    subject_id: str
    scope: frozenset
    body: bytes

    @property
    def instance_hash(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


class ScopeCache:
    """Deliberately keyed by credential instance hash, never by issuer/subject.
    Keying by issuer/subject is the defect this module exists to prevent."""

    def __init__(self):
        self._by_instance = {}

    def resolve(self, cred: Credential) -> frozenset:
        key = cred.instance_hash
        if key not in self._by_instance:
            self._by_instance[key] = cred.scope
        return self._by_instance[key]


def attenuate(child_scope: frozenset, parent: Credential, cache: ScopeCache) -> frozenset:
    """Enforce scope(child) subset-of scope(parent) using the parent credential
    instance actually presented, not a re-resolved or cached-by-issuer view."""
    resolved = cache.resolve(parent)
    if resolved != parent.scope:
        # Cache returned a scope inconsistent with the presented credential bytes.
        raise ScopeLaunderingError(
            f"scope cache diverged from presented parent credential "
            f"{parent.instance_hash[:12]} (issuer={parent.issuer_id}, "
            f"subject={parent.subject_id}): cached={sorted(resolved)} "
            f"actual={sorted(parent.scope)}"
        )
    if not child_scope.issubset(parent.scope):
        raise ScopeLaunderingError(
            f"attenuation violation: child scope {sorted(child_scope)} is not a "
            f"subset of parent scope {sorted(parent.scope)} for credential "
            f"{parent.instance_hash[:12]}"
        )
    return child_scope


def issue_child(parent: Credential, requested: frozenset, cache: ScopeCache) -> frozenset:
    granted = attenuate(requested, parent, cache)
    return granted
