# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-schedules-a-cross-org-subagent-whose-trust-budget-is-denominated-in-a-different-latency-class-than-its-own.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-schedules-a-cross-org-subagent-whose-trust-budget-is-denominated-in-a-different-latency-class-than-its-own.warrant.json
# Markdown SHA-256:   b0b46cbae615eb890161b090c5c5d8abf9c6f70d88f373d3ba7bd21413374af9
# Code AST SHA-256:   0751795d0a22b6027d89f74de758fdb27c47d1f5ceb2f967df6d74e7e5bf7695
# Verified Classes:   WarrantDenominationMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantDenominationMismatch(RuntimeError):
    """Raised when speculative spend is denominated in a different latency
    class than the downstream ledger's reservation unit, or when a peer
    manifest fails to declare a usable tail ratio."""
    pass


def speculative_admission(
    remaining_warrant_seconds: float,
    p50_settlement_s: float,
    peer_manifest: dict,
    requested_fanout: int,
) -> int:
    """Compute the hard speculative fan-out ceiling for a cross-org peer.

    The ledger reserves at p99, the caller budgets at p50. We must normalize
    before dividing, or we over-dispatch by the tail ratio and leak
    reservations from abandoned branches.
    """
    if p50_settlement_s <= 0:
        raise WarrantDenominationMismatch(
            f"non-positive p50 settlement {p50_settlement_s!r}; cannot denominate"
        )

    tail_ratio = peer_manifest.get("reservation_tail_ratio")
    if tail_ratio is None:
        # Cannot read the peer's denomination: speculation is an unhedged bet.
        raise WarrantDenominationMismatch(
            f"peer {peer_manifest.get('org_id', '<unknown>')} declares no "
            "reservation_tail_ratio; speculative dispatch must be disabled "
            "and handoff downgraded to synchronous warrant confirmation"
        )
    if tail_ratio < 1.0:
        raise WarrantDenominationMismatch(
            f"peer tail ratio {tail_ratio!r} < 1.0; reservation unit is "
            "narrower than settlement unit, manifest is inconsistent"
        )

    cost_per_speculation = tail_ratio * p50_settlement_s
    ceiling = int(remaining_warrant_seconds // cost_per_speculation)

    if requested_fanout > ceiling:
        # Refuse to dispatch the overage rather than let the ledger reject it
        # after reserving — rejection-after-reservation is what leaks budget.
        return ceiling
    return requested_fanout


def dispatch_with_lease(
    fanout: int,
    lease_ttl_s: float,
    ledger,
    orphaned_branches: int,
):
    """Every speculative call gets a lease and a cancellation obligation.
    Abandoned branches must release within the lease or the ledger reclaims."""
    if orphaned_branches > 0:
        raise WarrantDenominationMismatch(
            f"{orphaned_branches} speculative branch(es) abandoned without a "
            f"cancellation event; reservations will outlive lease_ttl={lease_ttl_s}s "
            "and drift the budget toward zero with no completed work"
        )
    for call_id in range(fanout):
        ledger.reserve(call_id, ttl_s=lease_ttl_s)
    return fanout
