# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-cross-org-read-delegation-that-carries-a-valid-capability-token-but-whose-lease-epoch-predates-the-sha.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-cross-org-read-delegation-that-carries-a-valid-capability-token-but-whose-lease-epoch-predates-the-sha.warrant.json
# Markdown SHA-256:   ff5a88f9f1ed6bad28d5a0bdad88ed785f15859b2cdecba01f00d5347ec3de49
# Code AST SHA-256:   28b92a3b4b2993097136ed5191b131180576d55a9866fe64ec233d7bc723cebe
# Verified Classes:   EpochFenceViolation, ReclaimInProgress
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EpochFenceViolation(RuntimeError):
    """Raised when a cross-org read delegation carries a lease epoch older
    than the shard's current fencing generation and the delegate cannot
    reconcile stale reads."""
    pass


class ReclaimInProgress(RuntimeError):
    """Raised when a read is attempted while the shard is advancing its fence."""
    pass


def authorize_cross_org_read(token, shard, now, delegate_has_version_vector):
    # Capability plane
    if not token.verify_signature(issuer_keyring=shard.keyring):
        raise EpochFenceViolation("capability signature invalid")
    if not (token.nbf <= now < token.exp):
        raise EpochFenceViolation("capability outside validity window")
    if not token.scope.covers(shard.path, op="read"):
        raise EpochFenceViolation("capability scope does not cover read")

    # Fencing plane -- the non-obvious clause
    if shard.state == "RECLAIM_IN_PROGRESS":
        raise ReclaimInProgress(
            f"shard {shard.path} is advancing fence; refusing read"
        )

    if token.lease_epoch < shard.fence_gen:
        if not delegate_has_version_vector:
            raise EpochFenceViolation(
                f"token epoch {token.lease_epoch} < shard fence {shard.fence_gen} "
                f"and delegate cannot reconcile stale reads"
            )
        # Delegate can reconcile: serve as advisory stale read
        return {"serve": True, "stale": True, "epoch": token.lease_epoch}

    return {"serve": True, "stale": False, "epoch": token.lease_epoch}
