Skip to content

resource

Uncertain Supplier Orders: Unit B Exercises

Study uncertain supplier orders in Chapter 11. Unit B: diagnose a controlled failure, repair it and test a changed case in the student notebook.

Student edition · 90 minutes of dedicated work · 2026-09-09

This is one of two practical units for Chapter 11. Unit A constructs and connects the mechanism; Unit B investigates a controlled failure, repairs it and transfers the invariant. Each is a complete ninety-minute session, with its own setup and required conceptual introductions. Basic Python variables, conditions, loops, functions, lists and dictionaries are the starting knowledge. Libraries and specialized concepts used here are introduced below before the main task.

By the end you should be able to:

  1. Explain the chapter's mechanism using a prediction and an observed intermediate result.
  2. Repair a retry that invents an operation identity, then normalize another supplier's discovery response without changing intent.
  3. Solve interpret discovery without inventing certainty using changed inputs and an independent expectation.
  4. Retain your implementation, failed/corrected observations, causal explanation and limits.
MinutesDedicated activityEvidence you produce
0–5State the problem and make a predictionInitial prediction in your own words
5–25Foundations and library examplesValues, explanations, revised predictions
25–35Trace setup and the main interfaceInput → learner function → observation
35–60Reproduce, diagnose and repairSource, visible checks and runtime evidence
60–80Implement and challenge the transfer taskFunction and a new counterexample
80–90Retrieve, explain and saveExit ticket and retained submission

Installation is preparation time. These are planning estimates, not measured completion times. Use the reference primers when a term is unfamiliar; in Unit B retrieve an explanation before re-reading it. Run All checks that the artifact executes. Unfinished student functions deliberately produce NEEDS_WORK. Keep your first attempt before opening answers.

This notebook belongs to the nineteen-chapter edition. Its supplied teaching runtime is embedded, so it can run without the textbook or another notebook. Where code uses REFERENCE_LESSON, that is the frozen runtime exercise identifier; the reader-facing chapter and saved unit identifiers use the current edition. Building against a supplied runtime is not proof that you have constructed all of its dependencies.

Run the self-contained setup

Use a Python 3.14 Jupyter kernel and Pydantic 2. If needed, run %pip install "pydantic==2.13.4" once in a separate cell and restart the kernel. Package installation needs internet; the lesson itself needs no repository download, API key or prior notebook. The complete source runtime uses Python 3.14, so this edition does not claim compatibility with a hosted notebook service's default interpreter.

The collapsed cell contains 89 frozen teaching files. Base85 represents compressed bytes as text; zlib decompresses them; SHA-256 checks that the decoded files match this edition. These are supplied packaging operations, not learner algorithms. tempfile creates an isolated working copy; Path handles file locations; sys.path tells Python where the supplied modules live. The code is available for inspection below and performs no package installation itself. The subsequent lesson teaches the libraries used by the mechanisms you will implement.

Run setup on every fresh kernel. It writes scratch runtime files separately from your retained practical-work/ch11-b folder. Rerunning setup restores the frozen support files and keeps your saved work. Restarting a kernel clears variables, not saved submission files. Source basis: Sovereign Agent 444c5f6. Some tasks use reviewed local subprocesses; they are not an OS sandbox.

Supplied offline setup and teaching files

The complete supplied setup cell is in the downloadable notebook. Run it there before attempting the cells below. This web edition omits only that compressed setup payload.

Commit to a prediction before the examples

python
prediction_notes = {
    "prediction": "Write the expected behavior before running the worked example.",
    "reason": "Name the input and rule behind that prediction.",
    "falsifier": "Name an observation that would prove the explanation wrong.",
    "revision": "After execution, explain what changed in your understanding.",
}

Reading the Python vocabulary used in this notebook

You need basic assignments, if, loops, functions, lists and dictionaries. The less familiar features used by the supplied code are introduced here. A library is reusable code that Python can import. The standard library ships with Python; Pydantic is an additional package. An import makes a name available, but does not mean that you have completed the exercise.

JSON is text for exchanging structured values. A Python dictionary is an in-memory object; the JSON representation is a string. Use json.dumps to encode and json.loads to decode. Decoding proves that text has valid JSON syntax, not that its fields match our business contract. Predict which of the following two decoded objects could describe a stock count.

python
import json

intro_data = {"sku": "MANGO", "count": 3}
intro_text = json.dumps(intro_data, sort_keys=True)
print(type(intro_data).__name__, type(intro_text).__name__, intro_text)
print(json.loads(intro_text))
print("Also valid JSON:", json.loads('["not", "a", "stock", "record"]'))
assert json.loads(intro_text) == intro_data

The first result is a dictionary; the second is a list. Before indexing a decoded object, check the shape that your function promises to accept. An exception interrupts the normal path. raise ValueError(...) refuses an invalid value; try/except lets a caller inspect that expected refusal. Catch the expected class, rather than turning every programming error into apparent success. finally runs cleanup even when an earlier operation raises.

An annotation, such as count: int, documents the expected type. It does not by itself enforce the type at runtime. A class defines a kind of object; an instance holds one object's data. @dataclass asks Python to generate routine construction and comparison methods from annotated fields. frozen=True prevents ordinary reassignment of the instance's fields; it does not make every object nested inside those fields immutable. A method is a function attached to a class; self refers to the instance receiving the call.

python
from dataclasses import dataclass


@dataclass(frozen=True)
class IntroObservation:
    operation: str
    count: int


intro_observation = IntroObservation("count-mango", 3)
print(intro_observation.operation, intro_observation.count)
assert intro_observation == IntroObservation("count-mango", 3)

A callback is a function passed to another function. This is how the classroom harness invokes your implementation. The argument candidate below is a function object; parentheses perform the call. Predict the two answers before execution, then trace the result to the callback.

python
def intro_apply(candidate, value):
    return {"input": value, "observed": candidate(value)}


def intro_double(value):
    return value * 2


print(intro_apply(intro_double, 3))
print(intro_apply(lambda value: value + 2, 3))
assert intro_apply(intro_double, 3)["observed"] == 6

lambda value: value + 2 is a small anonymous function. A closure is a function that retains access to values from its surrounding scope. It can bind a tool to a shop snapshot. A shallow copy duplicates only the outer container; copy.deepcopy also copies nested containers used in these fixtures. A set stores distinct values; required <= allowed asks whether every required item is allowed. frozenset is the corresponding immutable set. A tuple groups ordered values; (value,) is a one-item tuple, including the comma.

Paths and cleanup. Path represents a filesystem location. path / "file.json" constructs a child path; read_text and write_text read and write text. A context manager, used with with, manages entry and exit. A temporary-directory context removes its contents on exit. Save your submission outside temporary runtime directories. Reopening a file is different from reusing a Python variable: the former tests retained bytes, while the latter only tests this kernel.

python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as intro_folder:
    intro_path = Path(intro_folder) / "observation.json"
    intro_path.write_text(json.dumps(intro_data), encoding="utf-8")
    intro_reopened = json.loads(intro_path.read_text(encoding="utf-8"))
    assert intro_reopened == intro_data
    print("Read from a file:", intro_reopened)

Retrieval check: explain JSON versus a dictionary, annotation versus validation, class versus instance, and defining a callback versus invoking it. Change the callback above so an incorrect implementation visibly changes the observed output. This distinction will matter when grading your connected work. Reference: Python's JSON, dataclasses, and pathlib documentation.

Pydantic: turn an input dictionary into a checked object

Pydantic is an additional Python library for validating data. Its model is a class describing fields, not a neural network. Inherit from BaseModel, declare annotated fields, then call model_validate on incoming data. A field without a default is required. A field with a default can be omitted. The result is an instance whose values you read with dot notation.

python
from pydantic import BaseModel, ConfigDict, Field, ValidationError


class IntroCourseRequest(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid")
    name: str = Field(min_length=1)
    quantity: int = Field(gt=0, le=1000)
    note: str = ""


intro_request = IntroCourseRequest.model_validate({"name": "mango", "quantity": 4})
print(intro_request.name, intro_request.quantity, repr(intro_request.note))
assert intro_request.note == ""

The annotation says the field's type. Field supplies constraints: gt=0 means greater than zero, le=1000 means at most 1000, and min_length=1 excludes an empty name. ConfigDict sets model-wide behavior. strict=True rejects conversions for this integer field, including "4", 4.0 and True; extra="forbid" rejects undeclared keys. Pydantic can otherwise convert some compatible inputs, so choose this boundary deliberately rather than assuming every accepted input arrived in the expected type.

Predict which rule refuses each payload. ValidationError reports a failed contract. Its errors() entries contain loc, the field location, and type, the failure category. Catching that expected exception lets the notebook inspect the failure and continue.

python
intro_bad_requests = [
    {"name": "mango", "quantity": "4"},
    {"name": "mango", "quantity": True},
    {"name": "", "quantity": 4},
    {"name": "mango", "quantity": 0},
    {"name": "mango", "quantity": 4, "approved": True},
    {"quantity": 4},
]
for intro_bad_request in intro_bad_requests:
    try:
        IntroCourseRequest.model_validate(intro_bad_request)
    except ValidationError as intro_error:
        print([(item["loc"], item["type"]) for item in intro_error.errors(include_input=False)])
    else:
        raise AssertionError("An invalid input crossed the declared contract")

Use model_dump() for a Python dictionary, model_dump_json() for JSON text, and model_validate_json() to parse and validate JSON. model_json_schema() describes the contract; it is neither an instance's current values nor an invocation of the business handler.

python
intro_serialized = intro_request.model_dump_json()
intro_schema = IntroCourseRequest.model_json_schema()
assert IntroCourseRequest.model_validate_json(intro_serialized) == intro_request
print("Actual values:", intro_request.model_dump())
print("Quantity contract:", intro_schema["properties"]["quantity"])
assert intro_schema["properties"]["quantity"]["exclusiveMinimum"] == 0

Four is valid input to this schema even if the shop needs six. Pydantic checks the declared shape and constraints; the handler still needs authoritative stock, price and permission. Ordinary assignments to an existing instance are not automatically revalidated unless configured for assignment validation. This lesson validates new input at the boundary and uses the resulting values. Explain these limits before relying on a model object in a transaction or tool call.

Chapter 2's full introduction expands this pattern with a separate data-repair checkpoint. This notebook contains the required pattern here so prior Pydantic experience is not needed. References: models, fields, and strict mode.

SQLite from the first row to an atomic change

A dictionary disappears when its process ends. A database can retain records so a later process can resume from evidence. SQLite is an embedded database: Python's sqlite3 library opens a local database file without starting a separate database server. SQL is the language used to define, select and change its records. A table has named columns and rows. A primary key identifies a row; a query asks for rows satisfying a condition.

Start with a deliberately small preference table. Read the SQL as instructions: create the table, insert one named value, then select the value for one session. ? is a parameter placeholder; the values are passed separately so they are data, not SQL instructions. fetchone() returns one row or None; it does not guarantee that a matching row exists.

python
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as intro_sql_folder:
    intro_db_path = Path(intro_sql_folder) / "example.sqlite"
    intro_db = sqlite3.connect(intro_db_path, autocommit=True)
    intro_db.execute("CREATE TABLE preference (id INTEGER PRIMARY KEY, session TEXT, value TEXT)")
    intro_db.execute("INSERT INTO preference (session,value) VALUES (?,?)", ("lucy", "09:00"))
    intro_row = intro_db.execute(
        "SELECT value FROM preference WHERE session=?", ("lucy",)
    ).fetchone()
    print("Matching row:", intro_row)
    assert intro_row == ("09:00",)
    assert (
        intro_db.execute(
            "SELECT value FROM preference WHERE session=?", ("another-session",)
        ).fetchone()
        is None
    )
    intro_db.close()
    intro_reopen = sqlite3.connect(intro_db_path, autocommit=True)
    assert intro_reopen.execute("SELECT count(*) FROM preference").fetchone()[0] == 1
    intro_reopen.close()
print("The row survived closing and reopening its connection.")

Index [0] selects the first column of a returned tuple. sqlite3.Row is an alternative row factory that also permits named-column access. dict(row) then produces an ordinary dictionary. The book's Database wrapper supplies that configuration and its schema; the wrapper is course code, while sqlite3 is the standard library. You will use the public connection and transaction methods explained at the exercise boundary, rather than needing to reconstruct the wrapper.

Now consider a budget. Moving five pence from reserved to spent requires two values to change together. A transaction makes a group of local changes commit together or roll back together. The example explicitly controls SQL transactions with autocommit=True and SQL statements. BEGIN IMMEDIATE starts a write transaction; COMMIT keeps its changes; ROLLBACK discards them. Predict the row after the deliberately raised exception. Catching an error alone would not undo the first update; the rollback is the operation that restores the prior state.

python
intro_ledger = sqlite3.connect(":memory:", autocommit=True)
intro_ledger.execute(
    "CREATE TABLE budget (id INTEGER PRIMARY KEY, reserved INTEGER, spent INTEGER)"
)
intro_ledger.execute("INSERT INTO budget VALUES (1,5,0)")
intro_ledger.execute("BEGIN IMMEDIATE")
try:
    intro_ledger.execute("UPDATE budget SET reserved=0 WHERE id=1")
    raise ValueError("injected failure before the matching spend update")
except ValueError:
    intro_ledger.execute("ROLLBACK")
assert intro_ledger.execute("SELECT reserved,spent FROM budget").fetchone() == (5, 0)
intro_ledger.execute("BEGIN IMMEDIATE")
intro_ledger.execute("UPDATE budget SET reserved=0,spent=5 WHERE id=1")
intro_ledger.execute("COMMIT")
print(
    "After a complete change:", intro_ledger.execute("SELECT reserved,spent FROM budget").fetchone()
)
intro_ledger.close()

The literal :memory: creates a temporary database inside this connection; it is useful for the small experiment, but the earlier file example establishes persistence. Neither example proves that a remote supplier rolls back when the local transaction rolls back. An external operation has its own state and evidence.

SQL you will meet later. UPDATE ... SET ... WHERE ... changes selected rows. AND combines conditions. ORDER BY makes an ordering explicit; absent that clause, do not rely on row order. count(*) counts rows; sum(amount) totals a column and can be NULL on an empty input; coalesce(sum(amount),0) uses zero for that empty aggregate. A UNIQUE constraint rejects duplicate identities. GROUP BY status computes one aggregate per status.

An invariant is a condition that must remain true across operations, such as nonnegative reserved money. A snapshot is a consistent view at one point; two separate reads can describe different moments unless their transaction contract binds them. In the book, with db.immediate() groups related writes. It is a course-defined context manager with the commit/rollback purpose you just observed. Do not assume that an arbitrary with connection has identical behavior under every SQLite autocommit setting.

Your prediction: two workers both read ten remaining pence outside a transaction and each approve seven. Why can both believe the next order fits? Explain what must be checked together with the write. Then change the example's initial reserved amount and repeat the failure. Reference: Python's SQLite tutorial and transaction control.

An ambiguous response leaves two systems with different knowledge

Lucy approves an order. The supplier stores it, then the network reply is lost. Locally we see a timeout; remotely an order exists. The central difficulty is not calculating the quantity again. It is deciding what evidence is available without creating another purchase. Distributed state means relevant records live in more than one independently changing system.

An intent is the durable local record of one exact operation before sending. An operation identity distinguishes that intent from another business operation. A receipt binds a supplier outcome to that identity and exact proposal. Reconciliation asks the external system for evidence and brings local state into agreement where the evidence is conclusive.

Separate the effect from the caller's observation

The function below deliberately stores a supplier record before raising. The exception describes what the caller observed; it does not reverse the stored effect. Predict both the local exception and the independent order count before running.

python
intro_supplier_orders = {}


def intro_accept_then_lose_reply(operation, proposal):
    if operation in intro_supplier_orders and intro_supplier_orders[operation] != proposal:
        raise ValueError("same identity used for different intent")
    intro_supplier_orders.setdefault(operation, dict(proposal))
    raise TimeoutError("reply lost after acceptance")


for intro_operation in ("opening-order", "opening-order"):
    try:
        intro_accept_then_lose_reply(intro_operation, {"sku": "MANGO", "quantity": 4})
    except TimeoutError:
        print("caller state UNKNOWN; supplier count", len(intro_supplier_orders))
assert len(intro_supplier_orders) == 1

This fixture's stable-identity contract prevents a second effect when the same operation is repeated. A real supplier must explicitly support the relevant behavior; a local ID string alone cannot force a remote service to deduplicate. The book's supplier fixture lets us inspect the independent records so the experiment does not grade its own final prose.

Why a new identity creates a new operation

Repeat the experiment with a new identity after the lost reply. Nothing tells the supplier that the second identity is intended as a retry of the first. There are now two valid-looking intents for the same products. Identical payloads are not enough to conclude that two operations are one.

python
try:
    intro_accept_then_lose_reply("opening-order-retry", {"sku": "MANGO", "quantity": 4})
except TimeoutError:
    pass
assert len(intro_supplier_orders) == 2
print("Stored operation identities:", sorted(intro_supplier_orders))

Unit B introduces this defect at the actual send boundary with a freshly generated UUID. A UUID is a generated identifier; uniqueness is useful for a new intent but harmful when it accidentally turns a retry into a new business operation. The repair reuses the recorded identity and proposal. The evidence is the supplier's order count, not a message claiming “retry handled.”

Read the local state machine

StateWhat the local record saysWhat it does not establish
APPROVEDExact intent has bounded authoritySupplier acceptance
SENDINGSend was admitted and intent recordedA conclusive response
UNKNOWNAvailable evidence cannot settle the outcomeFailure or permission for a new order
CONFIRMEDMatching accepted receipt was retainedPhysical delivery
REJECTEDMatching conclusive rejection was retainedThat every transport failure is rejection

The reservation remains held while the outcome is uncertain. On a matching accepted receipt, money moves from reserved to spent exactly once. On a conclusive rejection, the reservation is released. A repeated identical receipt must not spend twice; a contradictory receipt must not silently overwrite the first outcome. Both identity and exact proposal need comparison.

Adapt vocabulary without weakening evidence

Another supplier may call its fields order_ref, payload and decision. An adapter maps these names to the internal receipt. It must preserve operation and proposal and reject unknown decisions. None from a lookup is not an accepted receipt. Nor is an unavailable lookup proof that no remote order exists. Keep absence, unavailability and conclusive rejection distinct.

The core code uses SQLite for local intent and a local supplier fixture for independent effects. A loopback server, where used, listens on this machine rather than contacting a real supplier. Its subprocess and temporary database are supplied infrastructure. Your work constructs the transition boundary, repairs identity handling and normalizes changed discovery data.

Before coding, draw two columns, local ledger and supplier ledger, at four instants: before send, after acceptance, after lost reply and after lookup. Put unknown values explicitly in the table. The transfer task will change the receipt vocabulary and failure schedule while requiring the same accounting invariant.

Choose an explicit starting point for this independent notebook

This Unit B runs without Unit A. By default it prepares a supplied reference starting point and labels its provenance. It is not evidence that you built Unit A. To investigate your own successful implementation, set LEARNER_HANDOFF to its saved path before running the cell. An invalid selected file refuses; it is never silently replaced with the reference.

SourceTask supplies copied-source execution and handoff validation; RuntimeLab supplies the controlled failure experiment. Their public operations are introduced beside the main exercise. The artifact stores identity and observations; no variables from another kernel are required.

python
LEARNER_HANDOFF = None

Prepare and validate the supplied starting artifact

python
import json
import runpy
import shutil
from pathlib import Path

COURSE_INPUT = COURSE_WORK / "ch11-unit-a-handoff-v1.json"
if LEARNER_HANDOFF is not None:
    learner_input = Path(LEARNER_HANDOFF).expanduser().resolve()
    if not learner_input.is_file():
        raise FileNotFoundError("The selected learner handoff does not exist")
    if learner_input != COURSE_INPUT.resolve():
        shutil.copy2(learner_input, COURSE_INPUT)
    HANDOFF_ORIGIN = "LEARNER_SELECTED"
else:
    reference_encoded = (
        "c-pmD>vG$;75>ksK>26MET!1H?M~wvHsjh%t0s{&l9F`C^>APkvazN}h5+qoGoI-~^a=YUJ-CtJMRt<y"
        "`iDh;z`?nn4~KMD78OUoup)PyZB^_LEAB`|=ye|BYm)ORxr6@<QMC}4CCSrRPC5>?cI)SYnWw7G%e@(}"
        "j~V6U$7Z;1mT|Hxw=^TonC^(;q{RFtqgUqWB@8u>71;uhc|zi%y2d&E6?0nTY|401k*Va{>|%tZaaJe$"
        "ap^E)lyRJMpp=rTk#jA?r1|x-$Y`<;gxnQu4G{d41tU*UyDzF+Lo3NJ-35r`A8S${*qLIEuP`HK&$%8u"
        "4$ve@V^i3|K+c%v+XDS1MBa}9I{u^YIIG2CgF<w+c(+<du^2gEoIE8$3Lqb|x-2tFDp(}VGKK%K(67gM"
        "<;m^Ok$Y7Xx6g5QkM}Gt^5@A7Np8!6g8AY3=*6_$yS{(nAoz2~sJqUk<180%W@kUcL0uJkAoi~$XM}s7"
        "U11OR!4D8GIL_iym@@n!J~}!AVVsm~jlNT57OyG_9-wEi0aw?Ahwhes;&nyb0I}OTbl0!nP2Qi*XK&t|"
        "!qmqaOhEZQ{K-F&+@@E+k5Q>4Cd5^mSDxwma$(~wUV5cwwAEl7AUC<eB`4L36Y_~v31#AZB@FzoNSTqG"
        "vKzrvef0}TcnHiXGSVMH<qBO|6UJ+yMa=;f&vdJ7rJYS~5EP`et$d9-)Q=*N(rdyvY)-GHNs;Hk2KdYr"
        "I8JI#Jh?_%a2>sg&NgQKtJUHy8brf~zelSGcnV*FP+rShpw9BATf&o@A}5}Iadau?wB_1^fcfUxqR_sV"
        "476jMKoo~st<7vHy(m=P)lQR7C9MbxMb?;#f1Z!NM?W2@6^hG>fUD%FRbtD9_BJVPTwFn<-N{rUHQp}M"
        "Zd4WbU#?fsBd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yKw%Bd|<>jt(Xht=SGoEmk_nlioID$Iu&cG779L"
        "n%xiy(Xlh|*lZ+=S#?+pW%+=bb9_9hbIK=pasvpe*ls6x$5T;5A)f9lh~$`)Pu3mODzA+nw*|J}t`i@="
        "+<)b6pc-j#D-Ye8Zzq3tt#4tvB!f2RrfblUzOY^O()xg7FH!z!z4e_o>2;~k7V~(%*u<;o^!#V^-+%uH"
        ")LCL$4I?}dIWHHVrV+lzG@pv1Z@#g{uuFUrHv#Ml9SYba6^iwZ+r?ZIegW@J(6OFNid~rzH77XhVg}t6"
        "aJN|A+|?41g~yk%TM9Q8vF@lLZ+a#cXcUm9%{m&*7%doPwf)7m53AW`6U`6qGw%cE!2qi0pV8`UCcgAX"
        "%f)IFx?p+BS9*#Y_=*2NmhLDa"
    )
    reference_code = zlib.decompress(base64.b85decode(reference_encoded)).decode()
    reference_namespace = {"COURSE_ROOT": COURSE_ROOT, "COURSE_WORK": COURSE_WORK}
    exec(compile(reference_code, "<supplied-unit-a-reference>", "exec"), reference_namespace)
    if not COURSE_INPUT.is_file():
        raise RuntimeError("The supplied reference did not produce its handoff")
    HANDOFF_ORIGIN = "SUPPLIED_REFERENCE"
print("Starting evidence:", HANDOFF_ORIGIN)
print("The core task below validates the selected artifact before using it.")

Understand the supplied execution interface

The course runtime is provided so your implementation can be connected to real callers and storage. SourceTask(ROOT, chapter) makes a private copy. install(source) replaces only the declared function; visible() invokes the real chapter probe; save(path, result) retains a successful implementation and its evidence. load(path) checks the saved identities and hashes. inject_failure() changes the declared boundary; repair(fragment) replaces that broken fragment. close() removes the scratch copy after you retain evidence. These methods are supplied harness operations, not additional packages you must discover or install.

RuntimeLab provides the same copied-source failure experiment without the complete-function construction layer. Its run method records exit status, observations and the compared expectation. A subprocess log from an unfinished learner implementation is feedback about that implementation; it is not a successful connection. A syntax error in the notebook cell itself is a separate issue to fix. The task below names which interface it uses.

For direct-function units, the visible driver calls your callback without installing a source string. In either case, trace where your code is invoked. Supplied fixtures, database wrappers and replay models are labelled infrastructure; your own implementation and changed-case explanation are the evidence of learning.

Main practical: construct, connect and challenge

Unit A preserved one exact intent and later settled it from supplier evidence. Now you will make a plausible retry bug create two remote purchases, repair the real order boundary, and adapt a second supplier's discovery shape without changing the meaning of its receipt.

This unit runs reviewed repository code in bounded local subprocesses and starts only in-memory or loopback supplier fixtures. A subprocess is not a security sandbox.

1. Verify the handoff and load the real experiment

python
import json
import os
import sys
import tempfile
import time
from pathlib import Path

assert sys.version_info >= (3, 14)

ROOT = COURSE_ROOT


HANDOFF_PATH = Path("ch11-unit-a-handoff-v1.json")
handoff_status = "MISSING"
if HANDOFF_PATH.is_file():
    handoff = json.loads(HANDOFF_PATH.read_text(encoding="utf-8"))
    valid_handoff = (
        handoff.get("after_loss", {}).get("status") == "UNKNOWN"
        and handoff.get("final", {}).get("status") == "CONFIRMED"
        and handoff.get("supplier_orders") == 1
    )
    handoff_status = "VERIFIED" if valid_handoff else "INVALID"
print("UNIT_A_HANDOFF", handoff_status)

support = runpy.run_path(str(ROOT / "book/always_on/educator/runtime_labs_v1.py"))
RuntimeLab = support["RuntimeLab"]

Predict the broken observation before running it. If a retry invents a new operation ID, what can lookup of the original ID discover? How many supplier rows remain?

2. Break the real source copy

python
lab = RuntimeLab(ROOT, 9)
baseline = lab.run("BASELINE", expected=lab.spec["expected_baseline"])
lab.break_source()
broken = lab.run("BROKEN", expected=lab.spec["expected_broken"])
print(json.dumps({"baseline": baseline["observation"], "broken": broken["observation"]}, indent=2))
assert baseline["status"] == "PASS"
assert broken["status"] == "PASS"

The fault replaces the stable operation ID at the actual supplier.order call. The supplier accepts two distinct effects while both local attempts remain UNKNOWN.

3. Construct the repair

Return the complete replacement for the one broken fragment. The starter preserves the unsafe fresh-ID send.

python
def repair_fragment():
    return 'receipt = supplier.order(uuid.uuid4().hex, json.loads(row["proposal"]))'

Hint 1 — the decision

Retries for one intended purchase keep one operation identity. A new business purchase needs a new work item.

Hint 2 — the evidence

Compare supplier_order_count and local_statuses in the baseline and broken records. Read the marked line in lab.source_excerpt().

Hint 3 — the structure

Call supplier.order with the existing identifier and the stored proposal. Do not generate another UUID or change the expected data.

python
lab.repair(repair_fragment())
student_repair = lab.run("STUDENT_REPAIR", expected=lab.spec["expected_baseline"])
REPAIR_PASSED = student_repair["status"] == "PASS"
print(json.dumps(student_repair["observation"], indent=2))
print("REAL_SOURCE_REPAIR", "PASSED" if REPAIR_PASSED else "NEEDS_WORK")
lab.close()

State a diagnosis that this result could falsify. Printing the expected dictionary, changing expected data, or returning a canned tool result does not alter the independently observed supplier database.

4. Adapt another supplier's discovery evidence

The partner returns order_ref, payload, and decision. Implement the adapter boundary that converts None, accepted, or declined into the exact internal receipt shape. Reject unknown decisions rather than guessing.

python
def normalize_discovery(raw):
    return raw

Hint 1 — the decision

Normalize vocabulary at the integration boundary. Keep the stable operation and exact proposal unchanged.

Hint 2 — the evidence

Internal receipts use operation, proposal, and an uppercase conclusive status. An absent lookup stays None.

Hint 3 — the structure

Return None unchanged. Map accepted to ACCEPTED and declined to REJECTED; raise ValueError for any other decision.

python
partner_proposal = {
    "sku": "SKU-VANILLA",
    "quantity": 6,
    "unit_cost_pence": 250,
    "supplier": "lucy-local",
    "currency": "GBP",
}
expected_partner = {
    "operation": "partner-order-1",
    "proposal": partner_proposal,
    "status": "ACCEPTED",
}
try:
    VISIBLE_ADAPTER_PASSED = (
        normalize_discovery(None) is None
        and normalize_discovery(
            {
                "order_ref": "partner-order-1",
                "payload": partner_proposal,
                "decision": "accepted",
            }
        )
        == expected_partner
    )
except Exception:
    VISIBLE_ADAPTER_PASSED = False
print("VISIBLE_ADAPTER", "PASSED" if VISIBLE_ADAPTER_PASSED else "NEEDS_WORK")

5. Connect the adapter to the real order workflow

The partner makes its result discoverable only after order has been attempted. The second call to the real execute path must look up that evidence before considering another send.

python
from reference_organizations.store.agent import seed_lucy
from sovereign_agent.assistant_orders import SpendingPolicy, approve, execute, propose
from sovereign_agent.assistant_work import claim, enqueue
from sovereign_agent.database import Database


class PartnerSupplier:
    idempotent = True
    identity = "partner-v2"
    timeout = 1.0

    def __init__(self, normalizer, decision):
        self.normalizer = normalizer
        self.decision = decision
        self.receipts = {}
        self.events = []

    def order(self, operation, proposal):
        self.events.append(("order", operation))
        self.receipts.setdefault(
            operation,
            {"order_ref": operation, "payload": proposal, "decision": self.decision},
        )
        raise OSError("partner committed but reply was lost")

    def lookup(self, operation):
        self.events.append(("lookup", operation))
        return self.normalizer(self.receipts.get(operation))


def run_partner_fixture(normalizer, decision):
    with tempfile.TemporaryDirectory(prefix="ch09-partner-") as directory:
        db = Database(Path(directory) / "agent.sqlite")
        supplier = PartnerSupplier(normalizer, decision)
        policy = SpendingPolicy(frozenset({"lucy"}), total_pence=2_000)
        try:
            seed_lucy(db)
            enqueue(db, "chapter9:partner", "lucy", "Replenish", subject="SKU-VANILLA")
            work = claim(db, "chapter9-partner-worker")
            identifier = propose(db, work, "SKU-VANILLA", 6, target=supplier.identity)
            digest = db.connection.execute(
                "SELECT digest FROM assistant_orders WHERE id=?", (identifier,)
            ).fetchone()[0]
            approve(
                db,
                identifier,
                digest,
                actor="lucy",
                policy=policy,
                expires=time.time() + 60,
            )
            first = execute(db, work, identifier, supplier, policy=policy)
            second = execute(db, work, identifier, supplier, policy=policy)
            status = db.connection.execute(
                "SELECT status FROM assistant_orders WHERE id=?", (identifier,)
            ).fetchone()[0]
            money = tuple(
                db.connection.execute(
                    "SELECT reserved_pence,spent_pence FROM assistant_spending WHERE id=1"
                ).fetchone()
            )
            return {
                "statuses": [first["status"], second["status"]],
                "local_status": status,
                "events": [event for event, _ in supplier.events],
                "supplier_orders": len(supplier.receipts),
                "money": money,
            }
        finally:
            db.close()


partner_result = None
if REPAIR_PASSED and VISIBLE_ADAPTER_PASSED:
    partner_result = run_partner_fixture(normalize_discovery, "accepted")
    print(json.dumps(partner_result, indent=2))
    assert partner_result == {
        "statuses": ["UNKNOWN", "ACCEPTED"],
        "local_status": "CONFIRMED",
        "events": ["order", "lookup"],
        "supplier_orders": 1,
        "money": (0, 1500),
    }
else:
    print("TRANSFER_NOT_READY — repair both learner-owned mechanisms.")

The event order is evidence: no receipt existed until after order; reconciliation then used lookup; no second order began.

Exit ticket

Explain why a local transaction cannot guarantee exactly-once external effects. Name the supplier properties this result depends on, and state what the system must do if discovery is unavailable and retransmission is not idempotent.

python
exercise_report = {
    "unit": "ch11-b",
    "attempted": 2,
    "completed": int(REPAIR_PASSED) + int(VISIBLE_ADAPTER_PASSED),
    "failed": int(not REPAIR_PASSED) + int(not VISIBLE_ADAPTER_PASSED),
    "skipped": 0,
    "connection": "PASSED" if partner_result else "NOT_READY",
    "handoff": handoff_status,
}
print("EXERCISE_REPORT=" + json.dumps(exercise_report, sort_keys=True))

Changed-constraint construction: Interpret discovery without inventing certainty

Allow twenty minutes. Spend three minutes predicting, ten implementing and tracing, five on a new case of your own, and two explaining the surviving limitation. This is dedicated work, not an invitation to run a supplied answer. Both units revisit the same invariant after different core experiences; in Unit B, attempt this task from memory before consulting Unit A.

Implement transfer_check(operation, proposal, receipt). None means UNKNOWN. Otherwise require a dictionary whose operation equals the intended operation and proposal equals the exact proposal. ACCEPTED maps to CONFIRMED; REJECTED maps to REJECTED. Any other receipt or decision raises ValueError. Do not alter the proposal or assign a new operation ID.

Write your expected values before running the table. Keep one accepted case and one refusal. Your function is passed directly into the driver below. The driver copies inputs and checks they remain unchanged; it does not replace your implementation with the reference answer.

Hint 1 — identify the authoritative inputs Name the source field for each output value. Which input changes while the rule remains the same?

Hint 2 — choose the boundary cases Start with exact empty, exact equality and one value on each side of the boundary where valid. Do not add a special case for a visible product name or operation identity.

python
def transfer_check(operation, proposal, receipt):
    raise NotImplementedError("Require matching conclusive supplier evidence")
python
import copy
import json

TRANSFER_CASES = [
    ("no evidence", ["op-a", {"quantity": 4}, None], "UNKNOWN"),
    (
        "accepted evidence",
        [
            "op-a",
            {"quantity": 4},
            {"operation": "op-a", "proposal": {"quantity": 4}, "status": "ACCEPTED"},
        ],
        "CONFIRMED",
    ),
    (
        "new identity",
        [
            "op-a",
            {"quantity": 4},
            {"operation": "op-b", "proposal": {"quantity": 4}, "status": "ACCEPTED"},
        ],
        {"raises": "ValueError"},
    ),
    (
        "changed quantity",
        [
            "op-a",
            {"quantity": 4},
            {"operation": "op-a", "proposal": {"quantity": 5}, "status": "ACCEPTED"},
        ],
        {"raises": "ValueError"},
    ),
]


def same_transfer_value(actual, expected):
    if type(actual) is not type(expected):
        return False
    if isinstance(expected, dict):
        return actual.keys() == expected.keys() and all(
            same_transfer_value(actual[key], value) for key, value in expected.items()
        )
    if isinstance(expected, list):
        return len(actual) == len(expected) and all(
            same_transfer_value(a, e) for a, e in zip(actual, expected, strict=True)
        )
    return actual == expected


def run_transfer(candidate, cases):
    observations = []
    for label, arguments, expected in cases:
        supplied = copy.deepcopy(arguments)
        before = copy.deepcopy(supplied)
        raised = None
        try:
            actual = candidate(*supplied)
        except NotImplementedError:
            raised = "NotImplementedError"
            actual = {"unfinished": True}
        except Exception as error:
            raised = type(error).__name__
            actual = {"raises": raised}
        expects_error = isinstance(expected, dict) and set(expected) == {"raises"}
        correct = (
            raised == expected["raises"]
            if expects_error
            else (raised is None and same_transfer_value(actual, expected))
        )
        passed = correct and same_transfer_value(supplied, before)
        observations.append(
            {"case": label, "expected": expected, "observed": actual, "passed": passed}
        )
        print("PASS" if passed else "NEEDS_WORK", label, "expected", expected, "observed", actual)
    return observations


transfer_observations = run_transfer(transfer_check, TRANSFER_CASES)
TRANSFER_PASSED = all(row["passed"] for row in transfer_observations)
print("TRANSFER_STATUS", "PASS" if TRANSFER_PASSED else "NEEDS_WORK")

Design a counterexample and retrieve the mechanism

Add one new case with an independently calculated expected outcome to TRANSFER_CASES and rerun the driver. Change one condition at a time. Then deliberately replace your candidate with a constant answer in a temporary copy and show a case that rejects it. Restore your implementation. Explain why that counterexample is stronger than repeating the original example with a new name.

Without viewing the worked example, write the invariant in words and trace one observed value back to its input. Identify which part is a local fixture result and which claim would need a live provider, host or external-system observation. Keep a first attempt even if you used a hint.

Save your evidence and explain the result

Fill the prediction notes and your explanation before saving. Include the exact observed value, the input or retained row that caused it, your code's invocation point, one failed hypothesis, and the strongest claim the evidence still cannot support. A completed code cell alone does not earn explanation credit. Do not label reference-start behavior as your own Unit A construction.

Keep this edited notebook, the Markdown if used for notes, saved handoff files, and the JSON record below. Your work folder survives scratch cleanup and can be reopened in a new kernel. An instructor can ask for an unseen case after the visible checks; keep your implementation general.

python
explanation_notes = {
    "causal_trace": "Explain the input, learner invocation and observed result.",
    "failed_hypothesis": "Describe a prediction the evidence changed.",
    "remaining_limit": "Name the guarantee not established by this experiment.",
}
course_submission = {
    "unit": "ch11-b",
    "planned_minutes": 90,
    "starting_evidence": globals().get("HANDOFF_ORIGIN", "INDEPENDENT_UNIT_A"),
    "prediction": prediction_notes,
    "explanation": explanation_notes,
    "core_report": exercise_report,
    "transfer": transfer_observations,
    "explanation_review": "HUMAN_REVIEW_REQUIRED",
}
submission_path = COURSE_WORK / "ch11-b-submission-v1.json"
submission_path.write_text(
    json.dumps(course_submission, indent=2, sort_keys=True), encoding="utf-8"
)
print("Saved evidence:", submission_path)
print(
    "COURSE_REPORT="
    + json.dumps(
        {
            "unit": "ch11-b",
            "transfer_passed": TRANSFER_PASSED,
            "starting_evidence": course_submission["starting_evidence"],
            "edition": "student",
        },
        sort_keys=True,
    )
)

Keep building with Prof Rod

Found this material through a colleague, classroom or shared download? Get the complete book at profrod.ai/book and join the Prof Rod learner community. Bring one result, one question or one failure you learned from. Share this resource with another learner and keep its source links with it so they can find the full course and future updates.

SOURCE PROVENANCE

Derived from github.com/profrodai/sovereign-agent/blob/5b825f3a58461bce8aba1173acf0b6d175c44b64/book/exercises/ch11/profrod-sovereign-agent-ch11-b-ambiguous-order-recovery-exercise.md