Understand first
New to this knowledge point
Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.
Start with core principles →Understand → Implement → Debug → Design
Analyze logs, context, execution, credentials, tool discovery and joint releases without mistaking hosted recovery for business exactly-once.
Knowledge content check2026-10-30 · Check the source of the original question2026-10-30
It is recommended to understand first:
Task contracts and independent acceptance checks →Transfer responsibility and permissions during task handoff →Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.
New to this knowledge point
Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.
Start with core principles →Prepare to write the principles into code
Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.
Reading implementation and trade-offs →Need to handle failures and changes in conditions
Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.
Continue to delve deeper into the problem →Need to design or review plans
Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.
Analyze engineering scenarios →LEARN · PRACTICE · REFLECT
First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.
Can be practiced directly. After logging in, answers, favorites, and notes will be saved to your account.
Log in and saveEach modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.
Core concept · Separating state, execution and governance
Preparatory concepts:Task contracts and independent acceptance, Handoff ownership and permission, Idempotency and unknown-outcome boundaries
Separate disposable computation from authoritative facts; constrain actual actions with current authority, stable intent and independent receipts, and evolve model and orchestration together.
The harness rebuilds context from durable records. Optional compute grants no authority; current gateway checks and bound receipts control actual effects. Select the figure to open it at full size.
A session can outlive a context window while workspace bytes disappear; a harness can restart after a merchant write has committed. Recovery is therefore reconciliation through record owners, not one retry button. Dynamic loading, programmatic reads and reusable skills change efficiency and behavior, and must be designed with authority, budgets and release manifests. The course code verifies one narrow window; production choices still need real integration and controlled workload comparisons.
Keep governed events in a session, rebuild lossy context in a replaceable harness, add execution only when needed, enforce current permissions/approval in the business gateway and confirm effects through the merchant ledger. Reconcile original operations rather than replaying writes. Keep real secrets outside generated-code environments. Authorize and budget every dynamic/programmatic call; pin skills/plugins/hooks and instruction precedence. Evaluate model+harness jointly and simplify one mechanism at a time; rollback cannot erase in-flight semantics or business facts.
For tenant A/order o-17, the target is one authorized return request, not a model message saying “done”. Keep the merchant receipt as the authority for that effect. Store intent, transport attempts and observations in an external session log, while a replaceable harness creates a bounded working context. Store durable artifacts independently of an executor's workspace.
A worker replacement reads the log, obtains a new execution epoch, verifies current authority and loads the pinned release. It must reconcile any unknown write under the original operation_id. A new event_id identifies a new observation; a model call_id correlates a model tool exchange; a new attempt_id identifies a transport attempt. None of these replaces the merchant's deduplication identity. The receiving service must enforce whichever epoch or stable-operation contract the design relies on.
A sandbox supplies compute, files and dependencies when the task needs them; a read-only service workflow may need no sandbox. Keep the durable session, rebuild recipe and retained artifact digests outside disposable compute. Keep real credentials in an external vault or application-side signer and expose only bounded operations. Network access and credential injection have different allowlists. A placeholder design does not make local signing possible and does not prevent abuse of an allowed action; current authorization still matters.
Tool search selects definitions, not permission. Programmatic orchestration can batch independent reads and filter large results before context admission, but every dispatched call still needs authorization and pre-dispatch budget accounting. Bound total attempts, concurrency, input/output bytes, active time and artifact size. Do not fan out many writes and then use cancellation as if it could undo them.
As checked on 2026-10-30, OpenAI's guide distinguishes deferred function loading from Agents API MCP discovery. Follow the selected API, rather than copying Responses API configuration into a different runtime. These product mechanisms do not impose this lesson's application event schema.
Record actual archive/content digests, loaded instruction sources and documented precedence. A plugin version label can point at changed bytes unless immutable resolution is enforced. Review hook executables, outbound/tool permissions, deadlines and failure behavior. An async after-action hook cannot block an action already committed. A skill cannot authorize itself, and a model-readable instruction file is not an OS capability boundary. If a permission hook can approve actions in the chosen runtime, it belongs in the trusted policy surface.
Approval binds the exact action, resource, current policy/release interpretation, approver and expiry. Changing a hook, skill or model while waiting requires an explicit compatibility decision; preserving an approval's string ID does not establish preserved meaning.
Compare old-model/old-harness, new-model/old-harness and new-model/simplified-harness on the same task identities, limits and independently checked business outcomes. Predeclare non-negotiable rejection conditions and thresholds for quality, full-task latency and cost; retain unknowns and failures in denominators. Remove a context reset or extra review loop only after an ablation shows its target failure is absent under relevant conditions. Keep independent authority and business checks.
For rollback, route new work to the old release and pin or explicitly migrate in-flight tasks. An already created merchant return remains created. Query original operations before compensation; code rollback is not business reversal.
The supplied program verifies local persistent identities across separate invocations and deterministic receipt reconciliation only. Hosted recovery, real model behavior, hostile-code containment and multi-host correctness remain untested integration work.
Save as harness_architecture_demo.py; run prepare then recover twice. Complete commands, observed outputs and boundaries are in the linked implementation layer. This is a one-host, two-SQLite-file service fixture without a model, network, authorization service or actual sandbox.
Save the following complete source as harness_architecture_demo.py. Use a fresh architecture-work directory and run each command separately. This exact source and these three separate process invocations were verified on 2026-10-30 with Python 3.14.7 and SQLite 3.53.4. The first process intentionally stops normally before receipt logging; this is not a measured crash or network failure.
import json
import sqlite3
import sys
from pathlib import Path
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"))
class SessionLog:
def __init__(self, path):
self.db = sqlite3.connect(path)
self.db.execute("CREATE TABLE IF NOT EXISTS events("
"seq INTEGER PRIMARY KEY AUTOINCREMENT,"
"event_id TEXT UNIQUE NOT NULL,kind TEXT NOT NULL,"
"operation_id TEXT NOT NULL,payload TEXT NOT NULL)")
self.db.commit()
def append(self, event_id, kind, operation_id, payload):
body = canonical(payload)
with self.db:
self.db.execute("BEGIN IMMEDIATE")
old = self.db.execute(
"SELECT kind,operation_id,payload FROM events WHERE event_id=?",
(event_id,)).fetchone()
if old is not None:
if old != (kind, operation_id, body):
raise ValueError("event_identity_conflict")
return "replayed"
self.db.execute(
"INSERT INTO events(event_id,kind,operation_id,payload) VALUES(?,?,?,?)",
(event_id, kind, operation_id, body))
return "committed"
def intents(self):
return self.db.execute(
"SELECT operation_id,payload FROM events WHERE kind='intent' ORDER BY seq"
).fetchall()
def count(self):
return self.db.execute("SELECT COUNT(*) FROM events").fetchone()[0]
class MerchantFixture:
def __init__(self, path):
self.db = sqlite3.connect(path)
self.db.execute("CREATE TABLE IF NOT EXISTS operations("
"operation_id TEXT PRIMARY KEY,payload TEXT NOT NULL,"
"receipt TEXT UNIQUE NOT NULL)")
self.db.commit()
def create(self, operation_id, payload):
body = canonical(payload)
with self.db:
self.db.execute("BEGIN IMMEDIATE")
old = self.db.execute(
"SELECT payload,receipt FROM operations WHERE operation_id=?",
(operation_id,)).fetchone()
if old is not None:
if old[0] != body:
raise ValueError("operation_identity_conflict")
return old[1]
receipt = "r-" + operation_id
self.db.execute("INSERT INTO operations VALUES(?,?,?)",
(operation_id, body, receipt))
return receipt
def lookup(self, operation_id, payload):
row = self.db.execute(
"SELECT payload,receipt FROM operations WHERE operation_id=?",
(operation_id,)).fetchone()
if row is None:
return None
if row[0] != canonical(payload):
raise ValueError("receipt_binding_conflict")
return row[1]
def count(self):
return self.db.execute("SELECT COUNT(*) FROM operations").fetchone()[0]
phase, directory = sys.argv[1:]
root = Path(directory)
root.mkdir(parents=True, exist_ok=True)
if phase == "prepare" and any(root.iterdir()):
raise FileExistsError("use_empty_directory")
session = SessionLog(root / "session.sqlite")
merchant = MerchantFixture(root / "merchant.sqlite")
try:
if phase == "prepare":
payload = {"tenant": "A", "order": "o-17", "quantity": 1}
session.append("intent-17", "intent", "return-17", payload)
merchant.create("return-17", payload)
result = {"phase": "interrupted", "events": session.count(),
"effects": merchant.count()}
# Stop before recording the receipt. A later command is a new process.
elif phase == "recover":
status = "unknown"
outcome = None
for operation_id, body in session.intents():
receipt = merchant.lookup(operation_id, json.loads(body))
if receipt is None:
continue # An empty query alone does not authorize another write.
outcome = session.append("receipt-" + operation_id, "receipt",
operation_id, {"receipt": receipt})
status = "completed"
result = {"phase": status, "append": outcome, "events": session.count(),
"effects": merchant.count()}
else:
raise ValueError("phase")
print(json.dumps(result, sort_keys=True))
finally:
session.db.close()
merchant.db.close()
python3 harness_architecture_demo.py prepare architecture-work
python3 harness_architecture_demo.py recover architecture-work
python3 harness_architecture_demo.py recover architecture-work
Actual observed output, in command order:
{"effects": 1, "events": 1, "phase": "interrupted"}
{"append": "committed", "effects": 1, "events": 2, "phase": "completed"}
{"append": "replayed", "effects": 1, "events": 2, "phase": "completed"}
Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.
Level 1Can a new worker resume from only a compacted summary?
The first changed condition removes worker memory while retaining application state.
A summary is a lossy working view. Load the authoritative session range, artifact references and release binding, and refresh current permissions. A summary may point at these records; it must not replace them or cause historical actions to be blindly re-executed.
Follow this answer further
Level 2The log has an intent but no receipt. Can the worker retry with a new operation ID?
This separates controller recovery from business recovery.
No. Query the original operation and compare its payload binding. A missing log receipt may follow a successful remote commit. A new ID can create a second effect. A retry is permissible only under the service's explicit deduplication/reconciliation contract.
Follow this answer further
Level 3The original-key lookup is empty and the old worker might still arrive. Is the absence conclusive?
This tests a time-of-check/late-arrival window rather than repeating the idempotency slogan.
Not without stronger guarantees. A point-in-time lookup does not rule out a delayed old request or eventually visible receipt. Require receiving-side fencing and an authoritative terminal-absence contract, or retain unknown for reconciliation. Expiring a local lease alone does not establish either.
Level 1A tool was found through search and its plugin is installed. Can it execute?
A larger dynamic catalog must not enlarge authority implicitly.
Discovery makes a definition available, not an action authorized. Validate authenticated principal, current resource policy, exact parameters and required approval at dispatch. Pin the schema/plugin bytes used to interpret the call.
Follow this answer further
Level 2One program now calls the tool 100 times. Does max_turns=1 bound the resource cost?
This moves from model-turn counting to execution accounting.
No. A single model turn can schedule many attempts. Reserve against shared total-attempt, concurrency, time, byte and spending limits before every call; collect and filter results without losing mandatory evidence. Restrict parallel writes by business semantics.
Follow this answer further
Level 3An asynchronous post-tool hook detects an unauthorized write. Has the hard boundary worked?
This asks whether the control runs before or after the irreversible boundary.
No. Detection after an effect is not pre-action refusal. Put authorization in a trusted receiving/gateway boundary. Audit the hook as executable code, document failure/timeout ordering, and reconcile the committed effect. Do not automatically mark it undone or let a hook's name stand for enforcement.
Level 1A newer model seems stronger. Which orchestration should be deleted?
Capability changes require controlled simplification, not permanent scaffolding.
Treat each mechanism as a hypothesis about a failure. Freeze task/policy/resource conditions and compare the new model with the old harness and with one mechanism removed. Preserve independent business gates; remove only what the measured comparison supports.
Follow this answer further
Level 2The simplified harness is cheaper on successful tasks but leaves more unknown operations. Can it pass?
This exposes success-only cost selection.
Not on that evidence. Include failures and unknowns in the task denominator; account for reconciliation and human intervention. Hard unauthorized/duplicate-effect gates cannot be offset by lower mean generation cost.
Follow this answer further
Level 3The canary fails after some merchant writes. What does rollback mean for those tasks?
This connects release management to irreversible external facts.
Stop new assignment to the candidate, preserve each in-flight release and original operation IDs, reconcile receipts, then explicitly migrate or complete under a compatible owner. Route new tasks to the previous release. Never delete merchant rows or assume code rollback reverses the business effect; compensation is another authorized operation.
First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.
Changing conditions:Change from support-service reads to code edits and build artifacts; the authoritative output is now a protected branch and artifact-store record.
Extended question:The session survives but the sandbox is gone. Which work actually survived?
Verify base commit, patch/artifact digests and protected remote records; rebuild the workspace from a pinned recipe. Descriptions do not restore unsaved bytes. Separate safely repeatable read-only builds from PR/publication writes. Keep credentials outside generated-code execution and bind approval to the concrete diff/target version. Session completed is not a build or publication receipt.
The principles that remain unchanged:Reconcile recovery through authoritative records; working context creates neither lost artifacts nor authority.
Changing conditions:The task needs three permitted remote reads and one approved write tool, with no local file or code requirement.
Extended question:Must every session receive a container?
No. A harness can use controlled remote tools directly, avoiding unnecessary provisioning latency and operational surface. Compare sequential/bounded parallel reads and discovery overhead. The write still checks current authority and approval at the business gateway and preserves original-key reconciliation. Add controlled compute only when large-result processing or files require it; no sandbox does not mean no state, authentication or accounting.
The principles that remain unchanged:Choose execution environments from task requirements while preserving business boundaries and evidence.
Official sources checked 2026-10-30; the local SQLite program ran as three separate process invocations. Event envelopes, release gates and ADRs are teaching designs, not vendor guarantees or a completed production deployment. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.
After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.
Run the linked complete program, inspect persistent records and add the three negative controls. Write incident timelines for unknown write, lost artifact and hook change, then a one-page hosted/self-managed and joint-release ADR. Separate executed evidence from proposed design and leave untested integrations pending.