Tool results, timeouts and idempotency
Handle outcomes and uncertainty
A tool call ID correlates a result with its originating model request. It is not necessarily a stable business-operation identifier across retries. A timeout means the caller stopped waiting; it does not prove that the remote operation failed or was cancelled. A read-only operation can often be retried under a bounded policy, while a write may already have committed. For unknown write outcomes, check authoritative operation status or request human reconciliation rather than blindly submitting another write. Use a typed result envelope with status, correlation ID and bounded safe data. Report errors to the model as data, and do not claim success until the executor confirms the operation. In this chapter no actual external operations occur.
Retry only within a trusted budget
A timeout should be enforced by the actual client or worker, with a total deadline across attempts. A bounded retry policy checks whether the error is transient, the operation is safe to repeat and the remaining time and attempt budget permit another call. Attempts in this example count calls already started; limit is the maximum total calls and remaining_ms is the time left. Inputs are trusted nonnegative integers, a boolean retry flag and a normalized outcome. Unknown outcomes route to reconciliation. The four results are retry, reconcile, stop, stop. A real retry scheduler should apply backoff and jitter, reserve sufficient remaining time for the next attempt, honor cancellation, and avoid retry amplification across service layers. The example makes a decision only; it does not sleep or enforce a real timeout.
def route(outcome, attempts, limit, remaining_ms, retry_safe): # All timing and safety metadata supplied by the trusted executor. if outcome == "ok": return "complete" if outcome == "denied" or outcome == "invalid": return "stop" if outcome not in ("timeout", "transient") or not retry_safe: return "reconcile" if attempts >= limit or remaining_ms <= 0: return "stop" return "retry"
print(route("timeout", 1, 3, 500, True))print(route("timeout", 1, 3, 500, False))print(route("transient", 3, 3, 500, True))print(route("denied", 1, 3, 500, True))Bind approval to the exact operation
For a high-impact action, show the user a concrete preview with target, quantity and consequence. The trusted system records explicit approval for that exact payload and actor, then rechecks permissions at execution time. Model text such as "approved":true is not approval. The next example is only an in-memory preview ledger: no stock is modified. An approval fixture binds actor, operation key, item and amount, and an actor-scoped key identifies a request. The first call records a preview; the duplicate returns the stored preview; an approved different amount with the same key returns conflict; an unapproved key requests approval. The ledger contains one entry. The permission and approval checks occur before returning a stored result, so revocation prevents replay disclosure. The preview ledger has no actual authentication, expiry, transaction or concurrency protection.
def preview(ledger, actor, key, item, amount, permissions, approvals): # In-memory dry run only. Trusted identity, permissions and approvals. payload = (item, amount) if (item not in permissions or type(amount) is not int or not 1 <= amount <= 5 or type(key) is not str or not key): return "denied" if (actor, key, item, amount) not in approvals: return "approval_required" scope = (actor, key) if scope in ledger: return ledger[scope][1] if ledger[scope][0] == payload else "conflict" result = f"preview: reserve {amount} of {item}" ledger[scope] = (payload, result) return result
ledger = {}approvals = {("u", "r1", "A", 2), ("u", "r1", "A", 3)}print(preview(ledger, "u", "r1", "A", 2, {"A"}, approvals))print(preview(ledger, "u", "r1", "A", 2, {"A"}, approvals))print(preview(ledger, "u", "r1", "A", 3, {"A"}, approvals))print(preview(ledger, "u", "r2", "A", 2, {"A"}, approvals))print(len(ledger))Idempotency beyond the toy ledger
Idempotency means repeated execution of the same logical operation has the same intended effect as one execution. The caller should reuse a stable operation key on retry, not create a fresh key for every attempt. Store a canonical payload or fingerprint and reject key reuse with a changed payload. In a real write path, bind the key to actor/tenant and operation type, enforce uniqueness, make the business change and durable result recording atomic where possible, and handle in-progress states and crashes. Across external services use their idempotency contracts and reconcile uncertain outcomes; a local cache alone cannot guarantee exactly-once effects. Record audit metadata and establish retention, revocation and expiry policies. The dry-run result is not a reservation confirmation.
Practice: simulate failures and duplicates
Replay a preview with the same key and payload, then with a changed amount. Remove the permission or approval and replay; it must not return the previous result. Simulate a timeout on a retry-safe read, a timeout on an uncertain write, a denied call, and a depleted budget. Record each routing decision and count attempted executions separately from successes. A production evaluation should also test concurrent duplicate deliveries, crash recovery, stale approvals and cancellation using a controlled environment. Complete the local project before moving to Model Context Protocol.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tool results, timeouts and idempotency quiz
Apply tool validation and execution boundaries.
A write times out without a reliable idempotency contract. What is safest?
When is the retry budget exhausted in route?
What happens to an approved changed payload with an existing key?
Why check permission before replaying a stored result?
What does the in-memory preview ledger establish?