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

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Delivery conditions and shared deadlines for parallel results

Examine asynchronous concurrency, deadlines, cancellation propagation, and partial results.

Learning objectives: Parallelism only shortens independent waiting and does not change task dependencies and success conditions. Global deadlines constrain all attempts and backoffs; the cancellation of a local task does not prove that the remote side effects have stopped, and the results must be retained and classified item by item.

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.

Delivery conditions and shared deadlines for parallel results
Parallelism only shortens independent waiting and does not change task dependencies and success conditions. Global deadlines constrain all attempts and backoffs; the cancellation of a local task does not prove that the remote side effects have stopped, and the results must be retained and classified item by item.

How does the mechanism work?

Step-by-step explanation
  1. What's the problem with calling the synchronous HTTP library in the async function?

    Concurrent execution requires yielding control; function syntax alone does not guarantee this.

  2. Are other tasks still running after aggregation wait encounters an exception?

    Error handling changes the lifecycle of concurrent tasks, so check the library's actual semantics.

  3. Why does the tool retry reusing the remaining time?

    Local retries must obey the global delivery budget.

Implementation · Build it

Implement the contract · Delivery conditions and shared deadlines for parallel results

Objectives of this level: Ability to set concurrency limits, timeouts and per-tool status.

Visual guide · One deadline governs every branch

One deadline governs every branch

Required failures block; optional failures may yield partial. Cleanup must run on exceptions too, and local cancellation proves no remote noncommit. Select the figure to open it at full size.

Implement the independent contract

Implement run_batch(runtime, jobs, deadline) in deadline_student.py. The fixed input is below. Published grader cases also change IDs, values, required flags, absolute times, and the initial clock; there are no undisclosed random questions.

jobs = [
    {"id": "a", "required": True, "complete_at": 1, "outcome": "ok", "value": "evidence-A", "effect_at": None},
    {"id": "b", "required": False, "complete_at": 2, "outcome": "error", "value": None, "effect_at": None},
    {"id": "c", "required": False, "complete_at": None, "outcome": "ok", "value": "never", "effect_at": None},
]
now = 0
deadline = 5

Preserve input order and do not mutate jobs or required. Jobs have unique nonempty IDs, boolean required, integer complete_at at/after the initial clock or None, outcome ok/error, and a fixture effect_at or None. Valid job structure is an input precondition. deadline must be a strict int: bool is invalid. A deadline earlier than runtime.now raises ValueError before any start. Equality is allowed for completions at the current time.

Runtime API: now is logical time; start(id) starts a job and opens a local handle; advance(target) moves time monotonically and processes started jobs; poll(id) returns state/value/error with state pending/succeeded/failed/cancelled; pending_ids() and opened_ids() expose cleanup work; cancel(id) marks only a local pending job; close(id) releases its handle. Start every job in input order at the shared initial time. Every advance uses the same absolute deadline. Early completion is allowed, but results must agree with runtime state. A timeout requires actually reaching the deadline.

Return exactly status, finished_at, results. Every row contains exactly id, state, value, error. Failure error is unavailable; timeout error is deadline; nonsuccess value is None; success error is None. The baseline output at time 5 is:

{
    "status": "partial",
    "finished_at": 5,
    "results": [
        {"id": "a", "state": "succeeded", "value": "evidence-A", "error": None},
        {"id": "b", "state": "failed", "value": None, "error": "unavailable"},
        {"id": "c", "state": "timeout", "value": None, "error": "deadline"},
    ],
}

On every exit cancel pending jobs and close every opened handle. When poll injects LabFault("poll_failure"), clean up and propagate that same exception. Do not convert it into an empty success. cancel is a separate operation from close and does not roll back an external ledger.

Create the scaffold first. Its first grade should exit 1 with 0/12, because the independent function is unfinished. scaffold refuses to overwrite an existing file and exits 2.

python3 deadline_lab.py scaffold --out deadline_student.py
python3 deadline_lab.py grade --module deadline_student.py --out deadline-template-report.json

Scaffold body:

def run_batch(runtime, jobs, deadline):
    """Return status/finished_at/results; preserve input order and required flags.
    Reject non-int/bool or elapsed deadline with ValueError before starting.
    Start all jobs at the current logical time. Complete-at == deadline is allowed.
    On every exit cancel pending jobs and close every opened handle.
    Propagate LabFault unchanged; cleanup must also run on that path.
    """
    raise NotImplementedError("implement run_batch")

After your implementation, submit the report from this command; expect 12/12 and exit 0. Each worker actually imports and calls your module and checks the result, start times, runtime states, pending work, handles, unchanged inputs, and ledger. A five-second worker limit is an infrastructure hang guard, unrelated to the logical deadline or performance.

python3 deadline_lab.py grade --module deadline_student.py --out deadline-report.json

Copyable runtime and grader

This source is identical to the HTTPS resource and can be saved as deadline_lab.py. It provides fixed guided cases, an unfinished scaffold, and a grader; the learner implements the general run_batch.

#!/usr/bin/env python3
"""Logical-time exercise; standard library, Python 3.9+. No HTTP or wall-time benchmark.

Independent API: run_batch(runtime, jobs, deadline) -> batch dict.
This file contains the runtime, an unfinished template, a small guided scenario,
and a grader. It deliberately does not contain the general learner solution.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import subprocess
import sys

# CLI runtime and learner imports share one canonical module and exported types.
if __name__ == "__main__":
    sys.modules["deadline_lab"] = sys.modules[__name__]


class LabFault(RuntimeError):
    pass


class LogicalRuntime:
    def __init__(self, jobs, now=0, fault_id=None):
        self.now = now
        self.jobs = {j["id"]: copy.deepcopy(j) for j in jobs}
        self.states = {}
        self.open_handles = set()
        self.events = []
        self.external_ledger = []
        self.fault_id = fault_id

    def start(self, job_id):
        if job_id in self.states:
            raise ValueError("duplicate_start")
        self.states[job_id] = "pending"
        self.open_handles.add(job_id)
        self.events.append(["start", job_id, self.now])

    def advance(self, target):
        if type(target) is not int or target < self.now:
            raise ValueError("invalid_logical_time")
        self.now = target
        for job_id, state in list(self.states.items()):
            job = self.jobs[job_id]
            at = job["complete_at"]
            if state == "pending" and at is not None and at <= target:
                self.states[job_id] = "succeeded" if job["outcome"] == "ok" else "failed"
                self.events.append(["complete", job_id, at])
        self._external_until(target)
        self.events.append(["advance", target])

    def poll(self, job_id):
        if job_id == self.fault_id:
            self.events.append(["fault", job_id, self.now])
            raise LabFault("poll_failure")
        state = self.states[job_id]
        job = self.jobs[job_id]
        return {"state": state,
                "value": copy.deepcopy(job["value"]) if state == "succeeded" else None,
                "error": "unavailable" if state == "failed" else None}

    def pending_ids(self):
        return [key for key, state in self.states.items() if state == "pending"]

    def opened_ids(self):
        return sorted(self.open_handles)

    def cancel(self, job_id):
        if self.states[job_id] == "pending":
            self.states[job_id] = "cancelled"
            self.events.append(["cancel", job_id, self.now])

    def close(self, job_id):
        self.open_handles.remove(job_id)
        self.events.append(["close", job_id, self.now])

    def _external_until(self, target):
        committed = {row["job_id"] for row in self.external_ledger}
        for job_id in self.states:
            at = self.jobs[job_id].get("effect_at")
            if at is not None and at <= target and job_id not in committed:
                self.external_ledger.append({"job_id": job_id, "committed_at": at})

    def settle_external(self, target):
        """Provider fixture advances independently after local cleanup; never a real service."""
        self._external_until(target)

    def audit(self):
        return {"now": self.now, "states": self.states,
                "open_handles": self.opened_ids(), "events": self.events,
                "external_ledger": self.external_ledger}


BASE = [
    {"id": "a", "required": True, "complete_at": 1, "outcome": "ok", "value": "evidence-A", "effect_at": None},
    {"id": "b", "required": False, "complete_at": 2, "outcome": "error", "value": None, "effect_at": None},
    {"id": "c", "required": False, "complete_at": None, "outcome": "ok", "value": "never", "effect_at": None},
]
TEMPLATE = '''def run_batch(runtime, jobs, deadline):
    """Return status/finished_at/results; preserve input order and required flags.
    Reject non-int/bool or elapsed deadline with ValueError before starting.
    Start all jobs at the current logical time. Complete-at == deadline is allowed.
    On every exit cancel pending jobs and close every opened handle.
    Propagate LabFault unchanged; cleanup must also run on that path.
    """
    raise NotImplementedError("implement run_batch")
'''


def case_data(name):
    jobs = copy.deepcopy(BASE)
    now, deadline, fault_id = 0, 5, None
    if name == "required_failure":
        jobs[1]["required"] = True
    elif name == "required_timeout":
        jobs[2]["required"] = True
    elif name == "all_success":
        for i, job in enumerate(jobs):
            job.update(complete_at=i + 1, outcome="ok", value={"ordinal": i})
    elif name == "at_deadline":
        jobs = [dict(jobs[0], complete_at=5)]
    elif name == "after_deadline":
        jobs = [dict(jobs[0], complete_at=6)]
    elif name == "shifted_clock":
        now, deadline = 4, 9
        jobs[0]["complete_at"], jobs[1]["complete_at"] = 5, 6
    elif name == "changed_input":
        jobs = [dict(jobs[2], id="extra", complete_at=4, value={"revision": 9}),
                dict(jobs[0], id="read-v2", value=["new", 3])]
    elif name == "cancelled_write":
        jobs = [dict(jobs[0], id="write", complete_at=8, effect_at=7)]
    elif name == "poll_fault":
        fault_id = "a"
    elif name == "bool_deadline":
        deadline = True
    elif name == "elapsed_deadline":
        now, deadline = 6, 5
    return jobs, now, deadline, fault_id


CASES = ["partial", "required_failure", "required_timeout", "all_success", "at_deadline",
         "after_deadline", "shifted_clock", "changed_input", "cancelled_write", "poll_fault",
         "bool_deadline", "elapsed_deadline"]


def expected_batch(jobs, deadline):
    rows = []
    for job in jobs:
        if job["complete_at"] is None or job["complete_at"] > deadline:
            state, value, error = "timeout", None, "deadline"
        elif job["outcome"] == "error":
            state, value, error = "failed", None, "unavailable"
        else:
            state, value, error = "succeeded", job["value"], None
        rows.append({"id": job["id"], "state": state, "value": value, "error": error})
    blocked = any(j["required"] and r["state"] != "succeeded" for j, r in zip(jobs, rows))
    status = "blocked" if blocked else ("succeeded" if all(r["state"] == "succeeded" for r in rows) else "partial")
    return status, rows


def load_learner(path):
    spec = importlib.util.spec_from_file_location("learner_under_test", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module.run_batch


def grade_case(path, name):
    jobs, now, deadline, fault_id = case_data(name)
    original = copy.deepcopy(jobs)
    runtime = LogicalRuntime(jobs, now=now, fault_id=fault_id)
    errors = []
    result, caught = None, None
    try:
        result = load_learner(path)(runtime, jobs, deadline)
    except BaseException as exc:
        caught = exc
    invalid = name in ("bool_deadline", "elapsed_deadline")
    if invalid:
        if not isinstance(caught, ValueError) or runtime.events:
            errors.append("invalid_deadline_must_raise_before_actions")
    elif fault_id:
        if type(caught) is not LabFault or str(caught) != "poll_failure":
            errors.append("original_LabFault_must_propagate")
        if not any(e[0] == "fault" for e in runtime.events):
            errors.append("fault_path_was_not_exercised")
    else:
        status, rows = expected_batch(original, deadline)
        expected = {"status": status, "results": rows, "finished_at": runtime.now}
        if caught:
            errors.append("unexpected_exception:" + type(caught).__name__ + ":" + str(caught))
        if result != expected:
            errors.append("result_contract_mismatch")
        if any(j["complete_at"] is None or j["complete_at"] > deadline for j in original) and runtime.now != deadline:
            errors.append("timeout_requires_reaching_shared_deadline")
        expected_states = {r["id"]: "cancelled" if r["state"] == "timeout" else r["state"] for r in rows}
        if runtime.states != expected_states:
            errors.append("report_disagrees_with_runtime")
    if not invalid:
        starts = [e for e in runtime.events if e[0] == "start"]
        if starts != [["start", j["id"], now] for j in original]:
            errors.append("all_jobs_must_start_at_shared_initial_time_in_input_order")
        if runtime.now > deadline:
            errors.append("shared_deadline_exceeded")
        if runtime.pending_ids() or runtime.open_handles:
            errors.append("pending_jobs_or_handles_leaked")
    if jobs != original:
        errors.append("input_was_mutated")
    if name == "cancelled_write":
        runtime.settle_external(10)
        if runtime.external_ledger != [{"job_id": "write", "committed_at": 7}]:
            errors.append("local_cancel_must_not_erase_external_fixture")
    return {"case": name, "pass": not errors, "errors": errors, "result": result,
            "exception": None if caught is None else type(caught).__name__ + ":" + str(caught), "audit": runtime.audit()}


def guided(variant="reference"):
    # A fixed two-job walkthrough; not the general run_batch implementation.
    jobs = [copy.deepcopy(BASE[0]), dict(BASE[2], required=True)]
    rt = LogicalRuntime(jobs)
    rt.start("a")
    rt.start("c")
    rt.advance(5)
    observed = {key: rt.poll(key)["state"] for key in ("a", "c")}
    if variant == "broken":
        reported = "succeeded"  # Deliberate bug: required pending c is ignored; resources leak.
    else:
        reported = "blocked"
        rt.cancel("c")
        rt.close("a")
        rt.close("c")
    checks = {"required_gate": reported == "blocked",
              "cleaned": not rt.pending_ids() and not rt.open_handles,
              "deadline": rt.now == 5, "successful_result_retained": rt.poll("a")["value"] == "evidence-A"}
    return {"scenario": "guided_two_jobs", "time_basis": "integer_logical_time_not_wall_latency",
            "variant": variant, "reported": reported, "observed": observed, "checks": checks,
            "pass": all(checks.values()), "audit": rt.audit()}


def grade(path):
    cases = []
    for name in CASES:
        try:
            run = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--mode", "grade-case",
                                  "--learner", str(Path(path).resolve()), "--case", name],
                                 text=True, capture_output=True, timeout=5)
            row = json.loads(run.stdout.splitlines()[-1])
            row["worker_exit_code"] = run.returncode
            if run.returncode != (0 if row.get("pass") else 1):
                row["pass"] = False
                row["errors"].append("worker_exit_code_mismatch")
        except (subprocess.TimeoutExpired, ValueError, IndexError) as exc:
            row = {"case": name, "pass": False, "errors": ["worker_failed:" + type(exc).__name__]}
        cases.append(row)
    return {"mode": "grade", "time_basis": "integer_logical_time_not_wall_latency",
            "worker_timeout_seconds": 5, "worker_timeout_purpose": "hang_guard_not_performance_gate",
            "python": platform.python_version(), "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "learner_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
            "module_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(), "module_path": str(Path(path).resolve()),
            "passed": sum(c["pass"] for c in cases), "total": len(cases),
            "pass": all(c["pass"] for c in cases), "cases": cases}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("command", nargs="?", choices=["guided", "scaffold", "incident", "explain", "grade"])
    parser.add_argument("--mode", choices=["reference", "template", "debug", "grade", "grade-case"])
    parser.add_argument("--variant", choices=["broken", "repaired"], default="broken")
    parser.add_argument("--learner", "--module", dest="learner")
    parser.add_argument("--case", choices=CASES)
    parser.add_argument("--out")
    args = parser.parse_args()
    modes = {"guided": "reference", "scaffold": "template", "incident": "debug", "explain": "debug", "grade": "grade"}
    if args.command:
        if args.mode:
            parser.error("use a command or --mode, not both")
        args.mode = modes[args.command]
        if args.command == "explain":
            args.variant = "repaired"
    if args.mode is None:
        parser.error("choose guided/scaffold/incident/explain/grade")
    if args.mode == "template":
        if not args.out:
            parser.error("template requires --out")
        path = Path(args.out)
        if path.exists():
            parser.error("refusing to overwrite learner file")
        path.write_text(TEMPLATE, encoding="utf-8")
        result = {"mode": "template", "path": str(path), "pass": True}
    elif args.mode in ("reference", "debug"):
        result = guided("reference" if args.mode == "reference" else args.variant)
    else:
        if not args.learner or (args.mode == "grade-case" and not args.case):
            parser.error("grade requires --learner; grade-case also requires --case")
        result = grade_case(args.learner, args.case) if args.mode == "grade-case" else grade(args.learner)
    output = json.dumps(result, ensure_ascii=False, sort_keys=True)
    if args.out and args.mode != "template":
        Path(args.out).write_text(output + "\n", encoding="utf-8")
    print(output)
    return 0 if result["pass"] else 1


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

Python 3.12 asyncio semantics; lab source.

code example

Grade the actual module

The scaffold raises NotImplementedError and grades 0/12 with exit 1. Your implementation needs 12/12, actual runtime events, and its module SHA.

Acceptance task for this level

Implement run_batch independently; keep the 0/12 scaffold failure, then submit your source, 12/12 report, and module/source SHA.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Does a report claiming open_handles=[] prove cleanup?

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.