# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-its-capability-manifest-mid-handoff-the-stale-warrant-race-in-dynamic-role-reassignment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-its-capability-manifest-mid-handoff-the-stale-warrant-race-in-dynamic-role-reassignment.warrant.json
# Markdown SHA-256:   ae3f24188b4bd431f0c19eb70b6e2afa79bc9878d786ea7c7f6131c4a9704e40
# Code AST SHA-256:   45623693ba7c125d5568bef17a72cfdb78c0ea12ee120450983bcddc692626db
# Verified Classes:   WarrantSupersededError, SchemaMismatchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantSupersededError(RuntimeError):
    """Raised when an in-flight warrant's generation no longer matches the
    worker's current manifest generation, i.e. the worker was reassigned
    after the warrant was issued. The task must be re-queued, not retried
    against the same worker."""
    pass


class SchemaMismatchError(RuntimeError):
    """Raised when a warrant's declared schema does not equal the schema
    in the worker's current manifest. Never coerce; always fail closed."""
    pass


def invoke_tool(worker, warrant, tool_name, payload):
    # Atomic read of the worker's current generation and manifest schema.
    # Both must be read under the same lock / snapshot to avoid TOCTOU.
    with worker.snapshot() as snap:
        current_gen = snap.generation
        current_schema = snap.manifest.schema
        current_tools = snap.manifest.tools

        if warrant.generation < current_gen:
            # Manifest was mutated after this warrant was issued.
            # Do NOT proceed; the task belongs to a different role now.
            raise WarrantSupersededError(
                f"worker {worker.id} gen {current_gen} > warrant gen "
                f"{warrant.generation}; task must be re-queued"
            )

        if warrant.generation > current_gen:
            # Warrant issued for a future generation: ordering violation
            # in the supervisor's write path. Fail loudly, do not guess.
            raise WarrantSupersededError(
                f"warrant gen {warrant.generation} ahead of worker "
                f"{worker.id} gen {current_gen}; supervisor ordering bug"
            )

        if warrant.schema != current_schema:
            raise SchemaMismatchError(
                f"warrant schema {warrant.schema!r} != manifest schema "
                f"{current_schema!r} on worker {worker.id}"
            )

        if tool_name not in current_tools:
            raise SchemaMismatchError(
                f"tool {tool_name!r} not in manifest tools {current_tools!r}"
            )

        return worker.execute(tool_name, payload, gen=current_gen)
