Student edition · 90 minutes of dedicated work · 2026-09-09
Runs on Google Colab as it ships today, or on any local Python 3.12+ kernel.
This is one of two practical units for Chapter 9. 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:
- Explain the chapter's mechanism using a prediction and an observed intermediate result.
- Repair the failure: Checking only the sender allows a group message into a private session. Use the real poll function and SQLite cursor with a fixture bot; reopen the database and replay an unordered batch.
- Solve plan private intake across accounts and replays using changed inputs and an independent expectation.
- Retain your implementation, failed/corrected observations, causal explanation and limits.
| Minutes | Dedicated activity | Evidence you produce |
|---|---|---|
| 0–5 | State the problem and make a prediction | Initial prediction in your own words |
| 5–25 | Foundations and library examples | Values, explanations, revised predictions |
| 25–35 | Trace setup and the main interface | Input → learner function → observation |
| 35–60 | Reproduce, diagnose and repair | Source, visible checks and runtime evidence |
| 60–80 | Implement and challenge the transfer task | Function and a new counterexample |
| 80–90 | Retrieve, explain and save | Exit ticket and retained submission |
Scroll horizontally to view columns.
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 construction 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
Open this notebook in Google Colab with the badge above, or use a local
Python 3.12+ Jupyter kernel, with 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 closing extension can use an OpenAI key from Colab's Secrets pane to put a
live model behind the same tools; without a key it replays a recorded transcript and says so.
The collapsed cell contains 90 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; a .pth file, the mechanism an editable install uses, tells reviewed local subprocesses the same. 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/ch09-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
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.
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_dataThe 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.
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.
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"] == 6lambda 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.
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.
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.
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.
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"] == 0Four 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.
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 cents 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.
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 cents 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.
Messaging is durable intake followed by separately observed delivery
Lucy sends a message from her phone. The assistant must decide whether it belongs to an authorized private conversation, record it once, and arrange work. A transport moves messages between systems. An adapter translates that transport's data into the application's internal shape. The offline fixture implements this adapter boundary without a Telegram account or network call. It proves local intake behavior; a live phone session requires separate transport evidence.
An incoming update has a transport identifier. A cursor records how far the poller has durably processed updates. A poll asks for a batch after that cursor. A batch may be repeated after a reconnect, so receipt is not permission to enqueue the same work again. Deduplication recognizes a stable origin identity and avoids creating a second local work item for it.
A sender and a conversation are different identities
An allowlisted person can write in a group. Checking only the sender's identity would route that
group message into a supposedly private session. The contract therefore checks chat kind and
matching sender/chat identity as well as the allowlist. A boolean is not an acceptable account
identifier even though Python considers bool a subclass of int.
intro_updates = [
{"id": 12, "sender": 7, "chat": 7, "kind": "private", "text": "Opening check"},
{"id": 13, "sender": 7, "chat": -50, "kind": "group", "text": "Opening check"},
{"id": 14, "sender": True, "chat": True, "kind": "private", "text": "Opening check"},
]
for intro_update in intro_updates:
intro_private = (
type(intro_update["sender"]) is int
and type(intro_update["chat"]) is int
and intro_update["sender"] == intro_update["chat"]
and intro_update["sender"] in {7}
and intro_update["kind"] == "private"
)
print(intro_update["id"], intro_private)The first message is admitted; the other two are refused. Changing the text to sound familiar must not change those identity decisions. Text is content, not proof of the actor's identity. The core task adds batch bounds, lease ownership, exact types and persistent enqueueing.
Advance the cursor only with durable work
Imagine recording cursor 14 and crashing before storing update 14's work. The next poll starts after 14 and loses that request. Reversing the operations without a transaction can instead duplicate work after a crash. The local intake rows and cursor advance belong in one transaction, with unique origin identities protecting replay. This is a local atomicity claim, not a claim that a transport and SQLite participate in one distributed transaction.
intro_seen = set()
intro_work = []
intro_cursor = 0
for intro_batch in ([14, 12, 13], [12, 13, 14], [15]):
for intro_update_id in sorted(intro_batch):
intro_origin = ("fixture-account", intro_update_id)
if intro_origin not in intro_seen:
intro_seen.add(intro_origin)
intro_work.append(intro_origin)
intro_cursor = max([intro_cursor, *intro_batch])
print("cursor", intro_cursor, "work count", len(intro_work))
assert len(intro_work) == 4This small set model explains the identity rule; it does not survive a restart. The real exercise uses SQLite, closes and reopens its connection, and inspects retained work and cursor evidence. Including the account in the identity prevents two accounts' update 12 from being mistaken for one event. Sorting gives a predictable order; do not assume transport arrival order is sorted.
A reply can be accepted while its acknowledgement is lost
Outbound delivery has another ambiguity. If the transport accepted a reply but the caller lost the acknowledgement, a local timeout does not prove the reply was never delivered. UNKNOWN means evidence is insufficient to choose success or failure. Automatically sending another message can create a duplicate. The notebook records intake and delivery state separately so an accepted incoming request is not mislabeled as proof of a delivered outgoing response.
The course _poll_owned function runs while holding a valid poll lease. A lease is a time-
bounded ownership claim; the transaction checks that claim before modifying durable state.
_enqueue is a supplied helper that creates the internal work item. Your implementation decides
which validated updates reach it and when the cursor advances. In Unit B the broken predicate
admits group messages; observing the actual work count exposes the effect.
Before the main exercise, write predictions for an empty batch, a reordered batch, a duplicate, a second account and an overlong text. State whether each should create work, move the cursor, both or neither under the stated contract. For a rejected malformed batch, test that neither earlier rows nor the cursor were partially changed.
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.
LEARNER_HANDOFF = NonePrepare and validate the supplied starting artifact
import json
import runpy
import shutil
import textwrap
from pathlib import Path
COURSE_INPUT = COURSE_WORK / "ch09-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:
source_task_class = runpy.run_path(
str(COURSE_ROOT / "book/always_on/exercises/source_tasks_v1.py")
)["SourceTask"]
reference_task = source_task_class(COURSE_ROOT, 6)
try:
reference_task.install(textwrap.dedent(reference_task.fragment))
reference_observation = reference_task.visible("SUPPLIED_REFERENCE_START")
if reference_observation["status"] != "PASS":
raise RuntimeError("The supplied starting point did not pass its connection check")
reference_task.save(COURSE_INPUT, reference_observation)
finally:
reference_task.close()
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 labeled infrastructure; your own implementation and changed-case explanation are the evidence of learning.
Main practical: construct, connect and challenge
Checking only the sender allows a group message into a private session. This time you begin with your Unit A implementation and its saved evidence. Lucy’s agent admits a message from a channel context her private-chat policy excludes.
Verify the handoff
The starting-point cell has selected the Unit A artifact explicitly. A selected learner handoff must validate; the default reference start is labeled separately. Run the setup and keep the runtime and implementation hashes in your submission.
import json
import os
import runpy
from pathlib import Path
ROOT = COURSE_ROOT
SourceTask = runpy.run_path(str(ROOT / "book/always_on/exercises/source_tasks_v1.py"))["SourceTask"]
REFERENCE_LESSON = 6
HANDOFF = Path("ch09-unit-a-handoff-v1.json")
handoff_status = "MISSING"
if HANDOFF.is_file():
task = SourceTask(ROOT, REFERENCE_LESSON)
try:
handoff = task.load(HANDOFF)
handoff_status = "VERIFIED"
print("IMPLEMENTATION", handoff["implementation_sha256"])
finally:
task.close()
print("UNIT_A_HANDOFF", handoff_status)Reproduce and diagnose
Predict the consequence of this injected boundary before executing it:
and TrueThe controlled mutation changes the same implementation you submitted. It refuses if the declared mutation boundary no longer occurs exactly once; inspect an alternative implementation with the instructor before adapting the experiment.
baseline = broken = None
if handoff_status == "VERIFIED":
task = SourceTask(ROOT, REFERENCE_LESSON)
try:
task.load(HANDOFF)
baseline = task.visible("YOUR_BASELINE")
if baseline["status"] != "PASS":
raise ValueError("Saved Unit A code no longer satisfies the visible contract")
task.inject_failure()
broken = task.run("INJECTED_FAILURE", expected=task.spec["expected_broken"])
print("BEFORE", baseline["observation"])
print("AFTER", broken["observation"])
finally:
task.close()
else:
print("HANDOFF_REQUIRED: complete Unit A before performing Unit B")State a diagnosis using those two observations. Name a test that would prove your diagnosis wrong. Use the real poll function and SQLite cursor with a fixture bot; reopen the database and replay an unordered batch.
Repair the boundary
Return the complete replacement for the injected fragment. Do not edit the oracle or print a desired observation. Repair the actual source. The starter keeps the defect so the learner outcome remains incomplete.
def repair_fragment():
return "and True"Hint 1: the consequence
Lucy’s agent admits a message from a channel context her private-chat policy excludes.
Hint 2: the evidence
Compare the two observations, then trace the changed field to _poll_owned in src/sovereign_agent/telegram_channel.py. Distinguish a schema refusal from a business-rule or authority refusal.
Hint 3: the design
Inspect the lease before writes, validate identities by exact integer type, use the existing _enqueue helper, and persist the highest offset after the whole batch.
def connect_repair(fragment):
task = SourceTask(ROOT, REFERENCE_LESSON)
try:
task.load(HANDOFF)
task.inject_failure()
task.repair(fragment)
return task.visible("YOUR_REPAIR")
finally:
task.close()
repair_result = None
if handoff_status == "VERIFIED":
repair_result = connect_repair(repair_fragment())
print("REPAIR", repair_result["status"], repair_result["observation"])
else:
print("REPAIR_NOT_ATTEMPTED: missing Unit A evidence")Transfer under a changed constraint
Change account, actor, update order, chat kind and message length. A rejected batch must not partially move the cursor or create work.
Create a fresh task, load your handoff, inject the defect and apply your repair. Then change only the copied probe to exercise the new condition. Keep the actual observation and a prediction written beforehand. Explain why a visible-case lookup or a blanket refusal could pass the original example but fail this transfer.
The instructor's holdout applies your repair to a new copied runtime and checks both the positive case and the missing protection. An exact exception or changed state must cause a failure; no broad error is accepted as successful refusal.
Exit ticket
Submit the original handoff, baseline and broken observations, repair, transfer probe and results. State what Lucy would experience before and after the fix. Identify the guarantee that still requires separate evidence: Offline intake proves neither Telegram authentication nor phone delivery.
passed = repair_result is not None and repair_result["status"] == "PASS"
exercise_report = {
"unit": "ch09-b",
"attempted": int(repair_result is not None),
"completed": int(passed),
"failed": int(repair_result is not None and not passed),
"skipped": int(repair_result is None),
"connection": "PASS" if passed else "NOT_READY",
"handoff": handoff_status,
}
print("EXERCISE_REPORT=" + json.dumps(exercise_report, sort_keys=True))Changed-constraint construction: Plan private intake across accounts and replays
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(updates, seen, allowed). Return new [account, update_id] pairs in input order for private messages with exact integer sender/chat IDs, matching sender and chat, sender in allowed, and nonempty text of at most 100 characters. seen contains prior [account, update_id] pairs. Deduplicate within the batch too. Updates have valid account strings and integer update IDs; refuse ineligible messages by omission. Do not mutate inputs.
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.
def transfer_check(updates, seen, allowed):
raise NotImplementedError("Bind private identity before deduplicating intake")import copy
import json
TRANSFER_CASES = [
(
"private",
[
[{"account": "a", "id": 1, "sender": 7, "chat": 7, "kind": "private", "text": "Hello"}],
[],
[7],
],
[["a", 1]],
),
(
"group",
[
[{"account": "a", "id": 1, "sender": 7, "chat": -1, "kind": "group", "text": "Hello"}],
[],
[7],
],
[],
),
(
"already retained",
[
[{"account": "a", "id": 1, "sender": 7, "chat": 7, "kind": "private", "text": "Hello"}],
[["a", 1]],
[7],
],
[],
),
(
"different account",
[
[{"account": "b", "id": 1, "sender": 7, "chat": 7, "kind": "private", "text": "Hello"}],
[["a", 1]],
[7],
],
[["b", 1]],
),
]
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.
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": "ch09-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 / "ch09-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": "ch09-b",
"transfer_passed": TRANSFER_PASSED,
"starting_evidence": course_submission["starting_evidence"],
"edition": "student",
},
sort_keys=True,
)
)Extension: put a language model behind the private channel
Everything above moved bytes from a fixture bot into durable work and, separately, moved a report back out with an honest delivery state. The part in the middle, which turns Lucy's text into a report, was never shown. In production it is a model, and this closing section puts one there without changing anything you built.
The boundary is poll on the way in and deliver_one on the way out. poll admits a message
only when the sender is an allowlisted human, the chat is private, and the chat identity
equals the sender identity; a familiar sender in a group is refused by omission. The model
never sees the bot: it reads the prompt from the work row claim returns, asks for shop
tools through a Dispatcher, and its answer is recorded with finish. deliver_one sends
that row only to the recipient it names, and only while that recipient is allowlisted. No
tool sends, so the model cannot pick a chat, reply twice, or mark anything delivered.
The loop is agent_loop.run_loop from Chapter 3. llm_lab.py supplies ScriptedModel,
which replays turns written in this notebook, and OpenAIModel, which sends the same
messages to a hosted model when a key is present. The record always says which one ran.
Prediction: the next cell polls an unordered batch of three updates: a stranger, Lucy in a group, and Lucy in her private chat. Write down how many work rows are created, what the published cursor will be, and what a second poll after reopening the database returns.
import json
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
from reference_organizations.store.agent import seed_lucy, shop_dispatcher
from sovereign_agent.agent_loop import Limits, run_loop
from sovereign_agent.assistant_work import claim, finish
from sovereign_agent.database import Database
from sovereign_agent.llm_lab import ScriptedModel, describe, scripted_turn, tool_trace
from sovereign_agent.telegram_channel import deliver_one, poll
from sovereign_agent.tool_dispatch import Dispatcher, ExecutableTool
CHANNEL_DB = COURSE_WORK / "ch09-llm-channel.sqlite"
OPERATORS = frozenset({123})
LUCY_TEXT = "Morning. What needs ordering today? Post the list in the staff group as well."
def private_update(identifier, actor, text, chat_type="private"):
"""One Telegram update as the fixture bot returns it. Chat identity equals sender."""
return {
"update_id": identifier,
"message": {
"from": {"id": actor, "is_bot": False},
"chat": {"id": actor, "type": chat_type},
"text": text,
},
}
class FixtureBot:
"""The checkpoint's offline bot: replays every update, records every send, no network."""
account = "teaching"
def __init__(self, updates):
self.updates = updates
self.offsets = []
self.sent = []
self.lose_next_reply = False
def call(self, method, data):
if method == "getUpdates":
self.offsets.append(data["offset"])
return self.updates
self.sent.append(data)
if self.lose_next_reply:
self.lose_next_reply = False
raise TimeoutError("accepted remotely but reply lost")
return {"message_id": 900 + len(self.sent)}
def fresh_channel_database(path):
"""Start from an empty ledger so reruns and replays observe the same rows."""
for stale in (path, Path(f"{path}-wal"), Path(f"{path}-shm"), path.with_suffix(".authority")):
stale.unlink(missing_ok=True)
db = Database(path)
seed_lucy(db)
return db
class LedgerQuery(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
limit: int = Field(default=5, ge=1, le=20)
def build_channel_tools(db, bot):
"""The shop's real tools plus a read-only view of this channel's delivery ledger."""
def delivery_ledger(args: LedgerQuery) -> list[dict[str, Any]]:
rows = db.connection.execute(
"SELECT r.id AS report, w.origin, r.status, r.delivery, r.receipt "
"FROM assistant_reports r JOIN assistant_work w ON w.id=r.work_id "
"WHERE r.channel=? ORDER BY r.id DESC LIMIT ?",
("telegram:" + bot.account, args.limit),
)
return [dict(row) for row in rows]
tools = [
*shop_dispatcher(db).tools.values(),
ExecutableTool(
"delivery_ledger",
"Read the newest reports sent to Lucy on this channel and their delivery state.",
LedgerQuery,
delivery_ledger,
),
]
return Dispatcher(tools, allowed=frozenset(tool.name for tool in tools))
def channel_messages(work):
"""The user turn is the text Lucy typed, read back from the durable work row."""
return [
{
"role": "system",
"content": (
"You help Lucy run her ice cream shop and are answering a message from her "
"phone. Check stock with the tools before drafting anything. A draft is a "
"calculation, not a purchase; draft exactly the quantity the shop needs. Your "
"final answer is the only thing Lucy receives, and the shop delivers it to the "
"private chat her message came from. Finish with a short plain-words summary."
),
},
{"role": "user", "content": work.prompt},
]
channel_db = fresh_channel_database(CHANNEL_DB)
fixture_bot = FixtureBot(
[
private_update(103, 999, "Hi, is this Lucy's shop?"),
private_update(101, 123, LUCY_TEXT, chat_type="group"),
private_update(102, 123, LUCY_TEXT),
]
)
admitted = poll(channel_db, fixture_bot, OPERATORS)
print("Admitted work:", len(admitted))
channel_db.close()
channel_db = Database(CHANNEL_DB)
replayed = poll(channel_db, fixture_bot, OPERATORS)
print("Replayed batch after reopening:", replayed, "| offsets the bot saw:", fixture_bot.offsets)
assert len(admitted) == 1 and replayed == [] and fixture_bot.offsets == [0, 104]
work_rows = channel_db.connection.execute(
"SELECT origin, session, recipient, status FROM assistant_work ORDER BY created"
).fetchall()
for work_row in work_rows:
print(dict(work_row))
assert [dict(row) for row in work_rows] == [
{
"origin": "telegram:teaching:102",
"session": "telegram:teaching:123",
"recipient": "123",
"status": "READY",
}
]
channel_tools = build_channel_tools(channel_db, fixture_bot)
for tool_schema in channel_tools.schemas():
function = tool_schema["function"]
print(function["name"], "requires", function["parameters"].get("required", []))
print(" ", function["description"])Three updates arrived, one work row exists, and the cursor moved past all three: the
stranger and the group message were ineligible, not invalid, so the batch was durable and
the cursor could advance. Replaying it after a restart created nothing, because the origin
telegram:teaching:102 already existed. The schemas are the same model_json_schema()
envelope as Chapter 2; delivery_ledger is new and only reads.
Run the loop against a recorded transcript
The turns below are what a model replied, written down. Turn one asks for stock and for the
delivery ledger, which is empty. Turn two asks for a supplier price and two drafts. Turn
three does what Lucy's message asked and tries to post the list to the staff group with a
tool called send_message. Turn four answers, which ends the loop. The answer is recorded
with finish, and only then does deliver_one run, with the fixture bot set to accept the
send and lose the acknowledgement, the ambiguous case from earlier in this chapter.
Prediction: what does the model see when it calls send_message, and why does the
dispatcher not even look at chat_id? After the lost acknowledgement, what delivery state
does the work row hold, and what does deliver_one return once the database is reopened?
RECORDED_TURNS = [
scripted_turn(
calls=[
{"name": "list_stock", "arguments": {}},
{"name": "delivery_ledger", "arguments": {"limit": 3}},
]
),
scripted_turn(
calls=[
{"name": "supplier", "arguments": {"sku": "SKU-VANILLA"}},
{"name": "draft_order", "arguments": {"sku": "SKU-VANILLA", "quantity": 6}},
{"name": "draft_order", "arguments": {"sku": "SKU-STRAWBERRY", "quantity": 4}},
]
),
scripted_turn(
calls=[
{
"name": "send_message",
"arguments": {"chat_id": 777, "text": "Order list: 6 vanilla, 4 strawberry."},
}
]
),
scripted_turn(
"Drafted 6 vanilla at 250 cents each ($15.00) and 4 strawberry at 275 cents each ($11.00). "
"Chocolate is above its reorder point. Nothing was purchased. I can only reply in "
"this private chat, so the staff group has not been told."
),
]
LOOP_LIMITS = Limits(model_calls=8, tool_calls=16, seconds=120, output_tokens=4096)
scripted_work = claim(channel_db, "phone-worker", identifier=admitted[0])
assert scripted_work is not None and scripted_work.prompt == LUCY_TEXT
scripted_result = run_loop(
ScriptedModel(RECORDED_TURNS),
channel_tools,
channel_messages(scripted_work),
limits=LOOP_LIMITS,
)
print(describe(scripted_result, "scripted"))
scripted_trace = tool_trace(scripted_result)
assert scripted_result.status == "COMPLETED"
assert [step["ok"] for step in scripted_trace] == [True, True, True, True, True, False]
assert scripted_trace[1]["result"] == []
assert scripted_trace[5]["tool"] == "send_message"
assert scripted_trace[5]["result"] == "tool_not_allowed"
assert [step["result"]["total_cents"] for step in scripted_trace[3:5]] == [1500, 1100]
finish(channel_db, scripted_work, "DONE", scripted_result.answer)
fixture_bot.lose_next_reply = True
print("First delivery:", deliver_one(channel_db, fixture_bot, OPERATORS))
assert fixture_bot.sent[-1] == {"chat_id": 123, "text": scripted_result.answer}
channel_db.close()
channel_db = Database(CHANNEL_DB)
channel_tools = build_channel_tools(channel_db, fixture_bot)
print("Delivery after reopening:", deliver_one(channel_db, fixture_bot, OPERATORS))
assert deliver_one(channel_db, fixture_bot, OPERATORS) is None
scripted_delivery = channel_db.connection.execute(
"SELECT delivery FROM assistant_work WHERE id=?", (scripted_work.id,)
).fetchone()[0]
print("Work delivery:", scripted_delivery, "| messages the bot accepted:", len(fixture_bot.sent))
assert scripted_delivery == "UNKNOWN" and len(fixture_bot.sent) == 1
assert channel_db.connection.execute("SELECT count(*) FROM assistant_orders").fetchone()[0] == 0send_message was refused with tool_not_allowed before any argument was read: the
dispatcher checks the name against allowed first, so a tool that does not exist is refused
like one the worker may not use. The report reached the bot once, its receipt was lost, and
the work row says UNKNOWN. Reopening the database did not resend it: deliver_one only
takes PENDING rows, and an ambiguous send is not pending. The message may already be on
Lucy's phone.
Run the same loop against a live model
Lucy sends the message again, because nothing appeared: a new update, a new origin, new
work. build_model looks for an OPENAI_API_KEY in Colab's Secrets pane (the key icon
in the left sidebar: add a secret with that name and switch on notebook access for it), then
in the process environment for a local kernel. Without a key it returns the scripted model
again and the record says so. A missing key is a normal condition, never a silent
substitution.
The live model is gpt-5.1 through the openai library, which Colab ships preinstalled; on
a local kernel run %pip install openai once. One run costs a few thousand tokens. It
receives the same four schemas and system message. It may read the ledger and notice the
UNKNOWN row, or ignore it; what it cannot do is send anything, because no tool sends.
Prediction: write the reply a careful assistant should give Lucy, including what it says about the staff group. Then run the cell and compare the model's answer, or the recorded transcript when the run is scripted, against your reply and the delivery state.
from sovereign_agent.llm_lab import DEFAULT_MODEL, build_model, resolve_api_key
chosen_model = build_model(RECORDED_TURNS, model=DEFAULT_MODEL)
print("Model source:", chosen_model.source, "| key found:", resolve_api_key() is not None)
fixture_bot.updates.append(private_update(104, 123, "Nothing arrived on my phone. " + LUCY_TEXT))
resent = poll(channel_db, fixture_bot, OPERATORS)
assert len(resent) == 1
live_work = claim(channel_db, "phone-worker", identifier=resent[0])
assert live_work is not None
live_result = run_loop(chosen_model, channel_tools, channel_messages(live_work), limits=LOOP_LIMITS)
print(describe(live_result, chosen_model.source))
live_trace = tool_trace(live_result)
finish(
channel_db,
live_work,
"DONE" if live_result.status == "COMPLETED" else "BLOCKED",
live_result.answer,
)
live_delivery = deliver_one(channel_db, fixture_bot, OPERATORS)
print("Live delivery:", live_delivery, "| receipt:", fixture_bot.sent[-1] is not None)
assert live_result.status in {"COMPLETED", "MODEL_CALL_LIMIT", "TOOL_LIMIT", "MODEL_FAILED"}
assert live_delivery == "SENT"
# Whatever the model did, only the runtime sent anything, and only to the allowlisted chat.
assert all(message["chat_id"] in OPERATORS for message in fixture_bot.sent)
assert len(fixture_bot.sent) == 2 and fixture_bot.sent[-1]["text"] == live_result.answer
for step in live_trace:
if step["tool"] not in channel_tools.allowed:
assert step["ok"] is False and step["result"] == "tool_not_allowed", step
sent_events = channel_db.connection.execute(
"SELECT count(*) FROM events WHERE kind='assistant.channel.sent'"
).fetchone()[0]
print("Recorded send receipts:", sent_events)
assert sent_events == 1
assert channel_db.connection.execute("SELECT count(*) FROM assistant_orders").fetchone()[0] == 0Challenge: change the allowlist, then send an invalid batch
Both rules are data. First the allowlist: Lucy hands the phone to a new manager, so the
operator set becomes {456}. Poll one more private message from 123, run the recorded
transcript, record the answer, and call deliver_one with the new allowlist. Predict before
running: is the bot called at all, and what does the work row's delivery say? The recipient
on the row was fixed at intake; the allowlist is checked again at delivery.
Then the batch: replace the fixture's updates with one whose update_id is the string
"106". Earlier, ineligible messages were skipped and the cursor still advanced. Predict
what an invalid update does to the cursor and to the work table, then run it. poll
validates inside the same db.immediate() transaction that publishes the cursor, so a
ValueError rolls both back together.
In your notes, separate what the scripted run proves (intake, deduplication, the cursor, the delivery states, the transcript accounting) from what only a live run can show (the model's judgment about Lucy's request). Offline intake proves neither Telegram authentication nor phone delivery, whichever model ran. The saved record keeps the two apart.
NEW_OPERATORS = frozenset({456})
fixture_bot.updates.append(private_update(105, 123, LUCY_TEXT))
late_ids = poll(channel_db, fixture_bot, OPERATORS)
late_work = claim(channel_db, "phone-worker", identifier=late_ids[0])
assert late_work is not None
late_result = run_loop(
ScriptedModel(RECORDED_TURNS), channel_tools, channel_messages(late_work), limits=LOOP_LIMITS
)
finish(channel_db, late_work, "DONE", late_result.answer)
sends_before = len(fixture_bot.sent)
denied = deliver_one(channel_db, fixture_bot, NEW_OPERATORS)
print("Delivery under new allowlist:", denied, "| bot calls:", len(fixture_bot.sent) - sends_before)
assert denied == "DENIED" and len(fixture_bot.sent) == sends_before
cursor_before = channel_db.connection.execute(
"SELECT offset FROM assistant_channel_cursor WHERE channel='telegram:teaching'"
).fetchone()[0]
work_before = channel_db.connection.execute("SELECT count(*) FROM assistant_work").fetchone()[0]
fixture_bot.updates = [private_update("106", 123, LUCY_TEXT)]
try:
poll(channel_db, fixture_bot, OPERATORS)
invalid_batch = "accepted"
except ValueError as error:
invalid_batch = str(error)
cursor_after = channel_db.connection.execute(
"SELECT offset FROM assistant_channel_cursor WHERE channel='telegram:teaching'"
).fetchone()[0]
work_after = channel_db.connection.execute("SELECT count(*) FROM assistant_work").fetchone()[0]
print("Invalid batch:", invalid_batch, "| cursor", cursor_before, "->", cursor_after)
assert invalid_batch == "invalid update identity"
assert (cursor_before, work_before) == (cursor_after, work_after) == (106, 3)
llm_lab_report = {
"unit": "ch09-b",
"scripted": {
"status": scripted_result.status,
"tool_calls": scripted_result.tool_calls,
"refused": [step["tool"] for step in scripted_trace if not step["ok"]],
"delivery": scripted_delivery,
},
"session": {
"source": chosen_model.source,
"model": DEFAULT_MODEL if chosen_model.source == "live" else None,
"status": live_result.status,
"model_calls": live_result.model_calls,
"tool_calls": live_result.tool_calls,
"refused": [step["tool"] for step in live_trace if not step["ok"]],
"delivery": live_delivery,
"answer": live_result.answer[:400],
},
"changed_allowlist": {"operators": sorted(NEW_OPERATORS), "delivery": denied},
"invalid_batch": {"error": invalid_batch, "cursor": cursor_after, "work_rows": work_after},
}
llm_report_path = COURSE_WORK / "ch09-b-llm-lab-report-v1.json"
llm_report_path.write_text(json.dumps(llm_lab_report, indent=2, sort_keys=True), encoding="utf-8")
print("Saved evidence:", llm_report_path)
print("LLM_LAB_REPORT=" + json.dumps(llm_lab_report["session"], sort_keys=True))
channel_db.close()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.