# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-bids-on-a-contract-net-task-it-cannot-locally-verify-phantom-capability-commitment-and-the-role-allocation-deadlock-that.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-bids-on-a-contract-net-task-it-cannot-locally-verify-phantom-capability-commitment-and-the-role-allocation-deadlock-that.warrant.json
# Markdown SHA-256:   f23f172cba7d500b980d7c6d809bb81d62ce407f31e43b8cb1afa1e6a1e8d8ec
# Code AST SHA-256:   06ff0378ec3f18412667d8c9d89d8950a2a3dbe2b3869a453c9576a0d6e59562
# Verified Classes:   PhantomCapabilityCommitment, Contract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PhantomCapabilityCommitment(RuntimeError):
    """Raised when an awarded contract fails a step for a capability the worker
    claimed but could not bind, and the manager has no rebid budget remaining."""
    pass


class Contract:
    def __init__(self, task_id, deadline_s, bids):
        self.task_id = task_id
        self.deadline_s = deadline_s
        self.bids = bids                       # list of dicts: worker, confidence, eta, claimed_tools
        self.state = "announced"
        self.awarded_to = None
        self.steps_done = 0
        self.total_steps = 3                   # fetch, parse_table, reconcile
        self.elapsed_s = 0.0
        self.rebid_budget_s = max(b["eta"] for b in bids) * 1.5

    def award(self, manifest):
        # Select highest confidence; but flag out-of-manifest claims.
        winner = max(self.bids, key=lambda b: b["confidence"])
        known = set(manifest.get(winner["worker"], []))
        claimed = set(winner["claimed_tools"])
        unverified = claimed - known
        if unverified and not winner.get("warrant"):
            # Downgrade: award but mark contract as warrant-deficient.
            self.state = "awarded_unwarranted"
        else:
            self.state = "awarded"
        self.awarded_to = winner
        return winner

    def record_step(self, step_name, ok, dt):
        self.elapsed_s += dt
        if ok:
            self.steps_done += 1
            return
        # Step failed. Determine whether rebid is possible.
        remaining = self.deadline_s - self.elapsed_s
        if self.state == "awarded_unwarranted" and remaining < self.rebid_budget_s:
            raise PhantomCapabilityCommitment(
                f"contract {self.task_id}: worker {self.awarded_to['worker']} "
                f"failed step '{step_name}' for unverified capability "
                f"{self.awarded_to['claimed_tools']!r}; "
                f"remaining={remaining:.1f}s < rebid_budget={self.rebid_budget_s:.1f}s; "
                f"state={self.state}; steps_done={self.steps_done}/{self.total_steps}"
            )
        # Otherwise transition to rebid.
        self.state = "rebid"
        self.steps_done = 0


def run_contract(contract, manifest, worker_executor):
    contract.award(manifest)
    plan = ["fetch", "parse_table", "reconcile"]
    for step in plan:
        ok, dt = worker_executor(contract.awarded_to["worker"], step)
        try:
            contract.record_step(step, ok, dt)
        except PhantomCapabilityCommitment:
            raise
        if contract.state == "rebid":
            # Re-announce to remaining bidders within reserved budget.
            contract.bids = [b for b in contract.bids
                             if b["worker"] != contract.awarded_to["worker"]]
            if not contract.bids:
                raise PhantomCapabilityCommitment(
                    f"contract {contract.task_id}: no bidders remain after rebid"
                )
            contract.award(manifest)
    return contract


# Example trace that triggers the deadlock:
manifest = {"A": ["fetch", "parse_table"], "B": ["fetch", "parse_table"], "C": ["fetch"]}
bids = [
    {"worker": "A", "confidence": 0.61, "eta": 30, "claimed_tools": ["fetch", "parse_table"]},
    {"worker": "B", "confidence": 0.82, "eta": 40, "claimed_tools": ["fetch", "parse_table", "reconcile"]},
    {"worker": "C", "confidence": 0.40, "eta": 20, "claimed_tools": ["fetch"]},
]
c = Contract("t-001", deadline_s=60, bids=bids)

def executor(worker, step):
    # B's 'reconcile' binding is absent despite the claim.
    if worker == "B" and step == "reconcile":
        return False, 38.0   # late failure, consumes most of the deadline
    return True, 5.0

run_contract(c, manifest, executor)   # raises PhantomCapabilityCommitment
