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

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Structural and business compatibility during workflow upgrades

Check workflow version, persistence state schema and playback compatibility.

Learning objectives: The old state can be deserialized only for structural compatibility; safe recovery also requires that the new code retains the original steps, approvals, budgets, and tool semantics. Releases require defining version ownership and migration boundaries for outstanding runs.

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

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

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Structural and business compatibility during workflow upgrades
The old state can be deserialized only for structural compatibility; safe recovery also requires that the new code retains the original steps, approvals, budgets, and tool semantics. Releases require defining version ownership and migration boundaries for outstanding runs.

How does the mechanism work?

Step-by-step explanation
  1. What will be the impact of changing the node name?

    Move from state-field compatibility to compatibility of the workflow topology's resume locations.

  2. What should I do if the migration execution is down halfway?

    Migration itself needs recovery and idempotency.

  3. Why is code rollback not equal to state rollback?

    Release rollback involves persisted run data as well as the deployment package.

Implementation · Build it

Implement pure migration and idempotent deep copies

Objectives of this level: Implement migrate_state with strict version/types and preserved business facts.

Visual guide · Migrate semantics, fence old work

Migrate semantics, fence old work

Readable v2 data is not enough for safe resume. The local migration fence does not reverse remote effects or implement cross-host fencing. Select the figure to open it at full size.

Three programming levels in the after-sales Agent

Junior, intermediate and senior describe progressively stronger local contracts. The four course tracks produce different evidence. Passing fixed public checks is not a job-level or hiring certification. Download the ZIP, extract it and enter agent-career-levels-v1; career_lab.py and career-cases.json must remain together. Python 3.9+, standard library only. Implement progressively in one career_student.py; scaffold refuses overwrites. Regress all three levels after senior changes.

  • https://ai.lwkjob.com/lab/career-levels/README.md
  • https://ai.lwkjob.com/lab/career-levels/career_lab.py
  • https://ai.lwkjob.com/lab/career-levels/career-cases.json
  • https://ai.lwkjob.com/downloads/agent-career-levels-v1.zip
python3 career_lab.py scaffold --out career_student.py
python3 career_lab.py grade --module career_student.py --level junior --out report-junior.json
python3 career_lab.py grade --module career_student.py --level intermediate --out report-intermediate.json
python3 career_lab.py grade --module career_student.py --level senior --out report-senior.json

Implement pure migration and idempotent deep copies

v2 requires a migration record and validated fields, not schema++. Valid repeated migration deep-copies the state. unsupported_schema differs from input_shape. Runtime fixtures are valid; arbitrary malformed stored runtime state is outside scope.

snapshot = {
    "schema": 1, "id": "r1", "tenant": "A", "status": "waiting",
    "approval": {"tenant": "A", "epoch": 1, "decision": "approved"},
    "budget_used": 2, "operation_key": None,
    "extensions": {"units": 3, "redacted_note": "keep", "nested": {"known": False}},
}
# expected schema=2, status="ready", migration={"from_schema":1,"to_schema":2}
# all other fields unchanged; epoch remains 1, budget_used remains 2
def validate_task(task, principal):
    raise NotImplementedError

def plan_round(tasks, budgets, cursor, slots):
    raise NotImplementedError

def migrate_state(snapshot):
    raise NotImplementedError

def run_step(runtime, lease, action):
    raise NotImplementedError

Worked difficulty: change state meaning without rewriting facts

Visual guide · r1: schema changes, approval and budget facts survive

r1: schema changes, approval and budget facts survive

Authored mapping of one valid career fixture; Runtime.commit was actually called with units=0 and rejected the old epoch afterward. This is separate from capstone SQL migration 002. Source: worked-probes.json migration. Select the figure to open it at full size.

Use r1 above to distinguish a state interpretation from a new business fact. The fixed probe deep-copies that valid input, authors its expected mapping, and actually calls career_lab.Runtime.commit. It does not execute a learner's migrate_state or run_step and does not certify the full validation contract.

Field schema 1 → schema 2 Business reason
schema / migration 1 → 2; add from_schema=1,to_schema=2 records this interpretation change
status waiting → ready because decision=approved old waiting was ambiguous
approval tenant=A,epoch=1,decision=approved unchanged migration cannot renew authority
budget_used 2 → 2 past consumption must survive
operation_key None → None for this waiting fixture do not invent an external operation
id / tenant / extensions same r1/A/values; fresh nested containers preserve identity and extension meaning

Other public mapping branches are waiting+pending→awaiting_approval, waiting+denied→blocked, unknown→reconcile_required with its nonempty original operation_key. running and completed retain their labels. These branches are specified contract examples, not extra measured outcomes in this probe. A structurally valid status does not authorize a side effect; dispatch still checks current policy and approval epoch.

Trace the actual storage boundary in worked-probes.json: before worker_epoch=1, budget A=10; commit receives units=0, writes the mapped snapshot and one migrate ledger row, and advances worker_epoch to 2. Historical approval.epoch stays 1 and budget_used stays 2. An old epoch=1 commit is rejected as worker_fenced, with unchanged budget and ledger. This probes the supplied storage API directly; the exercise remains to implement guarded orchestration and input/deep-copy validation in personal source.

Keep version namespaces separate. The capstone SQL 002 adds events_by_task, tasks_by_owner and release_meta; it does not perform the career status mapping or rename task fields. The debugging example below executes that separate SQL upgrade and checkpoint restore. Neither example establishes mixed-version multi-host rolling compatibility.

Independent contracts and authority

JSON arguments and Lease are immutable. run_step may change the supplied runtime only through runtime.commit. Pure-function results must not share dict/list containers with their arguments. JSON types are exact: True is not integer 1. Exception class and message are exact. principal and runtime policy are trusted server facts supplied by the exercise. A submitted task, historical approval or model text cannot grant authority. Import only learner modules you trust; a subprocess hang guard is not a hostile-code sandbox.

validate_task(task, principal): task has exactly id, tenant, units; the first two are nonempty str; units is strict int in 1..100. principal has exactly nonempty str tenant and strict bool enabled. Validate every shape first: ValueError("input_shape"). Then tenant mismatch: PermissionError("tenant_mismatch"). Then disabled: PermissionError("tenant_disabled"). Success returns a deep copy of task. Self-reported enabled fields cannot grant authority.

plan_round(tasks, budgets, cursor, slots): tasks is a list of the above task records with unique IDs; budgets maps nonempty str tenants to strict nonnegative int, and may be empty; cursor is None or nonempty str; slots is strict nonnegative int. Any malformed input raises ValueError("input_shape"). Do not schedule tenants absent from budgets or borrow another tenant's budget. Sort tenant names lexically, start immediately after cursor and wrap. Choose one affordable tenant head, debit planned remaining units, then continue after that selected tenant. Preserve FIFO within each tenant: an unaffordable head blocks its cheap tail. Stop at slots or when no head is affordable. Return exactly selected (ID list), cursor (last selected tenant, unchanged if none), remaining (planned budgets). This is request round-robin with integer estimated cost, not elapsed-time fairness, real token settlement or production quotas.

migrate_state(snapshot): v1 has exactly schema/id/tenant/status/approval/budget_used/operation_key/extensions. schema is strict int; unsupported values other than 1/2 raise ValueError("unsupported_schema"); other shape failures raise ValueError("input_shape"). id/tenant are nonempty str; budget_used is strict nonnegative int; operation_key is None or nonempty str; extensions is a JSON dict preserved through deep copy. approval has exactly matching tenant, strict positive int epoch, and decision pending/approved/denied. v1 statuses are waiting/running/unknown/completed. Map waiting to awaiting_approval/ready/blocked respectively; unknown to reconcile_required; preserve running/completed. unknown/reconcile_required requires operation_key. v2 adds migration={"from_schema":1,"to_schema":2} with strict integers and allows the new statuses plus running/completed. Valid v2 returns unchanged through deep copy. Preserve approval epoch, consumed budget, business key and extensions. Migration creates no business side effect.

run_step(runtime, lease, action): import career_lab.Lease and CommitConflict; legal dataclass/future annotations and canonical exception identity are supported. Check action first: only dispatch/migrate, otherwise ValueError("action"). Require a Lease instance with nonempty str task_id/tenant, strict positive int worker_epoch and strict nonnegative int expires_at, otherwise ValueError("lease_shape"). Both checks precede read. runtime.read(task_id) raises ValueError("unknown_task") for a missing task. Then reject in order: tenant mismatch→tenant_mismatch; expires_at<=now→lease_expired; worker_epoch mismatch→worker_fenced; current disabled policy→tenant_disabled. A rejection returns exactly {"status":"blocked","reason":reason} without commit.

For migrate, reject view.running as running_requires_old_executor; v2 returns {"status":"unchanged","reason":"already_v2"}; otherwise call your migrate_state, units=0, success migrated/schema_v2. For dispatch require schema2/status ready, otherwise ready_required; approval must be approved with epoch equal to current policy epoch, otherwise approval_stale. Then test global_running>=capacity, tenant_running>=tenant_limit, extensions.units>budget_remaining in that order, returning backpressure/tenant_limit/budget_exhausted. Valid dispatch deep-copies the snapshot, changes status to running, and reserves extensions.units. Both committing paths call runtime.commit(lease, view["policy"]["epoch"], updated, units). Catch canonical CommitConflict and return blocked/str(exc). Dispatch success is started/reserved. Runtime initial snapshots and extensions.units in these fixtures are valid; malformed stored runtime state beyond missing tasks is outside this exercise's contract.

runtime.read returns snapshot, worker_epoch, running, now, policy, global_running, tenant_running, capacity, tenant_limit, budget_remaining. Runtime.commit rechecks tenant, lease, worker epoch, current authority and resources in one SQLite transaction before updating state/budget/ledger. Every successful commit increments worker_epoch. environment_hook injects revocation, worker replacement or zero capacity between read and commit; it is deterministic simulation, not measured cross-host concurrency. Do not write runtime.db directly, change capacity, call external_write or bypass commit.

Evidence and limits

There are 14 junior, 17 intermediate and 41 senior public checks, 72 total. grade imports and calls the learner's functions, records each input/expected/actual/error, audited state, learner/source/cases SHA and Python version. Exit0 means all selected contracts pass; exit1 is failure; missing CLI arguments or scaffold overwrite exit2. Exceptions and invalid return types fail, including SystemExit/KeyboardInterrupt during import or calls. The parent binds the complete packet to the current case, actual values/ledger and process exit; a claimed passed flag is insufficient. The five-second limit only detects hung workers, not latency. Changed inputs and negative cases are public, not hidden tests or unseen transfer.

This is one process with in-memory SQLite and an integer logical clock. Budgets/capacity are teaching assumptions. A reserve ledger entry is local reservation, not a completed external refund. Completion settlement, resource release, remote cancellation, multi-host shared leases and production capacity measurements are not implemented. Local cancellation/release cannot undo an unknown external write; a real system needs receipt reconciliation and a preserved operation_key. Pure migration maps running structurally; run_step retains the old executor and refuses switching it. Recovery/rollback, dual-read windows and distributed fencing need separate validation. Green fixed checks cannot be reported as production experience or real model quality.

Submit your source, first failed report, personal diff, rerun report and a 300-word tradeoff note, disclosing assistance. Published expected outputs make the contract reviewable; they are not proof of independent authorship. Sources: Python sqlite3, Python importlib. Actual behavior is defined by this source and its public inputs.

Provided storage/loader/grader source · 提供的存储、导入器与验收源码

#!/usr/bin/env python3
"""Python 3.9+ authored local career exercises; no model/provider/business service.
Public cases are reproducible contracts, not unseen tests or career certification.
Only import learner modules you trust: this program is not a security sandbox.
"""
import argparse
import copy
from dataclasses import dataclass
import hashlib
import importlib.util
import json
from pathlib import Path
import sqlite3
import subprocess
import sys

if __name__ == "__main__":
    sys.modules["career_lab"] = sys.modules[__name__]
CASES = Path(__file__).with_name("career-cases.json")
VERSION = "career-lab-v1"


@dataclass(frozen=True)
class Lease:
    task_id: str
    tenant: str
    worker_epoch: int
    expires_at: int


class CommitConflict(RuntimeError):
    pass


class Runtime:
    """One SQLite database, integer logical clock, deterministic interleaving hooks.
    commit is the guarded atomic storage API, not a learner orchestration solution.
    A reserve is LOCAL capacity/budget state; it is not an external write receipt.
    """
    def __init__(self, states, policies, budgets, capacity=2, tenant_limit=1, now=10, hook=None):
        self.db = sqlite3.connect(":memory:")
        self.db.executescript("CREATE TABLE runs(id TEXT PRIMARY KEY,tenant TEXT,epoch INTEGER,state TEXT,running INTEGER);"
                              "CREATE TABLE policy(tenant TEXT PRIMARY KEY,epoch INTEGER,enabled INTEGER);"
                              "CREATE TABLE budget(tenant TEXT PRIMARY KEY,remaining INTEGER);"
                              "CREATE TABLE ledger(kind TEXT,task_id TEXT,tenant TEXT,units INTEGER,epoch INTEGER);")
        for row in states:
            s = row["snapshot"]
            self.db.execute("INSERT INTO runs VALUES(?,?,?,?,?)", (s["id"],s["tenant"],row["worker_epoch"],json.dumps(s),int(row["running"])))
        for tenant,p in policies.items():
            self.db.execute("INSERT INTO policy VALUES(?,?,?)", (tenant,p["epoch"],int(p["enabled"])))
        self.db.executemany("INSERT INTO budget VALUES(?,?)", list(budgets.items()))
        self.db.commit()
        self.capacity,self.tenant_limit,self.now,self.hook = capacity,tenant_limit,now,hook
        self.events = []

    def read(self, task_id):
        self.events.append(["read",task_id])
        row = self.db.execute("SELECT tenant,epoch,state,running FROM runs WHERE id=?",(task_id,)).fetchone()
        if row is None:
            raise ValueError("unknown_task")
        tenant,epoch,state,running = row
        policy = self.db.execute("SELECT epoch,enabled FROM policy WHERE tenant=?",(tenant,)).fetchone()
        budget = self.db.execute("SELECT remaining FROM budget WHERE tenant=?",(tenant,)).fetchone()
        return {"snapshot":json.loads(state),"worker_epoch":epoch,"running":bool(running),"now":self.now,
                "policy":{"epoch":policy[0],"enabled":bool(policy[1])},
                "global_running":self.db.execute("SELECT SUM(running) FROM runs").fetchone()[0],
                "tenant_running":self.db.execute("SELECT SUM(running) FROM runs WHERE tenant=?",(tenant,)).fetchone()[0],
                "capacity":self.capacity,"tenant_limit":self.tenant_limit,"budget_remaining":budget[0]}

    def commit(self, lease, expected_policy_epoch, snapshot, units=0):
        """Atomically guard authority/revision/capacity and install caller's state.
        The caller supplies the state transition and handles any conflict.
        """
        self.events.append(["commit_attempt",lease.task_id,units])
        if self.hook:
            if self.hook == "revoke":
                self.db.execute("UPDATE policy SET epoch=epoch+1,enabled=0 WHERE tenant=?",(lease.tenant,))
            elif self.hook == "worker_change":
                self.db.execute("UPDATE runs SET epoch=epoch+1 WHERE id=?",(lease.task_id,))
            elif self.hook == "capacity_zero":
                self.capacity = 0
            self.db.commit()
            self.events.append(["environment_hook",self.hook])
            self.hook = None
        self.db.execute("BEGIN IMMEDIATE")
        try:
            row = self.db.execute("SELECT tenant,epoch,state FROM runs WHERE id=?",(lease.task_id,)).fetchone()
            policy = self.db.execute("SELECT epoch,enabled FROM policy WHERE tenant=?",(row[0],)).fetchone()
            def reject(reason):
                raise CommitConflict(reason)
            if row[0] != lease.tenant or snapshot["tenant"] != row[0]: reject("tenant_mismatch")
            if lease.expires_at <= self.now: reject("lease_expired")
            if row[1] != lease.worker_epoch: reject("worker_fenced")
            if policy[0] != expected_policy_epoch or not policy[1]: reject("authority_changed")
            if type(units) is not int or units < 0: reject("invalid_units")
            if units:
                used = self.db.execute("SELECT SUM(running) FROM runs").fetchone()[0]
                tenant_used = self.db.execute("SELECT SUM(running) FROM runs WHERE tenant=?",(row[0],)).fetchone()[0]
                budget = self.db.execute("SELECT remaining FROM budget WHERE tenant=?",(row[0],)).fetchone()[0]
                if used >= self.capacity: reject("backpressure")
                if tenant_used >= self.tenant_limit: reject("tenant_limit")
                if budget < units: reject("budget_exhausted")
                self.db.execute("UPDATE budget SET remaining=remaining-? WHERE tenant=?",(units,row[0]))
            epoch = row[1]+1
            self.db.execute("UPDATE runs SET epoch=?,state=?,running=? WHERE id=?",(epoch,json.dumps(snapshot),int(bool(units)),lease.task_id))
            self.db.execute("INSERT INTO ledger VALUES(?,?,?,?,?)",("reserve" if units else "migrate",lease.task_id,row[0],units,epoch))
            self.db.commit()
            return epoch
        except BaseException:
            self.db.rollback()
            raise

    def external_write(self, task_id):
        """Forbidden simulated effect; no real external request occurs."""
        self.db.execute("INSERT INTO ledger VALUES('external_write',?,'unknown',0,0)",(task_id,))
        self.db.commit()
        self.events.append(["external_write",task_id])

    def audit(self):
        return {"runs":[{"id":i,"tenant":t,"worker_epoch":e,"snapshot":json.loads(s),"running":bool(r)} for i,t,e,s,r in self.db.execute("SELECT * FROM runs ORDER BY id")],
                "budgets":dict(self.db.execute("SELECT * FROM budget ORDER BY tenant")),
                "ledger":[dict(zip(["kind","task_id","tenant","units","epoch"],r)) for r in self.db.execute("SELECT * FROM ledger")],
                "policies":{t:{"epoch":e,"enabled":bool(v)} for t,e,v in self.db.execute("SELECT * FROM policy ORDER BY tenant")},
                "events":copy.deepcopy(self.events),"capacity":self.capacity}

    def close(self):
        self.db.close()


TEMPLATE = '''"""Implement progressively. Cases are public; disclose any assistance used."""
def validate_task(task, principal):
    raise NotImplementedError("junior contract")

def plan_round(tasks, budgets, cursor, slots):
    raise NotImplementedError("intermediate contract")

def migrate_state(snapshot):
    raise NotImplementedError("senior pure migration contract")

def run_step(runtime, lease, action):
    raise NotImplementedError("senior guarded orchestration contract")
'''


def load_module(path):
    spec = importlib.util.spec_from_file_location("career_student",path)
    if spec is None or spec.loader is None:
        raise ValueError("module_path")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def exact(a, b):
    """Compare both JSON values and their exact types."""
    if type(a) is not type(b):return False
    if type(a) is dict:return set(a)==set(b) and all(exact(a[k],b[k]) for k in a)
    if type(a) is list:return len(a)==len(b) and all(exact(x,y) for x,y in zip(a,b))
    return a==b


def case_fields(case):
    return {"name":case["name"],"function":case["function"],"input":copy.deepcopy(case["args"]),
            "runtime_input":copy.deepcopy(case.get("runtime")),"expected":copy.deepcopy(case.get("expected")),
            "expected_error":case.get("error"),"expected_audit":copy.deepcopy(case.get("audit"))}


def result_passes(case, row):
    """Recompute contract success from measured values, not a claimed passed flag."""
    if row["controlled_failure"]:return False
    if not all(row[k] for k in ("arguments_unchanged","result_alias_free","return_json_valid")):return False
    if not exact(row["error"],case.get("error")):return False
    if "error" not in case and not exact(row["actual"],case["expected"]):return False
    if not exact(row["audit"],case.get("audit")):return False
    if row["audit"] and any(item["kind"]=="external_write" for item in row["audit"]["ledger"]):return False
    return True


def validate_worker_report(case, row, returncode):
    """Bind a complete child packet to this case and its real process exit.
    This prevents accidental/spurious stdout from becoming a grading result.
    It does not turn trusted learner execution into a hostile-code sandbox.
    """
    fields=case_fields(case)
    required=set(fields)|{"passed","actual","error","audit","arguments_unchanged",
                          "result_alias_free","return_json_valid","controlled_failure"}
    if type(row) is not dict or set(row)!=required:raise ValueError("worker_packet_shape")
    if any(not exact(row[k],v) for k,v in fields.items()):raise ValueError("worker_packet_case")
    if any(type(row[k]) is not bool for k in ("passed","arguments_unchanged","result_alias_free","return_json_valid","controlled_failure")):
        raise ValueError("worker_packet_types")
    if row["error"] is not None and type(row["error"]) is not str:raise ValueError("worker_packet_error")
    try:
        json.dumps(row,allow_nan=False)
        passed=result_passes(case,row)
    except (TypeError,ValueError,KeyError,RecursionError):raise ValueError("worker_packet_values")
    if row["passed"]!=passed:raise ValueError("worker_packet_claim")
    if type(returncode) is not int or returncode!=(0 if passed else 1):raise ValueError("worker_packet_exit")
    return passed


def one_case(path, case):
    arguments=copy.deepcopy(case["args"])
    before=copy.deepcopy(arguments)
    rt=None
    actual,error,controlled_failure=None,None,False
    module_loaded=False
    try:
        module=load_module(path)
        module_loaded=True
        if case["function"]=="run_step":
            rt=Runtime(**case["runtime"])
            actual=[]
            for call in arguments:
                actual.append(module.run_step(rt,Lease(**call["lease"]),call["action"]))
        else:
            actual=getattr(module,case["function"])(*arguments)
    except BaseException as exc:
        error=type(exc).__name__+":"+str(exc)
        # SystemExit/KeyboardInterrupt are failures, never successful case exits.
        controlled_failure=not module_loaded or not isinstance(exc,Exception)
    audit=rt.audit() if rt else None
    if rt:rt.close()
    def containers(value):
        ids=set()
        if type(value) in (dict,list):
            ids.add(id(value))
            for child in (value.values() if type(value) is dict else value):ids.update(containers(child))
        return ids
    def json_values(value):
        if type(value) is dict:return all(type(k) is str and json_values(v) for k,v in value.items())
        if type(value) is list:return all(json_values(v) for v in value)
        return type(value) in (str,int,float,bool,type(None))
    try:
        arguments_unchanged=exact(arguments,before)
        result_alias_free=not bool(containers(actual)&containers(arguments))
    except RecursionError:arguments_unchanged,result_alias_free=False,False
    try:
        return_json_valid=json_values(actual)
        json.dumps(actual,allow_nan=False)
    except (ValueError,TypeError,RecursionError):return_json_valid=False
    if not return_json_valid:actual={"invalid_return_type":type(actual).__name__}
    row=case_fields(case)
    row.update(actual=actual,error=error,audit=audit,arguments_unchanged=arguments_unchanged,
               result_alias_free=result_alias_free,return_json_valid=return_json_valid,controlled_failure=controlled_failure)
    row["passed"]=result_passes(case,row)
    return row


def grade(path, level):
    data=json.loads(CASES.read_text())
    selected=[c for c in data["checks"] if c["level"]==level]
    rows=[]
    for index,case in enumerate(data["checks"]):
        if case["level"]!=level:continue
        r=None
        try:
            r=subprocess.run([sys.executable,str(Path(__file__).resolve()),"_case","--module",str(Path(path).resolve()),"--index",str(index)],text=True,capture_output=True,timeout=5)
            row=json.loads(r.stdout.splitlines()[-1])
            validate_worker_report(case,row,r.returncode)
        except (ValueError,IndexError,TypeError,KeyError,OSError,subprocess.TimeoutExpired) as exc:
            row=case_fields(case)
            row.update(actual=None,error=None,audit=None,passed=False,arguments_unchanged=False,result_alias_free=False,return_json_valid=False,controlled_failure=True,
                       worker_error=type(exc).__name__+":"+str(exc),worker_stderr=r.stderr[-1000:] if r else str(exc)[-1000:],worker_returncode=r.returncode if r else None)
        rows.append(row)
    return {"source":"public_fixed_local_contracts","version":VERSION,"level":level,"passed":bool(selected) and bool(rows) and all(r["passed"] for r in rows),"no_cases":not bool(selected),
            "passed_checks":sum(r["passed"] for r in rows),"total_checks":len(selected),"checks":rows,
            "student_sha256":hashlib.sha256(Path(path).read_bytes()).hexdigest(),"source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "cases_sha256":hashlib.sha256(CASES.read_bytes()).hexdigest(),"python":sys.version,
            "limits":"local SQLite/logical-time fixtures; no provider/production/hidden-test/role certification; 5s worker hang guard is not a latency gate"}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command",choices=["scaffold","grade","_case"])
    parser.add_argument("--out")
    parser.add_argument("--module")
    parser.add_argument("--level",choices=["junior","intermediate","senior"])
    parser.add_argument("--index",type=int)
    args=parser.parse_args()
    if args.command=="scaffold":
        if not args.out:parser.error("scaffold requires --out")
        try:
            with Path(args.out).open('x') as handle:handle.write(TEMPLATE)
        except FileExistsError:parser.error("refusing to overwrite learner module")
        print(json.dumps({"created":args.out,"source":"unimplemented_scaffold"}));return 0
    if not args.module:parser.error("requires --module")
    if args.command=="_case":
        result=one_case(args.module,json.loads(CASES.read_text())["checks"][args.index])
        print(json.dumps(result,sort_keys=True));return 0 if result["passed"] else 1
    if not args.level or not args.out:parser.error("grade requires --level and --out")
    result=grade(args.module,args.level)
    Path(args.out).write_text(json.dumps(result,sort_keys=True,indent=2)+'\n')
    print(json.dumps({k:v for k,v in result.items() if k!='checks'},sort_keys=True))
    return 0 if result["passed"] else 1


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

Run the resource boundary with real worker processes

Use the multiprocess project extension and source ZIP after the seven-stage baseline. It connects actual Agent preparation and approved return execution to shared admission, tenant/global limits, reservation settlement, worker epochs and original-key receipt reconciliation. Inspect distinct worker PIDs, persisted state and merchant HTTP before claiming a boundary passed. The merchant and runtime use separate processes/connections to one local SQLite file; this is a declared shared-storage experiment. Synthetic work units and local measured execution windows are not provider tokens, production quotas or the route's hypothetical 300/1200 tasks/minute. The supplied implementation is a reference; complete the separate learner hook, red baseline, personal diff and regression. Use ADR_GUIDE.md for alternatives, failure windows and migration/rollback proposals, labeling unexecuted proposals planned.

Continue in one runnable project: migrate the unresolved return

In Harness Journey, a merchant has committed while its worker has crashed. The recovery walkthrough upgrades the same persisted workflow before a replacement worker reconciles it. Preserve the business operation key, approval binding and consumed units; map unknown into reconciliation rather than a new write. Workflow schema is distinct from SQL schema and source release.

Run python3 -B journey.py scenario --name migration_rollback --work /tmp/journey-migration and compare before/after storage, including an aborted transaction. A successful migration must fence stale writers, avoid another reservation and preserve the original merchant history. Get the complete package to run both the rollback probe and the same-task recovery.

Continue the connected project article and inspect the executable entrypoint.

code example

Implement pure migration and idempotent deep copies

v2 requires a migration record and validated fields, not schema++. Valid repeated migration deep-copies the state. unsupported_schema differs from input_shape. Runtime fixtures are valid; arbitrary malformed stored runtime state is outside scope.

snapshot = {
    "schema": 1, "id": "r1", "tenant": "A", "status": "waiting",
    "approval": {"tenant": "A", "epoch": 1, "decision": "approved"},
    "budget_used": 2, "operation_key": None,
    "extensions": {"units": 3, "redacted_note": "keep", "nested": {"known": False}},
}
# expected schema=2, status="ready", migration={"from_schema":1,"to_schema":2}
# all other fields unchanged; epoch remains 1, budget_used remains 2

Acceptance task for this level

Implement migrate_state; inspect waiting-approved, old-unknown, v2-idempotent and migration-bool. Complete run_step and generate the senior report, recording preserved fields.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why validate fields even when schema is already v2?

Further explanations and practice

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

All linked explanations and exercises (1 )

Sources and verification scope

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