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: Design · Explain the trade-offs. 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.

Design · Explain the trade-offs

Design switching, old workers and rollback boundaries

Objectives of this level: Implement local epoch switching while distinguishing simulation from distributed guarantees.

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

Design switching, old workers and rollback boundaries

One SQLite transaction installs the state and increments worker_epoch. A subsequent old worker is rejected. A pure running mapping does not allow switching an active executor; unknown outcomes require reconciliation. Local fencing is not cross-host or external-service fencing. Code rollback does not reverse v2 data or refunds.

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
import career_student as student
from career_lab import Runtime, Lease
runtime = Runtime(
    states=[{"snapshot": snapshot, "worker_epoch": 1, "running": False}],
    policies={"A": {"epoch": 1, "enabled": True}}, budgets={"A": 10},
    capacity=2, tenant_limit=1, now=10,
)
try:
    first = student.run_step(runtime, Lease("r1", "A", 1, 20), "migrate")
    old = student.run_step(runtime, Lease("r1", "A", 1, 20), "dispatch")
    assert first == {"status": "migrated", "reason": "schema_v2"}
    assert old == {"status": "blocked", "reason": "worker_fenced"}
    assert runtime.audit()["budgets"] == {"A": 10}
    assert runtime.audit()["ledger"] == [
        {"kind": "migrate", "task_id": "r1", "tenant": "A", "units": 0, "epoch": 2}
    ]
finally:
    runtime.close()

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.

code example

Design switching, old workers and rollback boundaries

One SQLite transaction installs the state and increments worker_epoch. A subsequent old worker is rejected. A pure running mapping does not allow switching an active executor; unknown outcomes require reconciliation. Local fencing is not cross-host or external-service fencing. Code rollback does not reverse v2 data or refunds.

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

Complete run_step; write a migration ADR using old/new leases after migration, stale approval epoch and read-commit worker_change evidence. Explain old executors for active runs and further admission/dual-read/rollback checks.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Does rolling code back restore v1 after v2 is installed?

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.