Example

Write the runtime contract before the implementation

Run a typed request/backend contract with two architecture decisions and a toy conformance check that can fail.

A runtime design is a set of decisions about boundaries: what a request contains, what a backend must provide, what the engine returns, and which dependencies may cross the boundary. Writing those decisions down before optimising makes it possible to test a backend against a contract rather than against a particular implementation.

This example prints two architecture decision records and one RuntimeContract, then runs a toy backend through validate_contract. The contract names InferenceEngine, inputs prompt and max_new_tokens, and outputs text and tokens. The check asks the backend for hi plus two tokens and expects hixx. It is a smoke test, not a general type checker, and the page says so.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch41/contracts.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

RuntimeContract and ADR are dataclasses. Backend is a Protocol with one method. validate_contract executes that method and compares the result with a known string. The check is deliberately small enough to read in one screen.

@dataclass
class RuntimeContract:
    name: str
    inputs: List[str]
    outputs: List[str]

    def to_dict(self) -> dict:
        return asdict(self)


class Backend(Protocol):
    def generate(self, prompt: str, max_new_tokens: int) -> str: ...


class ToyBackend:
    def generate(self, prompt: str, max_new_tokens: int) -> str:
        return prompt + ("x" * max_new_tokens)


def validate_contract(backend: Backend) -> bool:
    result = backend.generate("hi", 2)
    return result == "hixx"


def run_demo() -> dict:
    adrs = [
        ADR("ADR-001", "CPU-first", "Core tests run on CPU."),
        ADR("ADR-002", "Typed contracts", "Use dataclasses and protocols."),
    ]
    contract = RuntimeContract(name="InferenceEngine", inputs=["prompt", "max_new_tokens"], outputs=["text", "tokens"])
    backend = ToyBackend()
    ok = validate_contract(backend)
    return {
        "adrs": [a.to_dict() for a in adrs],
        "contract": contract.to_dict(),
        "contract_valid": ok,
    }

Expected outcome

Observed with the command above (exit 0):

{
  "adrs": [
    {
      "id": "ADR-001",
      "title": "CPU-first",
      "decision": "Core tests run on CPU."
    },
    {
      "id": "ADR-002",
      "title": "Typed contracts",
      "decision": "Use dataclasses and protocols."
    }
  ],
  "contract": {
    "name": "InferenceEngine",
    "inputs": [
      "prompt",
      "max_new_tokens"
    ],
    "outputs": [
      "text",
      "tokens"
    ]
  },
  "contract_valid": true
}

The toy backend satisfies the smoke check. The output does not prove that the backend returns the declared tokens field, because the protocol’s return type is a single string and the contract’s outputs are only names. Those are design intentions, not enforced types.

Mechanism and limitations

Documented: RuntimeContract records a name, inputs and outputs. Backend is a protocol with one generate method. ToyBackend implements it by appending characters. validate_contract runs one example and compares the string. The tests check the toy validation, the two ADRs, the contract field and JSON serialisation.

Observed: the command exited 0 with the two ADRs, the contract and contract_valid: true. The targeted tests.test_ch41_contracts is part of the canonical suite; no independent test count is claimed here.

Not shown: a full type check, a real backend, conformance tests for every method, error semantics, cancellation, or a dependency graph. The validate_contract function is an example-specific assertion, not a reusable conformance suite. A backend can pass it and still violate the runtime’s real requirements.

Challenge this result

Change ToyBackend.generate to return "hiyy" and rerun; contract_valid should become false. Then add a second method to the protocol and a backend that does not implement it; explain why Python’s structural typing may not catch the omission at the call site. Finally, add an ADR for the cache policy and state one decision it forces on the backend interface.

Source and verification

Canonical source: examples/ch41/contracts.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch41_contracts.py . Chapter: Designing the Inference Runtime . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses a toy backend, not a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.