Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Capability and status contracts for fallback models

Examine multi-model adaptation, capability matrices, failure classification, and degradation.

Learning objectives: Switching the model changes the decision maker and cannot reset executed facts, authorizations and budgets. Only when the backup model meets the required capabilities and message semantics of the task can it be an executable downgrade path.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Capability and status contracts for fallback models
Switching the model changes the decision maker and cannot reset executed facts, authorizations and budgets. Only when the backup model meets the required capabilities and message semantics of the task can it be an executable downgrade path.

How does the mechanism work?

Step-by-step explanation
  1. Should the model be automatically changed after the main model returns a rejection?

    Reasons for switching models must distinguish temporary failures from prohibited behavior.

  2. How to handle the tool call ID when switching?

    Changing the message format must preserve correlations with actual actions.

  3. What should I do if the backup model is also limited?

    When fallback also fails, a global stopping rule is needed.

Implementation · Build it

Implement the contract · Capability and status contracts for fallback models

Objectives of this level: It can distinguish between temporary current limit, parameter error and permission denial, and does not apply to all models.

Visual guide · Fallback preserves business facts

Fallback preserves business facts

This routing fixture performs no writes. Consider fallback only after preserving business receipts, identity, required capabilities and shared limits. Select the figure to open it at full size.

Independent route function and output protocol

Implement route(runtime, request, state, event, capabilities) in fallback_student.py. Do not mutate request/state/event/capabilities. runtime.now starts at 0; the fixed input is:

request = {"business_id": "biz-77", "required_caps": ["tools", "json"],
           "deadline": 5, "max_model_calls": 2}
state = {"business_id": "biz-77", "write_state": "none", "receipt": None,
         "facts": [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}],
         "used_calls": 1}
event = {"kind": "rate_limited", "http_status": 429, "wait_units": 2}
capabilities = ["tools", "json"]
receipt = {"business_id": "biz-77", "receipt_id": "receipt-1", "status": "committed"}
now = 0

Valid structure is a precondition: write_state is none/unknown/committed; a trusted committed receipt was verified upstream and matches the business ID; facts contain executed evidence. This lab does not verify real receipt provenance. Mismatched request/state business IDs raise ValueError. deadline, max_model_calls, and used_calls must be nonnegative strict ints: bool is invalid. Validate those before any runtime action.

Runtime API: wait(units) advances integer logical time and records the action; call_fallback(business_id, facts) records actual arguments and returns a fixed draft/unavailable event; lookup(business_id) queries the fixture ledger. submit_write(business_id) creates a non-idempotent fixture effect that exposes replay errors. No branch of this routing exercise may call submit_write. Fallback responses take zero fixture time, so now+wait_units==deadline permits an immediate fixture response; a real network call needs a separate remaining-time contract.

Implement these ordered rules:

  1. After validation, committed returns committed/existing_receipt with the original receipt and no waiting or model call.
  2. unknown first calls lookup with the same business ID. A receipt returns committed/reconciled_receipt. No receipt returns reconcile_required/receipt_not_found_is_not_proof_of_no_write. Absence is not proof of noncommit and never permits a new write here.
  3. invalid_parameters returns permanent_error/invalid_parameters. permission_denied or safety_refusal returns denied with that kind as reason. Fallback cannot bypass them.
  4. Only kind=rate_limited and http_status=429 enter fallback. Other events return paused/unsupported_failure.
  5. Missing required_caps return capability_blocked with reason missing: followed by sorted missing capabilities joined with commas. No waiting or model call.
  6. used_calls>=max_model_calls returns budget_exhausted/model_call_budget_exhausted. used_calls=1 represents the already-authored primary call. At most one fallback shares that total budget.
  7. When entering fallback, validate wait_units as a nonnegative strict int. If now+wait_units>deadline, return deadline_exceeded/backoff_exceeds_remaining_time without waiting. Otherwise wait those units and call fallback once with the unchanged business ID and complete facts.
  8. A draft event returns draft_ready/fallback_draft and the original text. An unavailable fallback returns paused/fallback_unavailable; do not loop through more models.

Return exactly business_id/status/receipt/facts/reason/draft. Only known commits carry a receipt; only draft_ready carries a draft; otherwise these fields are None. Always retain facts. Baseline output:

{
    "business_id": "biz-77",
    "status": "draft_ready",
    "receipt": None,
    "facts": [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}],
    "reason": "fallback_draft",
    "draft": "fixture draft",
}

Create the scaffold and keep its failing run: expect 0/17 and exit 1. Repeated scaffold refuses to overwrite the learner file and exits 2.

python3 fallback_lab.py scaffold --out fallback_student.py
python3 fallback_lab.py grade --module fallback_student.py --out fallback-template-report.json

Scaffold body:

def route(runtime, request, state, event, capabilities):
    """Return business_id/status/receipt/facts/reason/draft, with exactly those keys.
    Validate IDs and strict integer budgets before actions (bool is invalid).
    Preserve completed/unknown writes before considering another model call.
    Only the authored rate_limited/429 fixture permits fallback, at most once.
    No branch of this routing exercise may call submit_write.
    Return draft_ready for a fixture draft; it does not mean business completion.
    """
    raise NotImplementedError("implement route")

Submit your completed implementation using this command; expect 17/17 and exit 0. The grader actually imports/calls it, changes business IDs, facts, capability order, clocks, and failure inputs, and inspects actual calls, lookup arguments, waits, budgets, unchanged inputs, and the ledger. A correct-looking JSON without required lookup/fallback actions fails. Its five-second worker limit only prevents hangs.

python3 fallback_lab.py grade --module fallback_student.py --out fallback-report.json

Copyable client fixtures and grader

Save this source as fallback_lab.py; it matches the HTTPS resource. It contains fixed guided cases, an unfinished scaffold, and public fixed counterexamples. The learner implements general route; there are no undisclosed random cases.

#!/usr/bin/env python3
"""Authored fallback fixtures, Python 3.9+ standard library. Zero provider/model calls.

Independent API: route(runtime, request, state, event, capabilities) -> decision dict.
The grader exercises actual learner code and checks fixture calls/ledger. No general
routing implementation is provided; scaffold is unfinished. Guided code is one case.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import subprocess
import sys

# CLI runtime and learner imports share one canonical module and exported types.
if __name__ == "__main__":
    sys.modules["fallback_lab"] = sys.modules[__name__]


class RoutingRuntime:
    def __init__(self, now=0, ledger=None, fallback_event=None):
        self.now = now
        self.ledger = copy.deepcopy(ledger or [])
        self.calls = []
        self.fallback_event = copy.deepcopy(fallback_event or {"kind": "draft", "text": "fixture draft"})

    def wait(self, units):
        if type(units) is not int or units < 0:
            raise ValueError("invalid_wait")
        self.now += units
        self.calls.append({"action": "wait", "units": units})

    def call_fallback(self, business_id, facts):
        self.calls.append({"action": "fallback", "business_id": business_id, "facts": copy.deepcopy(facts)})
        return copy.deepcopy(self.fallback_event)

    def lookup(self, business_id):
        self.calls.append({"action": "lookup", "business_id": business_id})
        matches = [r for r in self.ledger if r["business_id"] == business_id]
        return copy.deepcopy(matches[-1]) if matches else None

    def submit_write(self, business_id):
        """Deliberately non-idempotent fixture to expose replay; not a real external write."""
        receipt = {"business_id": business_id, "receipt_id": "receipt-" + str(len(self.ledger) + 1), "status": "committed"}
        self.calls.append({"action": "write", "business_id": business_id})
        self.ledger.append(receipt)
        return copy.deepcopy(receipt)

    def audit(self):
        return {"now": self.now, "calls": self.calls, "ledger": self.ledger}


REQUEST = {"business_id": "biz-77", "required_caps": ["tools", "json"], "deadline": 5, "max_model_calls": 2}
FACTS = [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}]
STATE = {"business_id": "biz-77", "write_state": "none", "receipt": None, "facts": FACTS, "used_calls": 1}
EVENT = {"kind": "rate_limited", "http_status": 429, "wait_units": 2}
RECEIPT = {"business_id": "biz-77", "receipt_id": "receipt-1", "status": "committed"}
TEMPLATE = '''def route(runtime, request, state, event, capabilities):
    """Return business_id/status/receipt/facts/reason/draft, with exactly those keys.
    Validate IDs and strict integer budgets before actions (bool is invalid).
    Preserve completed/unknown writes before considering another model call.
    Only the authored rate_limited/429 fixture permits fallback, at most once.
    No branch of this routing exercise may call submit_write.
    Return draft_ready for a fixture draft; it does not mean business completion.
    """
    raise NotImplementedError("implement route")
'''


def decision(request, state, status, reason, receipt=None, draft=None):
    return {"business_id": request["business_id"], "status": status, "receipt": receipt,
            "facts": copy.deepcopy(state["facts"]), "reason": reason, "draft": draft}


def case_data(name):
    req, state, event, caps = copy.deepcopy(REQUEST), copy.deepcopy(STATE), copy.deepcopy(EVENT), ["tools", "json"]
    now, ledger, fallback_event = 0, [], None
    status, reason, receipt, draft, actions = "draft_ready", "fallback_draft", None, "fixture draft", ["wait", "fallback"]
    if name == "invalid_parameters":
        event = {"kind": "invalid_parameters", "http_status": 400}
        status, reason, draft, actions = "permanent_error", "invalid_parameters", None, []
    elif name == "capability_missing":
        caps = ["tools"]
        status, reason, draft, actions = "capability_blocked", "missing:json", None, []
    elif name == "committed":
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        ledger = [copy.deepcopy(RECEIPT)]
        status, reason, receipt, draft, actions = "committed", "existing_receipt", copy.deepcopy(RECEIPT), None, []
    elif name in ("unknown_found", "unknown_missing"):
        state["write_state"] = "unknown"
        actions, draft = ["lookup"], None
        if name == "unknown_found":
            ledger = [copy.deepcopy(RECEIPT)]
            status, reason, receipt = "committed", "reconciled_receipt", copy.deepcopy(RECEIPT)
        else:
            status, reason = "reconcile_required", "receipt_not_found_is_not_proof_of_no_write"
    elif name in ("permission_denied", "safety_refusal"):
        event = {"kind": name}
        status, reason, draft, actions = "denied", name, None, []
    elif name == "deadline_exceeded":
        now = 4
        status, reason, draft, actions = "deadline_exceeded", "backoff_exceeds_remaining_time", None, []
    elif name == "budget_exhausted":
        state["used_calls"] = 2
        status, reason, draft, actions = "budget_exhausted", "model_call_budget_exhausted", None, []
    elif name == "fallback_unavailable":
        fallback_event = {"kind": "unavailable", "http_status": 429}
        status, reason, draft = "paused", "fallback_unavailable", None
    elif name == "changed_input":
        req["business_id"] = state["business_id"] = "order-909"
        state["facts"] = [{"kind": "tool_result", "operation_id": "stock-check-9", "data": {"quantity": 4}}]
        caps = ["json", "unused", "tools"]
        event["wait_units"] = 1
    elif name == "at_deadline":
        now = 3
    elif name == "other_failure":
        event = {"kind": "transport_error"}
        status, reason, draft, actions = "paused", "unsupported_failure", None, []
    elif name == "bool_budget":
        req["max_model_calls"] = True
        actions = []
    elif name == "mismatched_business_id":
        state["business_id"] = "wrong-business"
        actions = []
    elif name == "bool_deadline":
        req["deadline"] = True
        actions = []
    expected = decision(req, state, status, reason, receipt, draft)
    return req, state, event, caps, now, ledger, fallback_event, expected, actions


CASES = ["rate_limited", "invalid_parameters", "capability_missing", "committed", "unknown_found",
         "unknown_missing", "permission_denied", "safety_refusal", "deadline_exceeded", "budget_exhausted",
         "fallback_unavailable", "changed_input", "at_deadline", "other_failure", "bool_budget",
         "mismatched_business_id", "bool_deadline"]


def load_learner(path):
    spec = importlib.util.spec_from_file_location("learner_under_test", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module.route


def grade_case(path, name):
    req, state, event, caps, now, ledger, fallback_event, expected, actions = case_data(name)
    originals = copy.deepcopy([req, state, event, caps])
    rt = RoutingRuntime(now, ledger, fallback_event)
    result, caught, errors = None, None, []
    try:
        result = load_learner(path)(rt, req, state, event, caps)
    except BaseException as exc:
        caught = exc
    invalid = name in ("bool_budget", "mismatched_business_id", "bool_deadline")
    if invalid:
        if not isinstance(caught, ValueError) or rt.calls:
            errors.append("invalid_input_must_raise_before_actions")
    else:
        if caught:
            errors.append("unexpected_exception:" + type(caught).__name__ + ":" + str(caught))
        if result != expected:
            errors.append("decision_contract_mismatch")
        actual_actions = [c["action"] for c in rt.calls]
        if actual_actions != actions:
            errors.append("actual_call_sequence_mismatch")
        expected_now = now + (event["wait_units"] if "wait" in actions else 0)
        if rt.now != expected_now or rt.now > req["deadline"]:
            errors.append("shared_time_budget_mismatch")
        for call in rt.calls:
            if call["action"] in ("fallback", "lookup", "write") and call["business_id"] != req["business_id"]:
                errors.append("business_id_changed")
            if call["action"] == "fallback" and call["facts"] != originals[1]["facts"]:
                errors.append("executed_facts_lost_or_changed")
            if call["action"] == "wait" and call["units"] != event["wait_units"]:
                errors.append("authored_backoff_policy_not_followed")
        fallback_count = sum(c["action"] == "fallback" for c in rt.calls)
        if state["used_calls"] + fallback_count > req["max_model_calls"]:
            errors.append("model_call_budget_exceeded")
    if rt.ledger != ledger or any(c["action"] == "write" for c in rt.calls):
        errors.append("routing_replayed_or_created_write")
    if [req, state, event, caps] != originals:
        errors.append("input_was_mutated")
    return {"case": name, "pass": not errors, "errors": errors, "result": result,
            "exception": None if caught is None else type(caught).__name__ + ":" + str(caught), "audit": rt.audit()}


def guided(variant="reference"):
    # Each walkthrough is fixed; neither implements the general learner route().
    req, state = copy.deepcopy(REQUEST), copy.deepcopy(STATE)
    if variant == "reference":
        rt = RoutingRuntime()
        rt.wait(2)
        response = rt.call_fallback(req["business_id"], state["facts"])
        result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        checks = {"same_business_id": result["business_id"] == "biz-77",
                  "facts_preserved": rt.calls[-1]["facts"] == FACTS, "no_write": not rt.ledger,
                  "bounded_calls": len([c for c in rt.calls if c["action"] == "fallback"]) == 1}
    else:
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        rt = RoutingRuntime(ledger=[RECEIPT])
        if variant == "broken":
            rt.submit_write("biz-77-retry")  # Deliberate reset/replay after a 429 fixture.
            response = rt.call_fallback("biz-77-retry", [])
            result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        else:
            result = decision(req, state, "committed", "existing_receipt", receipt=state["receipt"])
        checks = {"one_effect": len(rt.ledger) == 1,
                  "same_receipt": result["receipt"] == RECEIPT,
                  "no_new_model_or_write": not rt.calls,
                  "facts_preserved": result["facts"] == FACTS}
    return {"scenario": "guided_429" if variant == "reference" else "guided_committed_then_429",
            "time_basis": "integer_logical_time", "provider_calls": 0, "variant": variant,
            "checks": checks, "pass": all(checks.values()), "result": result, "audit": rt.audit()}


def grade(path):
    cases = []
    for name in CASES:
        try:
            run = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--mode", "grade-case",
                                  "--learner", str(Path(path).resolve()), "--case", name],
                                 text=True, capture_output=True, timeout=5)
            row = json.loads(run.stdout.splitlines()[-1])
            row["worker_exit_code"] = run.returncode
            if run.returncode != (0 if row.get("pass") else 1):
                row["pass"] = False
                row["errors"].append("worker_exit_code_mismatch")
        except (subprocess.TimeoutExpired, ValueError, IndexError) as exc:
            row = {"case": name, "pass": False, "errors": ["worker_failed:" + type(exc).__name__]}
        cases.append(row)
    return {"mode": "grade", "time_basis": "integer_logical_time", "provider_calls": 0,
            "worker_timeout_seconds": 5, "worker_timeout_purpose": "hang_guard_not_performance_gate",
            "python": platform.python_version(), "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "learner_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
            "module_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(), "module_path": str(Path(path).resolve()),
            "passed": sum(c["pass"] for c in cases), "total": len(cases),
            "pass": all(c["pass"] for c in cases), "cases": cases}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("command", nargs="?", choices=["guided", "scaffold", "incident", "explain", "grade"])
    parser.add_argument("--mode", choices=["reference", "template", "debug", "grade", "grade-case"])
    parser.add_argument("--variant", choices=["broken", "repaired"], default="broken")
    parser.add_argument("--learner", "--module", dest="learner")
    parser.add_argument("--case", choices=CASES)
    parser.add_argument("--out")
    args = parser.parse_args()
    modes = {"guided": "reference", "scaffold": "template", "incident": "debug", "explain": "debug", "grade": "grade"}
    if args.command:
        if args.mode:
            parser.error("use a command or --mode, not both")
        args.mode = modes[args.command]
        if args.command == "explain":
            args.variant = "repaired"
    if args.mode is None:
        parser.error("choose guided/scaffold/incident/explain/grade")
    if args.mode == "template":
        if not args.out:
            parser.error("template requires --out")
        path = Path(args.out)
        if path.exists():
            parser.error("refusing to overwrite learner file")
        path.write_text(TEMPLATE, encoding="utf-8")
        result = {"mode": "template", "path": str(path), "pass": True}
    elif args.mode in ("reference", "debug"):
        result = guided("reference" if args.mode == "reference" else args.variant)
    else:
        if not args.learner or (args.mode == "grade-case" and not args.case):
            parser.error("grade requires --learner; grade-case also requires --case")
        result = grade_case(args.learner, args.case) if args.mode == "grade-case" else grade(args.learner)
    output = json.dumps(result, ensure_ascii=False, sort_keys=True)
    if args.out and args.mode != "template":
        Path(args.out).write_text(output + "\n", encoding="utf-8")
    print(output)
    return 0 if result["pass"] else 1


if __name__ == "__main__":
    sys.exit(main())

Bounded backoff and idempotence; Function calling associations; lab source.

Worked trace: one 429, three gates, one draft

Visual guide · Trace biz-77 before spending a fallback call

Trace biz-77 before spending a fallback call

Authored narrow guided trace; zero provider calls. This branch starts only after validation and write-state reconciliation. Logical time and fixture responses do not measure a network deadline. Select the figure to open it at full size.

This is a narrowly authored branch walkthrough executed against RoutingRuntime, not an independent learner solution or real model response. Preconditions: IDs and strict integer budgets validate; write_state=none; permanent failures and committed/unknown writes have already been handled by the ordered contract below. Input is business_id=biz-77, required_caps=['tools','json'], used_calls=1, max_model_calls=2, deadline=5, now=0, and event={kind: rate_limited, http_status: 429, wait_units: 2}. The retained fact is {kind: tool_result, operation_id: read-op-1, data: confirmed}. business_id names the business action; operation_id links executed evidence and is not a replacement business identity or provider call ID.

Step 1: with capabilities ['tools'], sorted missing capabilities are ['json']. Return capability_blocked/missing:json, calls [], now0, ledger []. Step 2: restore both capabilities but set used_calls=2. The shared allowance has no remaining model call: return budget_exhausted/model_call_budget_exhausted, calls []. The fallback does not receive a fresh allowance just because its model name differs. Step 3: restore used_calls1 but start now4. Since 4+2>5, return deadline_exceeded/backoff_exceeds_remaining_time before waiting, calls [], now4.

On the original now0/used_calls1 input with both capabilities, 0+2≤5: execute exactly wait(2) and call_fallback('biz-77', facts). Audit records actions wait then fallback, now2, no ledger rows. The drafted result is draft_ready/fallback_draft, with receipt=None, draft='fixture draft', and unchanged facts. One used primary plus one fallback equals the allowed total2; the function does not mutate state.used_calls. If that one backup instead returns unavailable, the same two calls end at paused/fallback_unavailable; there is no third model attempt. Only the result draft is ready: business completion was not established.

Concrete counterexample: calling fallback first and checking its capabilities afterward has already spent the forbidden call. Resetting used_calls on the backup similarly exceeds the shared allowance. invalid_parameters/400, permission denial and refusal never enter this 429 branch. A declared capability only passes this fixture gate; it does not prove a real adapter or model can perform the task.

Executed narrow trace source, actual calls, inputs and outputs, unchanged runtime. Save both Python files together and run python3 -B guided_depth_trace.py > guided-depth-output.json. The trace never calls case_data; expectations alone are not execution. It makes zero provider calls and cannot establish live 429 handling, network latency, model quality or a 17-case learner pass. Logical fallback response time is zero in this fixture; equality with deadline is not a real HTTP time guarantee.

Continue in one runnable project: a backup inherits the same return facts

Harness Journey makes fallback part of the actual return path. An authored primary 429 reaches a bounded backup carrying the same task/business identity and actual tool facts; the candidate must still satisfy evidence, proposal and approval gates before the merchant can write. Read the routing walkthrough and download the source.

Run python3 -B journey.py scenario --name fallback_blocked --work /tmp/journey-fallback. Permission denial, refusal, permanent invalid input, insufficient capability or exhausted bounds must not become permission to try another model. Once the write is unknown, recovery queries the original operation key instead of asking a new model to create another action. These are authored offline decisions with zero provider calls.

Continue the connected project article and inspect the executable entrypoint.

code example

Grade actual routing calls

The scaffold grades 0/17 with exit 1. Your route needs 17/17 with actual wait/fallback/lookup arguments and ledger inspection.

Acceptance task for this level

Implement route independently; keep the scaffold 0/17 failure, then submit 17/17, actual calls/ledger, and module/source SHA.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Does returning draft_ready without calling fallback pass?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.