# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-from-its-delegated-aaif-credential-scope-after-a-mid-chain-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-from-its-delegated-aaif-credential-scope-after-a-mid-chain-re-issuance.warrant.json
# Markdown SHA-256:   a08a3e06746094b8401b6ed5cad5031ffbbe663a59cd40e111767ae1132b008c
# Code AST SHA-256:   615135b5d114e3fec0dfd512d9a2f96e7b8c95ad96af45a35df7bd7e5159710a
# Verified Classes:   DelegationContinuityError, Credential
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class DelegationContinuityError(RuntimeError):
    """Raised when a delegated credential's signed parent link does not
    resolve to the issuer's live credential at verification time."""
    pass


@dataclass
class Credential:
    subject: str
    issuer: str
    caps: frozenset
    generation: int
    parent: Optional[str] = None          # canonical hash of predecessor
    issued_at: int = 0
    expires_at: int = 0

    def canonical_hash(self) -> str:
        body = json.dumps(
            {
                "subject": self.subject,
                "issuer": self.issuer,
                "caps": sorted(self.caps),
                "generation": self.generation,
                "parent": self.parent,
                "issued_at": self.issued_at,
                "expires_at": self.expires_at,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(body).hexdigest()


def verify_chain(
    leaf: Credential,
    registry: dict,          # hash -> Credential (retains superseded)
    live_issuer: dict,       # subject_id -> current Credential
    now: int,
    strict_parent_hash: bool = True,
) -> None:
    cred = leaf
    seen = set()
    while cred.parent is not None:
        if cred.canonical_hash() in seen:
            raise DelegationContinuityError("cycle in delegation chain")
        seen.add(cred.canonical_hash())

        if strict_parent_hash:
            parent = registry.get(cred.parent)
            if parent is None:
                raise DelegationContinuityError(
                    f"parent hash {cred.parent[:12]}… for {cred.subject} "
                    f"not retained; cannot prove warrant descent"
                )
        else:
            parent = live_issuer.get(cred.issuer)
            if parent is None:
                raise DelegationContinuityError(
                    f"issuer {cred.issuer} has no live credential"
                )

        if cred.issuer != parent.subject:
            raise DelegationContinuityError(
                f"issuer {cred.issuer} != parent subject {parent.subject}"
            )
        if parent.expires_at <= now:
            raise DelegationContinuityError(
                f"parent credential for {cred.subject} expired at {parent.expires_at}"
            )
        if cred.generation != parent.generation + 1:
            raise DelegationContinuityError(
                f"generation discontinuity: {cred.subject} gen={cred.generation} "
                f"but parent {parent.subject} gen={parent.generation}; "
                f"descendant was not re-issued after issuer rotation"
            )
        if not cred.caps <= parent.caps:
            raise DelegationContinuityError(
                f"capability escalation: {cred.subject} asserts "
                f"{set(cred.caps) - set(parent.caps)} not held by {parent.subject}"
            )
        cred = parent


def issue_child(parent: Credential, subject: str, caps: frozenset, now: int) -> Credential:
    if not caps <= parent.caps:
        raise DelegationContinuityError(
            f"cannot delegate {set(caps) - set(parent.caps)} to {subject}"
        )
    return Credential(
        subject=subject,
        issuer=parent.subject,
        caps=caps,
        generation=parent.generation + 1,
        parent=parent.canonical_hash(),
        issued_at=now,
        expires_at=parent.expires_at,
    )


# --- trace of the observed failure ---------------------------------------
T = 0
a = Credential("A", "root", frozenset({"read:dataset", "spawn:worker"}), 0, None, T, T + 10_000)
b_v1 = issue_child(a, "B", frozenset({"read:dataset", "spawn:worker"}), T)
c_v1 = issue_child(b_v1, "C", frozenset({"read:dataset"}), T)

# A rotates B at T+1800 with a *narrowed* set (quarantine) — C is never re-issued.
b_v2 = Credential("B", "A", frozenset({"read:dataset"}), 1, a.canonical_hash(), T + 1800, T + 10_000)

registry = {b_v1.canonical_hash(): b_v1, c_v1.canonical_hash(): c_v1}
live = {"A": a, "B": b_v2, "C": c_v1}

# Strict mode catches the gap immediately.
try:
    verify_chain(c_v1, registry, live, now=T + 3600, strict_parent_hash=True)
except DelegationContinuityError as e:
    print("strict:", e)

# Current-issuer mode without generation check would have passed — the bug.
try:
    verify_chain(c_v1, registry, live, now=T + 3600, strict_parent_hash=False)
except DelegationContinuityError as e:
    print("lax+generation:", e)
