MODULE 03.4 · PUBLISHED · ~4h

Loop Budgets, Checkpoints & Graceful Failure

Bound multi-step agent loops with strict step and token budgets, detect repeated tool-call cycles, compact growing message history, and return safe fallback diagnostics in fde-03-4 with pytest and GitHub Actions.

Even well-scoped multi-step workflows can stall, repeat identical tool calls, blow past token budgets, or overflow context windows when upstream APIs return noisy or partial data. Without hard runtime bounds, a single stuck run can burn disproportionate spend and leave users with an opaque crash.

In this module, you will build a bounded multi-step execution loop with step, token, and timeout budgets, deterministic cycle detection, context compaction, per-step checkpoints, and graceful fallback diagnostics, with a local pytest suite and a GitHub Actions workflow in fde-03-4.

Enterprise Scenario: Northwind Freight

Northwind’s exception-triage assistant gathers carrier tracking events, customs hold codes, and warehouse scans across multiple tools before summarizing an action plan for operators. When a carrier API returns repetitive responses or large raw manifests, the runner must compact older observations, cap retained tool-output size, stop duplicate tool loops early, and return a clear partial diagnostic summary rather than timing out silently.

What You Will Build

  • Loop budget, step trace, and fallback schemas: Define strict Pydantic v2 models for LoopBudget (including max_observation_chars), PlannedStep action-shape validation, ToolStepRecord, and BoundedLoopResult with extra="forbid", strict=True, boolean-int rejection, and non-blank text validation.
  • Cycle detection and context compaction: Validate JSON-compatible tool arguments, including circular-reference and nesting checks; detect repeated tool-and-argument calls; compact older observations when history exceeds its character budget while preserving the original goal and newest useful steps; and cap each retained tool observation.
  • Checkpointed bounded runner + CI: Enforce step and estimated planner-token ceilings; check elapsed-time deadlines before planner and tool calls, immediately before tool execution, and after checkpoint persistence; record per-step checkpoints through an optional persistence callback; handle failures gracefully; and verify termination modes with pytest and GitHub Actions.

1. Bounding Multi-Step Execution

  • Multi-dimensional loop budgets: Relying on a single step counter is rarely enough because one step can return a massive payload or stall on slow I/O. Combine max_steps, estimated planner-token usage, and max_elapsed_ms so whichever ceiling is detected first stops the run cleanly. Token usage here is an estimate supplied by the planner, not provider-reported total token accounting.
  • Deterministic cycle detection: Canonicalize each planned (tool_name, arguments) call and check whether that exact pair has already been executed anywhere in the current run. The first execution is allowed; a second identical tool-and-arguments pair stops the run, even if another tool call occurred between them. This conservative policy prevents repeated side effects and retry loops, but it can also block legitimate workflows that intentionally need the same operation more than once. If your use case needs that behavior, define an explicit repeat policy (for example, include a meaningful page, cursor, attempt, or idempotency key in the arguments, or use a bounded per-call repeat allowance) rather than silently disabling cycle protection.
  • Context compaction with anchor preservation: Raw tool responses accumulate rapidly across steps. When history exceeds max_context_chars, retain the initial task prompt and the most recent useful observations within the character limit while replacing omitted older observations with a compact count marker. The planner receives this bounded context and a step count, not the unbounded checkpoint list. Each stored observation is also capped by max_observation_chars; this bounds retained data, not the raw response already received from the tool.
  • Graceful fallback over unhandled exceptions: When a budget ceiling, cycle, planner/tool exception, or checkpoint persistence error stops execution early, return a structured BoundedLoopResult with status="stopped_gracefully", the specific termination_reason, completed in-memory checkpoints, and an actionable fallback summary instead of discarding partial progress.

Termination Modes and Fallback Behavior

Termination reasonTrigger conditionFallback output
completedPlanner signals final answer within all budgetsFinal synthesized summary + full step checkpoints
max_steps_exceededNext step would exceed max_stepsGraceful summary of findings gathered up to the step cap
token_budget_exceededCumulative tokens reach or exceed max_total_tokensGraceful summary + token usage breakdown
timeout_exceededA deadline check before planner/tool calls, immediately before tool execution, or after a synchronous call/checkpoint callback detects elapsed time at or above max_elapsed_msGraceful summary + completed in-memory checkpoints; synchronous calls are not forcibly interrupted
cycle_detectedPlanner proposes an already-executed (tool_name, arguments) pairImmediate halt naming the repeated tool call + partial findings
tool_execution_errorTool handler raises an unrecoverable exceptionError diagnostic + partial findings collected prior to failure
planner_errorPlanner raises, returns an invalid plan, or omits a valid next tool/final answerPlanner diagnostic + partial findings
checkpoint_persistence_errorOptional checkpoint callback fails after tool executionDiagnostic and reconciliation warning; tool may already have executed

2. Step-by-Step Build Walkthrough

  1. Create the fde-03-4 repository and project scaffold:
    mkdir -p fde-03-4/src/fde_03_4 fde-03_4/tests fde-03-4/.github/workflows
    cd fde-03-4
    git init
    
    cat > .gitignore <<'EOF'
    .venv/
    .env
    __pycache__/
    .pytest_cache/
    *.egg-info/
    dist/
    build/
    EOF
    
    cat > pyproject.toml <<'EOF'
    [build-system]
    requires = ["setuptools>=68"]
    build-backend = "setuptools.build_meta"
    
    [project]
    name = "fde-03-4"
    version = "0.1.0"
    description = "Bounded agent loops, cycle detection, context compaction, and graceful failure"
    requires-python = ">=3.11"
    dependencies = ["pydantic>=2.6,<3"]
    
    [project.optional-dependencies]
    dev = ["pytest>=8.0,<9"]
    
    [tool.setuptools.packages.find]
    where = ["src"]
    
    [tool.pytest.ini_options]
    testpaths = ["tests"]
    EOF
    
    cat > .env.example <<'EOF'
    # This teaching module uses deterministic local runners and needs no secrets.
    EOF
    
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env
  2. Define strict Pydantic v2 schemas in src/fde_03_4/schemas.py: Enforce extra="forbid", strict=True, positive integer bounds (rejecting booleans), and explicit termination reasons.
    """Strict Pydantic v2 schemas for bounded agent loops and graceful failure."""
    
    from __future__ import annotations
    
    from typing import Any, Literal
    from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
    
    TerminationReason = Literal[
        "completed",
        "max_steps_exceeded",
        "token_budget_exceeded",
        "timeout_exceeded",
        "cycle_detected",
        "tool_execution_error",
        "planner_error",
        "checkpoint_persistence_error",
    ]
    
    
    def _require_non_blank(value: str, field_name: str) -> str:
        cleaned = value.strip()
        if not cleaned:
            raise ValueError(f"{field_name} must not be blank")
        return cleaned
    
    
    def _require_positive_int(value: int, field_name: str) -> int:
        if isinstance(value, bool) or not isinstance(value, int):
            raise ValueError(f"{field_name} must be an integer, not bool")
        if value < 1:
            raise ValueError(f"{field_name} must be at least 1")
        return value
    
    
    class LoopBudget(BaseModel):
        """Execution ceilings for a bounded multi-step workflow."""
    
        model_config = ConfigDict(extra="forbid", strict=True)
    
        max_steps: int = Field(default=5)
        max_total_tokens: int = Field(default=4000)
        max_elapsed_ms: int = Field(default=10000)
        max_context_chars: int = Field(default=1200)
        max_observation_chars: int = Field(default=4000)
        keep_recent_steps: int = Field(default=2)
    
        @field_validator(
            "max_steps",
            "max_total_tokens",
            "max_elapsed_ms",
            "max_context_chars",
            "max_observation_chars",
            "keep_recent_steps",
        )
        @classmethod
        def _validate_positive_ints(cls, value: int, info) -> int:
            return _require_positive_int(value, info.field_name)
    
    
    class PlannedStep(BaseModel):
        """Next action proposed by a planner step."""
    
        model_config = ConfigDict(extra="forbid", strict=True)
    
        done: bool = False
        final_answer: str | None = None
        tool_name: str | None = None
        arguments: dict[str, Any] = Field(default_factory=dict)
        estimated_tokens: int = Field(default=200)
    
        @field_validator("estimated_tokens")
        @classmethod
        def _validate_tokens(cls, value: int) -> int:
            return _require_positive_int(value, "estimated_tokens")
    
        @model_validator(mode="after")
        def _validate_action_shape(self) -> "PlannedStep":
            if self.done:
                if self.final_answer is None or not self.final_answer.strip():
                    raise ValueError("done=True requires a non-blank final_answer")
                if self.tool_name is not None or self.arguments:
                    raise ValueError("done=True cannot include a tool_name or tool arguments")
            else:
                if self.final_answer is not None:
                    raise ValueError("done=False cannot include a final_answer")
                if self.tool_name is None or not self.tool_name.strip():
                    raise ValueError("done=False requires a non-blank tool_name")
            return self
    
    
    class ToolStepRecord(BaseModel):
        """Persisted checkpoint for a single executed tool step."""
    
        model_config = ConfigDict(extra="forbid", strict=True)
    
        step_number: int
        tool_name: str = Field(min_length=1)
        arguments: dict[str, Any]
        observation: str = Field(min_length=1)
        estimated_tokens: int
    
        @field_validator("step_number", "estimated_tokens")
        @classmethod
        def _validate_step_ints(cls, value: int, info) -> int:
            return _require_positive_int(value, info.field_name)
    
        @field_validator("tool_name", "observation")
        @classmethod
        def _validate_step_text(cls, value: str, info) -> str:
            return _require_non_blank(value, info.field_name)
    
    
    class BoundedLoopResult(BaseModel):
        """Structured final or fallback outcome from a bounded agent run."""
    
        model_config = ConfigDict(extra="forbid", strict=True)
    
        status: Literal["completed", "stopped_gracefully"]
        termination_reason: TerminationReason
        summary: str = Field(min_length=1)
        steps_executed: int = Field(ge=0)
        total_tokens_used: int = Field(ge=0)
        compaction_count: int = Field(ge=0)
        checkpoints: list[ToolStepRecord] = Field(default_factory=list)
        compacted_context: str = Field(min_length=1)
        diagnostic_detail: str | None = None
    
        @field_validator("summary", "compacted_context")
        @classmethod
        def _validate_non_blank_outputs(cls, value: str, info) -> str:
            return _require_non_blank(value, info.field_name)
  3. Implement cycle detection, context compaction, and bounded execution in src/fde_03_4/runner.py:
    """Bounded multi-step runner with cycle detection, context compaction, and graceful fallback."""
    
    from __future__ import annotations
    
    import copy
    import json
    import math
    import time
    from typing import Any, Callable
    
    from fde_03_4.schemas import (
        BoundedLoopResult,
        LoopBudget,
        PlannedStep,
        ToolStepRecord,
        TerminationReason,
        _require_non_blank,
    )
    
    PlannerFn = Callable[[str, str, int], PlannedStep]  # goal, bounded context, completed-step count
    ToolExecutorFn = Callable[[str, dict[str, Any]], str]
    ClockMsFn = Callable[[], float]
    
    
    def _validate_json_value(
        value: Any,
        path: str = "arguments",
        _active_containers: set[int] | None = None,
        _depth: int = 0,
    ) -> None:
        """Reject lossy, cyclic, excessively nested, or non-standard JSON values."""
        if _depth > 50:
            raise ValueError(f"{path} exceeds the maximum supported nesting depth (50)")
        if value is None or isinstance(value, (str, bool, int)):
            return
        if isinstance(value, float):
            if not math.isfinite(value):
                raise ValueError(f"{path} contains a non-finite number")
            return
    
        if _active_containers is None:
            _active_containers = set()
    
        if isinstance(value, (list, dict)):
            identity = id(value)
            if identity in _active_containers:
                raise ValueError(f"{path} contains a circular reference")
            _active_containers.add(identity)
            try:
                if isinstance(value, list):
                    for index, item in enumerate(value):
                        _validate_json_value(
                            item, f"{path}[{index}]", _active_containers, _depth + 1
                        )
                else:
                    for key, item in value.items():
                        if not isinstance(key, str):
                            raise ValueError(
                                f"{path} contains a non-string dictionary key: {key!r}"
                            )
                        _validate_json_value(
                            item, f"{path}.{key}", _active_containers, _depth + 1
                        )
            finally:
                _active_containers.remove(identity)
            return
    
        raise ValueError(
            f"{path} contains unsupported JSON value type: {type(value).__name__}"
        )
    
    
    def canonical_call_signature(tool_name: str, arguments: dict[str, Any]) -> str:
        """Build a deterministic signature from strict, JSON-compatible arguments."""
        clean_tool = _require_non_blank(tool_name, "tool_name")
        if not isinstance(arguments, dict):
            raise ValueError("arguments must be a dictionary")
        _validate_json_value(arguments)
        normalized_args = json.dumps(
            arguments, sort_keys=True, separators=(",", ":"),
            ensure_ascii=False, allow_nan=False,
        )
        return f"{clean_tool}:{normalized_args}"
    
    
    def detect_cycle(
        seen_signatures: set[str],
        tool_name: str,
        arguments: dict[str, Any],
    ) -> bool:
        """Return True if the exact (tool_name, arguments) call was already executed."""
        return canonical_call_signature(tool_name, arguments) in seen_signatures
    
    
    def compact_context_history(
        goal: str,
        checkpoints: list[ToolStepRecord],
        max_context_chars: int,
        keep_recent_steps: int,
    ) -> tuple[str, bool]:
        """Return context no longer than max_context_chars, preserving the goal and newest useful observations."""
        clean_goal = _require_non_blank(goal, "goal")
        if isinstance(max_context_chars, bool) or not isinstance(max_context_chars, int) or max_context_chars < 1:
            raise ValueError("max_context_chars must be a positive integer")
        if isinstance(keep_recent_steps, bool) or not isinstance(keep_recent_steps, int) or keep_recent_steps < 1:
            raise ValueError("keep_recent_steps must be a positive integer")
    
        goal_line = f"Goal: {clean_goal}"
        if len(goal_line) > max_context_chars:
            raise ValueError(
                "The goal itself exceeds max_context_chars; increase the context budget or shorten the goal"
            )
    
        full_lines = [goal_line] + [
            f"Step {rec.step_number} [{rec.tool_name}]: {rec.observation}"
            for rec in checkpoints
        ]
        full_text = "\n".join(full_lines)
        if len(full_text) <= max_context_chars:
            return full_text, False
    
        remaining = max_context_chars - len(goal_line)
        selected: list[str] = []
        recent = checkpoints[-keep_recent_steps:]
        # Prioritize the newest checkpoint. Older recent items are included only if they fit.
        for rec in reversed(recent):
            header = f"Step {rec.step_number} [{rec.tool_name}]: "
            available = remaining - 1  # newline separator
            if available <= len(header):
                break
            observation = rec.observation
            if len(header) + len(observation) > available:
                observation = observation[: max(0, available - len(header) - 1)].rstrip() + "…"
            line = header + observation
            if len(line) + 1 > remaining:
                break
            selected.append(line)
            remaining -= len(line) + 1
        selected.reverse()
    
        omitted_count = max(0, len(checkpoints) - len(selected))
        digest = ""
        if omitted_count and remaining > 0:
            digest_text = f"Earlier checkpoints compacted: {omitted_count}"
            if len(digest_text) + 1 <= remaining:
                digest = digest_text
    
        lines = [goal_line]
        if digest:
            lines.append(digest)
        lines.extend(selected)
        compacted = "\n".join(lines)
    
        # The goal always fits because an oversized goal is rejected as invalid input; trim the optional digest first if separators or edge cases exceed the limit.
        if len(compacted) > max_context_chars and digest:
            lines.remove(digest)
            compacted = "\n".join(lines)
        if len(compacted) > max_context_chars:
            compacted = goal_line
        return compacted, True
    
    
    def _build_graceful_fallback(
        goal: str,
        reason: TerminationReason,
        detail: str,
        checkpoints: list[ToolStepRecord],
        total_tokens: int,
        compaction_count: int,
        compacted_context: str,
    ) -> BoundedLoopResult:
        if checkpoints:
            findings = "; ".join(
                f"step {c.step_number} ({c.tool_name}): {c.observation[:80]}"
                for c in checkpoints
            )
            summary = (
                f"Stopped gracefully ({reason}) for '{goal}'. "
                f"Partial findings from {len(checkpoints)} completed step(s): {findings}."
            )
        else:
            summary = (
                f"Stopped gracefully ({reason}) for '{goal}' before completing any tool steps."
            )
        return BoundedLoopResult(
            status="stopped_gracefully",
            termination_reason=reason,
            summary=summary,
            steps_executed=len(checkpoints),
            total_tokens_used=total_tokens,
            compaction_count=compaction_count,
            checkpoints=list(checkpoints),
            compacted_context=compacted_context or f"Goal: {goal}",
            diagnostic_detail=detail,
        )
    
    
    def run_bounded_agent_loop(
        goal: str,
        planner: PlannerFn,
        tool_executor: ToolExecutorFn,
        budget: LoopBudget | None = None,
        checkpoint_sink: Callable[[ToolStepRecord], None] | None = None,
        clock_ms: ClockMsFn | None = None,
    ) -> BoundedLoopResult:
        """Run with cooperative elapsed-time checks, estimated planner-token accounting, and optional checkpoint persistence.
    
        A synchronous planner/tool call cannot be forcibly interrupted by this function.
        The deadline is checked immediately after each call returns. Use cancellable async
        operations or process isolation when a hard interruption guarantee is required.
        """
        clean_goal = _require_non_blank(goal, "goal")
        active_budget = budget or LoopBudget()
        now_ms: ClockMsFn = clock_ms or (lambda: time.monotonic() * 1000.0)
        start_ms = now_ms()
    
        checkpoints: list[ToolStepRecord] = []
        seen_signatures: set[str] = set()
        total_tokens = 0
        compaction_count = 0
        context_text, _ = compact_context_history(
            clean_goal, [], active_budget.max_context_chars, active_budget.keep_recent_steps
        )
    
        def timed_out() -> tuple[bool, float]:
            elapsed = now_ms() - start_ms
            return elapsed >= active_budget.max_elapsed_ms, elapsed
    
        while True:
            expired, elapsed_ms = timed_out()
            if expired:
                return _build_graceful_fallback(
                    clean_goal, "timeout_exceeded",
                    f"Elapsed time {round(elapsed_ms, 2)} ms reached limit {active_budget.max_elapsed_ms} ms",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            try:
                plan = planner(clean_goal, context_text, len(checkpoints))
                if not isinstance(plan, PlannedStep):
                    plan = PlannedStep.model_validate(plan)
            except Exception as exc:
                expired, elapsed_ms = timed_out()
                if expired:
                    return _build_graceful_fallback(
                        clean_goal, "timeout_exceeded",
                        f"Planner raised {type(exc).__name__} after elapsed time "
                        f"{round(elapsed_ms, 2)} ms reached limit "
                        f"{active_budget.max_elapsed_ms} ms: {exc}",
                        checkpoints, total_tokens, compaction_count, context_text,
                    )
                return _build_graceful_fallback(
                    clean_goal, "planner_error", f"{type(exc).__name__}: {exc}",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            # Charge the planner estimate even when it proposes completion.
            total_tokens += plan.estimated_tokens
    
            expired, elapsed_ms = timed_out()
            if expired:
                return _build_graceful_fallback(
                    clean_goal, "timeout_exceeded",
                    f"Planner returned after elapsed time {round(elapsed_ms, 2)} ms reached limit {active_budget.max_elapsed_ms} ms",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            # Reaching the budget is a stop, including when the planner says it is done.
            if total_tokens >= active_budget.max_total_tokens:
                return _build_graceful_fallback(
                    clean_goal, "token_budget_exceeded",
                    f"Estimated planner tokens {total_tokens} reached or exceeded limit {active_budget.max_total_tokens}",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            if plan.done:
                final_text = (plan.final_answer or "").strip()
                if not final_text:
                    return _build_graceful_fallback(
                        clean_goal, "planner_error",
                        "Planner marked run done without a non-blank final_answer",
                        checkpoints, total_tokens, compaction_count, context_text,
                    )
                return BoundedLoopResult(
                    status="completed",
                    termination_reason="completed",
                    summary=final_text,
                    steps_executed=len(checkpoints),
                    total_tokens_used=total_tokens,
                    compaction_count=compaction_count,
                    checkpoints=list(checkpoints),
                    compacted_context=context_text,
                    diagnostic_detail=None,
                )
    
            if len(checkpoints) >= active_budget.max_steps:
                return _build_graceful_fallback(
                    clean_goal, "max_steps_exceeded",
                    f"Reached max_steps limit ({active_budget.max_steps})",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            if not plan.tool_name or not plan.tool_name.strip():
                return _build_graceful_fallback(
                    clean_goal, "planner_error",
                    "Planner did not provide a valid tool_name for the next step",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            clean_tool = _require_non_blank(plan.tool_name, "tool_name")
            call_args = dict(plan.arguments)
            try:
                signature = canonical_call_signature(clean_tool, call_args)
            except (TypeError, ValueError) as exc:
                return _build_graceful_fallback(
                    clean_goal, "planner_error", f"Invalid tool arguments: {exc}",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            if signature in seen_signatures:
                return _build_graceful_fallback(
                    clean_goal, "cycle_detected",
                    f"Repeated identical tool call detected: {clean_tool} with args {call_args}",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            # Argument validation and signature generation may take time; recheck
            # the deadline immediately before starting the external side effect.
            expired, elapsed_ms = timed_out()
            if expired:
                return _build_graceful_fallback(
                    clean_goal, "timeout_exceeded",
                    f"Elapsed time {round(elapsed_ms, 2)} ms reached limit {active_budget.max_elapsed_ms} ms before tool execution",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            seen_signatures.add(signature)
    
            try:
                raw_observation = tool_executor(clean_tool, copy.deepcopy(call_args))
                if not isinstance(raw_observation, str) or not raw_observation.strip():
                    raise ValueError("Tool returned an empty observation")
            except Exception as exc:
                expired, elapsed_ms = timed_out()
                if expired:
                    return _build_graceful_fallback(
                        clean_goal, "timeout_exceeded",
                        f"Tool raised {type(exc).__name__} after elapsed time "
                        f"{round(elapsed_ms, 2)} ms reached limit "
                        f"{active_budget.max_elapsed_ms} ms. The tool may have "
                        f"performed an external side effect before raising; reconcile "
                        f"the external state before retrying. Original error: {exc}",
                        checkpoints, total_tokens, compaction_count, context_text,
                    )
                return _build_graceful_fallback(
                    clean_goal, "tool_execution_error",
                    f"{type(exc).__name__}: {exc}. The tool may have performed an "
                    "external side effect before raising; reconcile the external "
                    "state before retrying.",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            # Bound what is retained and forwarded; the raw response has already been
            # received, so this does not cap the provider/network response allocation.
            clean_observation = raw_observation.strip()
            if len(clean_observation) > active_budget.max_observation_chars:
                clean_observation = clean_observation[: active_budget.max_observation_chars - 1] + "…"
    
            record = ToolStepRecord(
                step_number=len(checkpoints) + 1,
                tool_name=clean_tool,
                arguments=call_args,
                observation=clean_observation,
                estimated_tokens=plan.estimated_tokens,
            )
            checkpoints.append(record)
    
            # Check immediately after the synchronous tool call and checkpoint creation.
            # Preserve the in-memory result even when the deadline has already expired.
            expired, elapsed_ms = timed_out()
            if expired:
                return _build_graceful_fallback(
                    clean_goal, "timeout_exceeded",
                    f"Tool returned after elapsed time {round(elapsed_ms, 2)} ms reached limit {active_budget.max_elapsed_ms} ms; external persistence was skipped",
                    checkpoints, total_tokens, compaction_count, context_text,
                )
    
            if checkpoint_sink is not None:
                try:
                    # Give callbacks a copy so they cannot mutate the runner's checkpoint.
                    checkpoint_sink(record.model_copy(deep=True))
                except Exception as exc:
                    return _build_graceful_fallback(
                        clean_goal, "checkpoint_persistence_error",
                        f"Checkpoint callback failed after tool execution: {type(exc).__name__}: {exc}. "
                        "The tool may already have executed; reconcile before retrying.",
                        checkpoints, total_tokens, compaction_count, context_text,
                    )
                expired, elapsed_ms = timed_out()
                if expired:
                    return _build_graceful_fallback(
                        clean_goal, "timeout_exceeded",
                        f"Checkpoint callback returned after elapsed time {round(elapsed_ms, 2)} ms reached limit {active_budget.max_elapsed_ms} ms",
                        checkpoints, total_tokens, compaction_count, context_text,
                    )
    
            context_text, did_compact = compact_context_history(
                clean_goal, checkpoints,
                max_context_chars=active_budget.max_context_chars,
                keep_recent_steps=active_budget.keep_recent_steps,
            )
            if did_compact:
                compaction_count += 1
    

    Execution and checkpoint boundaries: The elapsed-time budget is cooperative: the runner checks the deadline before work, after the planner returns, immediately before tool execution, after the tool returns, and after an optional checkpoint callback. After a tool returns, it records the bounded observation in memory before checking the deadline; if already expired, it skips the external checkpoint callback. It also checks again after that callback. Python cannot forcibly interrupt a blocking synchronous call. Use cancellable asynchronous operations or process isolation for a hard interruption guarantee. The token budget counts planner-provided estimates (including the final planning response); it is not actual provider token usage and does not measure tool payload tokens. max_observation_chars limits each observation retained in memory and sent back as planner context, but cannot prevent the tool/API from allocating a large raw response before returning. Each checkpoint labels its token figure estimated_tokens to distinguish it from measured provider usage. Checkpoints are always retained in the returned in-memory result. They are persisted externally only when a checkpoint_sink callback is supplied and succeeds. In production, connect this callback to a durable store (such as a transactional database or append-only event log), and make writes idempotent using the run ID and step number so retries do not create duplicate records. This lesson keeps the storage adapter out of scope; implementing durable storage, retention, access control, and recovery is a separate infrastructure concern. If that callback fails after a tool has run, reconcile the external action before retrying.

    Timeout and retry safety: The runner uses cooperative deadline checks; it cannot forcibly stop a synchronous planner, tool, or checkpoint callback. If one returns or raises after the deadline, the run is reported as timeout_exceeded. A tool can complete an external side effect and then raise before returning an observation, so do not blindly retry: first reconcile the external system state and use idempotency keys or deduplication where the API supports them.

  4. Add unit tests in tests/test_runner.py:
    """Tests for bounded agent loops, cycle detection, compaction, and graceful fallback."""
    
    from __future__ import annotations
    
    import pytest
    from pydantic import ValidationError
    
    from fde_03_4.schemas import LoopBudget, PlannedStep, ToolStepRecord
    from fde_03_4.runner import compact_context_history, run_bounded_agent_loop
    
    
    def test_completes_within_budget_and_records_checkpoints() -> None:
        persisted: list[ToolStepRecord] = []
    
        def planner(goal: str, context: str, steps_executed: int) -> PlannedStep:
            if steps_executed == 0:
                return PlannedStep(tool_name="lookup_shipment", arguments={"id": "SHP-10"}, estimated_tokens=150)
            return PlannedStep(done=True, final_answer="Shipment SHP-10 is cleared at port.", estimated_tokens=120)
    
        result = run_bounded_agent_loop(
            goal="Check shipment SHP-10 status",
            planner=planner,
            tool_executor=lambda tool, args: f"status=CLEARED for {args['id']}",
            budget=LoopBudget(max_steps=4, max_total_tokens=1000),
            checkpoint_sink=persisted.append,
        )
        assert result.status == "completed"
        assert result.steps_executed == 1
        assert len(persisted) == 1
        assert result.total_tokens_used == 270
    
    
    def test_stops_gracefully_on_max_steps_exceeded() -> None:
        def planner(goal: str, context: str, steps_executed: int) -> PlannedStep:
            return PlannedStep(tool_name="fetch_page", arguments={"page": steps_executed + 1}, estimated_tokens=100)
    
        result = run_bounded_agent_loop(
            "Scan shipment manifests", planner,
            lambda tool, args: f"page_{args['page']}_ok",
            LoopBudget(max_steps=2, max_total_tokens=5000),
        )
        assert result.termination_reason == "max_steps_exceeded"
        assert result.steps_executed == 2
    
    
    def test_detects_repeated_tool_call_cycle_immediately() -> None:
        planner = lambda goal, context, steps_executed: PlannedStep(
            tool_name="query_carrier", arguments={"shipment": "SHP-99"}, estimated_tokens=100
        )
        result = run_bounded_agent_loop(
            "Resolve carrier hold", planner, lambda tool, args: "pending_retry",
            LoopBudget(max_steps=6, max_total_tokens=5000),
        )
        assert result.termination_reason == "cycle_detected"
        assert result.steps_executed == 1
    
    
    def test_compacts_context_to_limit_and_preserves_goal_and_latest_observation() -> None:
        records = [
            ToolStepRecord(step_number=i, tool_name="read_manifest", arguments={"chunk": i},
                           observation=("old-" if i < 3 else "LATEST-") + "X" * 120, estimated_tokens=10)
            for i in range(1, 5)
        ]
        context, compacted = compact_context_history(
            "Audit long freight manifest", records, max_context_chars=150, keep_recent_steps=2
        )
        assert compacted is True
        assert len(context) <= 150
        assert "Goal: Audit long freight manifest" in context
        assert "LATEST-" in context
    
    
    def test_goal_larger_than_context_budget_is_rejected() -> None:
        with pytest.raises(ValueError, match="goal itself exceeds"):
            compact_context_history("A very long goal", [], max_context_chars=5, keep_recent_steps=1)
    
    
    def test_token_budget_is_checked_before_accepting_planner_completion() -> None:
        result = run_bounded_agent_loop(
            "Finish task",
            lambda goal, context, steps_executed: PlannedStep(
                done=True, final_answer="Done", estimated_tokens=100
            ),
            lambda tool, args: "unused",
            LoopBudget(max_total_tokens=100),
        )
        assert result.termination_reason == "token_budget_exceeded"
        assert result.status == "stopped_gracefully"
    
    
    def test_timeout_is_checked_after_planner_returns() -> None:
        times = iter([0.0, 0.0, 150.0])
        result = run_bounded_agent_loop(
            "Slow planning",
            lambda goal, context, steps_executed: PlannedStep(
                done=True, final_answer="Done", estimated_tokens=10
            ),
            lambda tool, args: "unused",
            LoopBudget(max_elapsed_ms=100),
            clock_ms=lambda: next(times),
        )
        assert result.termination_reason == "timeout_exceeded"
    
    
    def test_timeout_is_checked_after_tool_returns_and_checkpoint_is_kept() -> None:
        times = iter([0.0, 0.0, 0.0, 0.0, 150.0])
        result = run_bounded_agent_loop(
            "Slow tool",
            lambda goal, context, steps_executed: PlannedStep(
                tool_name="slow_lookup", arguments={}, estimated_tokens=10
            ),
            lambda tool, args: "tool completed",
            LoopBudget(max_elapsed_ms=100),
            clock_ms=lambda: next(times),
        )
        assert result.termination_reason == "timeout_exceeded"
        assert result.steps_executed == 1
        assert result.checkpoints[0].observation == "tool completed"
    
    
    def test_checkpoint_sink_failure_returns_diagnostic() -> None:
        result = run_bounded_agent_loop(
            "Persist result",
            lambda goal, context, steps_executed: PlannedStep(
                tool_name="lookup", arguments={}, estimated_tokens=10
            ),
            lambda tool, args: "lookup completed",
            LoopBudget(),
            checkpoint_sink=lambda record: (_ for _ in ()).throw(OSError("disk full")),
        )
        assert result.termination_reason == "checkpoint_persistence_error"
        assert result.steps_executed == 1
        assert "reconcile before retrying" in (result.diagnostic_detail or "")
    
    
    def test_planner_exception_returns_graceful_diagnostic() -> None:
        def planner(goal, context, history):
            raise RuntimeError("planner unavailable")
    
        result = run_bounded_agent_loop("Plan task", planner, lambda tool, args: "unused")
        assert result.termination_reason == "planner_error"
        assert "planner unavailable" in (result.diagnostic_detail or "")
    
    
    def test_tool_failure_returns_graceful_fallback_diagnostics() -> None:
        def planner(goal: str, context: str, steps_executed: int) -> PlannedStep:
            if steps_executed == 0:
                return PlannedStep(tool_name="get_invoice", arguments={"inv": "INV-1"}, estimated_tokens=100)
            return PlannedStep(tool_name="post_adjustment", arguments={"inv": "INV-1"}, estimated_tokens=100)
    
        def executor(tool_name: str, args: dict[str, object]) -> str:
            if tool_name == "post_adjustment":
                raise RuntimeError("ERP gateway 503 unavailable")
            return "invoice_verified"
    
        result = run_bounded_agent_loop(
            "Apply verified freight adjustment", planner, executor,
            LoopBudget(max_steps=5, max_total_tokens=2000),
        )
        assert result.termination_reason == "tool_execution_error"
        assert result.steps_executed == 1
        assert "ERP gateway 503 unavailable" in (result.diagnostic_detail or "")
        assert "invoice_verified" in result.summary
    
    
    def test_rejects_lossy_or_nonstandard_tool_arguments() -> None:
        from fde_03_4.runner import canonical_call_signature
    
        with pytest.raises(ValueError, match="non-string dictionary key"):
            canonical_call_signature("lookup", {1: "shipment"})  # type: ignore[dict-item]
        with pytest.raises(ValueError, match="non-finite"):
            canonical_call_signature("lookup", {"amount": float("nan")})
    
    
    def test_caps_retained_tool_observation_size() -> None:
        result = run_bounded_agent_loop(
            "Read a large manifest",
            lambda goal, context, steps: PlannedStep(
                tool_name="read_manifest", arguments={}, estimated_tokens=10
            ),
            lambda tool, args: "X" * 100,
            LoopBudget(max_observation_chars=20, max_context_chars=200),
        )
        assert result.steps_executed == 1
        assert len(result.checkpoints[0].observation) == 20
        assert result.checkpoints[0].observation.endswith("…")
    
    
    def test_timeout_after_slow_checkpoint_sink_is_reported() -> None:
        times = iter([0.0, 0.0, 0.0, 0.0, 0.0, 150.0])
        persisted: list[ToolStepRecord] = []
    
        def slow_sink(record: ToolStepRecord) -> None:
            persisted.append(record)
    
        result = run_bounded_agent_loop(
            "Persist a slow checkpoint",
            lambda goal, context, steps: PlannedStep(
                tool_name="lookup", arguments={}, estimated_tokens=10
            ),
            lambda tool, args: "tool completed",
            LoopBudget(max_elapsed_ms=100),
            checkpoint_sink=slow_sink,
            clock_ms=lambda: next(times),
        )
        assert result.termination_reason == "timeout_exceeded"
        assert result.steps_executed == 1
        assert len(persisted) == 1
    
    
    def test_tool_executor_mutation_does_not_change_checkpoint_arguments() -> None:
        def mutating_executor(tool: str, args: dict[str, object]) -> str:
            args["nested"]["id"] = "MUTATED"  # type: ignore[index]
            return "lookup complete"
    
        result = run_bounded_agent_loop(
            "Lookup shipment",
            lambda goal, context, steps: PlannedStep(
                tool_name="lookup", arguments={"nested": {"id": "SHP-10"}}, estimated_tokens=10
            ),
            mutating_executor,
            LoopBudget(),
        )
        assert result.checkpoints[0].arguments == {"nested": {"id": "SHP-10"}}
    
    
    def test_rejects_boolean_budget_fields() -> None:
        with pytest.raises(ValidationError):
            LoopBudget(max_steps=True)  # type: ignore[arg-type]
    
    
    def test_timeout_is_checked_immediately_before_tool_execution() -> None:
        calls: list[str] = []
        times = iter([0.0, 0.0, 0.0, 150.0])
    
        result = run_bounded_agent_loop(
            "Do not start a late tool call",
            lambda goal, context, steps: PlannedStep(
                tool_name="lookup", arguments={}, estimated_tokens=10
            ),
            lambda tool, args: calls.append(tool) or "unexpected",
            LoopBudget(max_elapsed_ms=100),
            clock_ms=lambda: next(times),
        )
    
        assert result.termination_reason == "timeout_exceeded"
        assert calls == []
        assert result.steps_executed == 0
    
    
    def test_rejects_circular_and_excessively_nested_arguments() -> None:
        from fde_03_4.runner import canonical_call_signature
    
        circular: dict[str, object] = {}
        circular["self"] = circular
        with pytest.raises(ValueError, match="circular reference"):
            canonical_call_signature("lookup", circular)
    
        deeply_nested: object = "leaf"
        for _ in range(55):
            deeply_nested = [deeply_nested]
        with pytest.raises(ValueError, match="maximum supported nesting depth"):
            canonical_call_signature("lookup", {"nested": deeply_nested})
    
    
    def test_planned_step_rejects_conflicting_action_fields() -> None:
        with pytest.raises(ValidationError, match="done=True cannot include"):
            PlannedStep(
                done=True, final_answer="Finished",
                tool_name="lookup", arguments={"id": "SHP-1"},
            )
    
        with pytest.raises(ValidationError, match="done=False cannot include"):
            PlannedStep(done=False, final_answer="Finished", tool_name="lookup")
    
        with pytest.raises(ValidationError, match="requires a non-blank final_answer"):
            PlannedStep(done=True, final_answer="   ")
    
    
    def test_planner_exception_after_deadline_is_reported_as_timeout() -> None:
        times = iter([0.0, 0.0, 150.0])
    
        def slow_failing_planner(goal, context, steps_executed):
            raise RuntimeError("planner timed out upstream")
    
        result = run_bounded_agent_loop(
            "Slow failing plan",
            slow_failing_planner,
            lambda tool, args: "unused",
            LoopBudget(max_elapsed_ms=100),
            clock_ms=lambda: next(times),
        )
        assert result.termination_reason == "timeout_exceeded"
        assert "planner timed out upstream" in (result.diagnostic_detail or "")
        assert result.steps_executed == 0
    
    
    def test_tool_exception_after_deadline_is_timeout_and_keeps_prior_checkpoints() -> None:
        ticks = iter([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 150.0])
        calls = 0
    
        def planner(goal, context, steps_executed):
            nonlocal calls
            calls += 1
            if calls == 1:
                return PlannedStep(tool_name="first_lookup", arguments={"id": "A"}, estimated_tokens=5)
            return PlannedStep(tool_name="second_lookup", arguments={"id": "B"}, estimated_tokens=5)
    
        def executor(tool, args):
            if tool == "first_lookup":
                return "first checkpoint saved"
            raise RuntimeError("remote tool failed after request")
    
        result = run_bounded_agent_loop(
            "Run two lookups",
            planner,
            executor,
            LoopBudget(max_elapsed_ms=100),
            clock_ms=lambda: next(ticks),
        )
        assert result.termination_reason == "timeout_exceeded"
        assert result.steps_executed == 1
        assert result.checkpoints[0].observation == "first checkpoint saved"
        assert "reconcile" in (result.diagnostic_detail or "").lower()
    
  5. Configure GitHub Actions in .github/workflows/tests.yml and run tests:
    name: Python tests
    
    on:
      push:
      pull_request:
    
    permissions:
      contents: read
    
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - name: Check out repository
            uses: actions/checkout@v4
    
          - name: Set up Python
            uses: actions/setup-python@v5
            with:
              python-version: "3.11"
    
          - name: Install package and test dependencies
            run: |
              python -m pip install --upgrade pip
              python -m pip install -e ".[dev]"
    
          - name: Run tests
            run: python -m pytest -v

3. Common Pitfalls and Operational Hygiene

  • Confusing estimated tokens, observation caps, or cooperative deadlines with hard limits: This example counts planner-supplied token estimates only. It caps stored observations but cannot prevent a tool from returning a large raw payload. It checks elapsed time after synchronous calls return, but cannot interrupt a blocked call. Use provider usage metadata for actual token accounting and cancellable async operations or process isolation for hard timeouts. Validate planner action shapes so a completed plan contains only a final answer and a continuing plan contains only a valid tool action. Reject circular, excessively nested, or non-standard JSON tool arguments before execution.
  • Compacting away the original user goal: Always anchor compacted context with the original task goal and most recent step observations so the planner does not drift off-task after summarization.
  • Assuming checkpoints are durable by default: The runner retains checkpoint records in memory. Supply a reliable checkpoint_sink to persist them externally; if persistence fails after a tool call, reconcile whether the external action happened before retrying.
  • Letting planner or tool exceptions crash without returning partial progress: Catch failures at the execution boundary and return a structured fallback summary so operators see what succeeded before the failure.

4. Completion Criteria

  • LoopBudget, PlannedStep, ToolStepRecord, and BoundedLoopResult validate inputs strictly with Pydantic v2 and reject boolean integer fields.
  • run_bounded_agent_loop enforces tool-step limits, planner-estimated token limits (including final planner responses), and cooperative elapsed-time checks before and after synchronous calls; it stops any exact repeated (tool_name, arguments) pair within a run, bounds compacted context while preserving the goal, and returns structured fallback summaries for planner, tool, timeout, and checkpoint-sink failures.
  • Run the supplied pytest suite locally and confirm the GitHub Actions workflow passes after pushing fde-03-4. The tests are a focused teaching suite, not proof of hard interruption of synchronous calls or production-grade durable storage.
Practice assignment

Build this

In fde-03-4, implement strict Pydantic v2 models in src/fde_03_4/schemas.py (LoopBudget, PlannedStep, ToolStepRecord, and BoundedLoopResult) and bounded execution controls in src/fde_03_4/runner.py (canonical_call_signature, detect_cycle, compact_context_history, and run_bounded_agent_loop).

  • Enforce maximum step caps, planner-estimated token ceilings (max_total_tokens), and cooperative elapsed-time checks (max_elapsed_ms), recording step checkpoints in memory and forwarding copies to an optional checkpoint_sink callback.
  • Validate JSON-compatible tool arguments (rejecting circular references, deep nesting, non-string keys, and non-finite floats), detect repeated identical (tool_name, arguments) cycles, and halt immediately with cycle_detected.
  • Cap retained observations with max_observation_chars, compact older step history once context exceeds max_context_chars while preserving the goal and newest observations, and return a structured BoundedLoopResult fallback summary on early termination or errors.
  • Add unit tests in tests/test_runner.py covering normal completion, max-step termination, token-budget termination, cycle detection, context compaction, cooperative timeouts, and planner, tool, or checkpoint-sink errors, then run python -m pytest -v and push fde-03-4 (including .github/workflows/tests.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. How do step caps and context compaction prevent runaway token spend and context overflow in multi-step runs?
  2. Why is cycle detection needed even when a workflow already has a maximum step limit?
  3. What information should a graceful fallback summary include when an agent loop stops early due to a tool failure or budget limit?
  4. Why record per-step checkpoints and pass them to a checkpoint_sink as each step finishes rather than waiting until the run ends?
Reveal self-review answers (attempt the questions first)
  1. Step caps and context compaction: Step caps put a hard ceiling on tool-call iterations and cumulative estimated tokens, while context compaction bounds prompt size within max_context_chars and caps stored observations via max_observation_chars instead of letting history grow unbounded across steps.
  2. Why cycle detection matters: If a planner repeats the exact same (tool_name, arguments) call on step 2 and step 3, waiting until max_steps wastes tokens, latency, and external rate-limit quota on calls guaranteed to repeat the prior result.
  3. Graceful fallback diagnostics: Return a structured BoundedLoopResult with status="stopped_gracefully", the exact termination_reason (such as max_steps_exceeded, token_budget_exceeded, timeout_exceeded, cycle_detected, tool_execution_error, planner_error, or checkpoint_persistence_error), completed steps, partial findings, and clear reconciliation or next-step guidance.
  4. Per-step checkpoints: Recording each completed step immediately preserves partial observations and spend counters in memory and lets an external checkpoint_sink persist progress incrementally so operators can inspect where a run stopped or reconcile external actions before retrying.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.