AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 46

    Agent Reliability, Guardrails and Failure Recovery

    A TechLearningPro operations run can fail in more ways than a single HTTP route.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 46 · AI Agents, Workflow Automation and Integrations

    Lesson Overview

    A TechLearningPro operations run can fail in more ways than a single HTTP route. The model returns a tool name you did not register. The billing read times out. The mail vendor returns 429. The same run asks for a refund after it was told to draft a reminder. A staff user double-submits the resume button while a commit is execution_unknown. If each of those cases is a special catch in a route, the next incident invents a new loop. This lesson puts the limits in one place: runGuardedStep.

    Guardrails are the checks that run before a step is allowed to spend money or change state: input shape, operation allow-list, output schema, step budget, and a wall clock. Reliability is what you do after a typed failure: retry a read with a cap, resume a commit only with the same idempotency key Lesson 45 stored, or checkpoint and stop. Recovery is the checkpoint itself, so a process restart does not repeat a side effect it cannot see.

    Policy version is agent-guardrails-v1. Illustrative budgets: 6 steps, 2 model calls, 4 connector calls, 20 seconds of wall time. Those numbers are lab ratios. Replace them with the tenant contract before you treat them as a capacity plan. The function does not call a vendor SDK. It calls ports for the model, the connector, the approval executor, and the checkpoint store.

    The capstone in Lesson 47 will use this runner for the cohort reminder workflow. This lesson is the runner and the failure matrix, with a small fixture workflow so the tests do not need the full product.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Define a guardrail as a server check that runs before a model or a connector spends a call.
    2. Enforce max steps, max model calls, max connector calls, and a wall-clock budget.
    3. Reject a tool name that is not on the run's allow-list.
    4. Validate model JSON against a schema and allow one repair call.
    5. Classify failures as timeout, rate limit, invalid output, tool denied, upstream, budget, or poison.
    6. Retry idempotent reads with a bounded attempt count and jittered backoff.
    7. Refuse to retry a write by minting a new idempotency key.
    8. Resume execution_unknown only through Lesson 45's executor.
    9. Open a circuit after repeated upstream failures and fail the next call fast.
    10. Persist a checkpoint that names completed steps and omits prompts and secrets.
    11. Stop a run that repeats the same invalid proposal, and mark it poison.
    12. Return a typed result the panel can render when the run pauses or fails.
    13. Keep the feature flag as a kill switch that stops new steps.
    14. Test the matrix with fakes: budget, retry cap, circuit, and idempotent resume.
    15. Explain which failures a human must see, and which ones the runner may absorb.

    Prerequisites

    What is an Agent Guardrail?

    An agent guardrail is deterministic code that allows or stops a step. The model is probabilistic. The guardrail is not. It counts steps, checks names against a set, and parses JSON. If the check fails, the step does not run.

    Reliability is the property that a failure has a planned outcome: a bounded retry, a paused ticket, a degraded read, or a clean stop. An unbounded loop is not reliability. It is a bill and a race.

    Failure recovery is how a run continues after a crash or a timeout without repeating a write. The checkpoint records which steps completed and the idempotency keys they used. Recovery loads that record and starts at the next step.

    The industry already had these ideas in workers and sagas. Agents added a planner that can request the same tool forever. The guardrail is the worker's max-attempt setting, applied to a planner that does not know your invoice table.

    TermMeaning in this lesson
    StepOne model call or one connector or approval call
    BudgetCaps on steps, model calls, connector calls, and wall time
    RepairA single extra model call after invalid JSON
    PoisonThe same invalid proposal repeated after repair
    CheckpointStored completed step names and idempotency keys
    CircuitA fast-fail switch after repeated upstream errors
    ResumeContinue from a checkpoint, not from step zero
    Kill switchfeatureEnabled false stops new steps

    Why Do We Need It?

    text
    Each step has its own try/catch
    |
    v
    A timeout retries a refund with a new key
    |
    v
    A tool loop spends the model budget overnight
    |
    v
    runGuardedStep + budget + checkpoint + retry policy
    |
    v
    Reads may retry. Writes keep their key. Loops stop.

    Benefits:

    • Cost has a ceiling the route can explain.
    • A crashed process resumes from completed steps instead of sending a second email.
    • Upstream outages trip a circuit instead of occupying every worker.
    • The panel receives paused, budget_exceeded, or circuit_open instead of a stack trace.
    • Lesson 47 can stay a workflow definition. The failure policy stays here.

    Real World Example

    The cohort reminder run looks up stalled Northwind learners, drafts a template id, and proposes messaging.email.send. The enrollment read times out once. The policy retries the read because it is idempotent, then succeeds. The model then emits billing.refund.create, which is not on this run's allow-list. The runner returns tool_denied and does not call the approval proposer. A second fixture hits the mail vendor with 429 twice. The circuit opens. The checkpoint says lookup completed and send did not. A resume after the vendor recovers does not repeat the lookup's side effects, because lookup had none, and it does not send mail until a ticket is approved.

    The same pattern is a bank job that retries a balance read and refuses to retry a wire without the original end-to-end id. A hospital interface retries a chart read and does not duplicate an order when the ack times out. Amazon-style workflows and Netflix-style encoders checkpoint stages. Microsoft and Google workflow products expose attempt caps and dead-letter queues. TechLearningPro's version is the operations runner with a six-step cap and a checkpoint row.

    Internal Working

    1. If featureEnabled is false, return disabled and do not load the checkpoint's next step.
    2. Load the checkpoint for (tenant, workflowRunId). If none, start at the first step with empty counters.
    3. Before each step, if steps, modelCalls, connectorCalls, or wallMs would exceed the budget, persist the checkpoint and return budget_exceeded.
    4. If the circuit for that operation is open, return circuit_open without calling the port.
    5. Model steps: call the model port once. If the output fails schema validation, call repair once. A second failure is poison if the payload equals the previous invalid payload, otherwise invalid_model_output.
    6. Connector read steps: on timeout or rate_limited, sleep the backoff and retry while attempts remain. Attempts count toward connectorCalls. Success records the step complete.
    7. Connector write steps: do not call the Lesson 44 read executor. Call propose and return awaiting_approval. There is no retry of propose with a new idempotency key.
    8. Resume of a commit: if the checkpoint says execution_unknown, call executeApproved with the same ticket id. Do not create a second ticket.
    9. On upstream failure past the attempt cap, increment the circuit failure count. At the threshold, open the circuit until openUntil.
    10. Persist the checkpoint after every successful step: completed step names, ticket id if any, counters, and no prompt text.
    11. Return completed, awaiting_approval, or a failure reason. The panel maps those strings. It does not parse vendor HTML.

    Architecture

    flowchart TB
      subgraph runner [runGuardedStep]
        Flag[Feature flag]
        Budget[Budget counters]
        Circuit[Circuit breaker]
        Model[Model port]
        Read[Read connector]
        Approve[Approval port]
        Save[Checkpoint]
      end
    
      Flag --> Budget
      Budget --> Circuit
      Circuit --> Model
      Circuit --> Read
      Circuit --> Approve
      Model --> Save
      Read --> Save
      Approve --> Save
    text
    workflowRunId + tenant + now
    |
    v
    Flag and checkpoint load
    |
    v
    Budget check
    |
    +--> exceeded --> save + budget_exceeded
    |
    v
    Circuit check
    |
    +--> open --> circuit_open
    |
    +--> model --> schema or one repair --> poison if repeated
    +--> read --> retry while attempts remain
    +--> write --> propose once --> awaiting_approval
    |
    v
    Checkpoint without prompt text

    Request flow into a vendor happens only inside the connector or commit port, after these checks. Response flow to the panel is the runner result plus the checkpoint id.

    Deep Dive

    Budgets are product limits

    GuardrailBudget in agent-guardrails-v1:

    CounterLab valueWhat counts
    maxSteps6Every attempt, including retries and the repair call
    maxModelCalls2First generation plus one repair
    maxConnectorCalls4Reads, retries, propose, execute
    maxWallMs20_000From run start, including backoff sleeps in production

    A retry is not free. It consumes connectorCalls and maxSteps. A team that sets retries to 5 and max connector calls to 4 will stop at the budget, which is what you want. Document the interaction so on-call does not "raise retries" without raising the budget on purpose.

    Wall time uses the injected clock in tests. Production uses Date.now() at the start and before each step. Backoff sleep counts. A run should not hold a web request for the whole budget. The route starts the run, stores the checkpoint, and returns 202 with the run id when the next step is a wait. The lab function is synchronous from the caller's point of view so tests can assert the result. The capstone route should move waits off the request thread.

    Schema and repair

    The model returns JSON. The runner accepts an object with tool and args or a terminal object { "done": true, "templateId": "cohort_reminder_v1" }. Anything else is invalid. Repair is one call with a fixed instruction: return JSON matching the schema. The repair prompt does not include the tool catalog from the user, and it does not include secrets. If repair returns the same invalid string, the run is poison. Poison checkpoints the run as terminal so a resume does not pay for the same failure. A human can start a new run id.

    False allow is a guardrail that lets a denied tool through. False refuse is a schema that rejects a valid terminal object. Keep a fixture for both in tests. Evaluation from Lesson 18 applies: the guardrail is a classifier you can score without a live model, because the fixtures are strings you wrote.

    Retry policy

    FailureReadWrite / commit
    timeoutRetry until attempt capexecution_unknown, same key, no new ticket
    rate_limitedRetry with backoffDo not propose again in a loop
    not_foundStop, success-shaped security outcomeStop
    invalid_argsStopStop
    upstream_unavailableRetry, then circuitCircuit, ticket stays put

    Attempt cap in the lab is 2 for reads (one initial, one retry). Backoff is baseMs * 2 ^ attempt with full jitter between 0 and that value. Tests inject sleep and random so they do not wait. Production base is 200 ms. Do not retry not_found. Widening the query is the Lesson 44 mistake, and a retry policy must not reintroduce it.

    Circuit breaker

    Per tenant and operation id, the breaker stores failures and openUntil. Threshold is 3 failures in the lab. Open interval is 30 seconds. While open, runGuardedStep returns circuit_open and does not increment vendor calls. Success resets failures. The breaker state lives beside the checkpoint, not inside the model prompt. A model must not be told to "try the other vendor" when the circuit is open. Vendor choice stays in the composition root, as in Lesson 44.

    Half-open is a single trial after openUntil. The lab implements that as: if now >= openUntil, allow one call. Failure reopens. Success closes. You do not need a library for a counter and a timestamp.

    Checkpoints

    text
    {
    workflowRunId, tenantId, completedSteps: string[],
    ticketId?: string, status: "running" | "paused" | "terminal",
    modelCalls, connectorCalls, steps
    }

    Omitting the user utterance is intentional. The run store from Lesson 38 may hold it under retention rules. The checkpoint is what a replayer needs, and a replayer in logs should not need the utterance. Idempotency keys live on the ticket, and the checkpoint stores ticketId so resume can find them.

    Resume rules:

    • Skip steps named in completedSteps.
    • If status is paused and ticketId is set, the next action is execute or keep waiting, never a second propose.
    • If status is terminal, return the stored reason and do not call the model.

    Kill switch

    featureEnabled is server configuration. A running wait can still be approved by a person, because approval is Lesson 45 and does not need the model. The runner refuses to start a new model or connector step when the flag is off. That split lets you stop spend without freezing a lead who is already looking at a ticket. Document it in the runbook so on-call does not expect the flag to void an approved refund.

    What this runner will not do

    It will not pick a fallback model vendor outside allowedProviderIds. It will not execute a write without a ticket. It will not delete a checkpoint to "start fresh" inside the same run id. A fresh start is a new workflowRunId. It will not parse HTML error pages from vendors. Adapters map those to upstream_unavailable before they reach here.

    Code Examples

    Place the runner in packages/guardrails/src/.

    Simple example: budget and classification

    packages/guardrails/src/policy.ts

    typescript
    export const POLICY_VERSION = "agent-guardrails-v1";
    export interface GuardrailBudget {
    maxSteps: number;
    maxModelCalls: number;
    maxConnectorCalls: number;
    maxWallMs: number;
    maxReadAttempts: number;
    }
    /** Lab ratios. Replace them from the tenant contract before production. */
    export const LAB_BUDGET: GuardrailBudget = {
    maxSteps: 6,
    maxModelCalls: 2,
    maxConnectorCalls: 4,
    maxWallMs: 20_000,
    maxReadAttempts: 2,
    };
    export type FailureReason =
    | "disabled"
    | "budget_exceeded"
    | "circuit_open"
    | "tool_denied"
    | "invalid_model_output"
    | "poison"
    | "timeout"
    | "rate_limited"
    | "upstream"
    | "not_found";
    export interface Counters {
    steps: number;
    modelCalls: number;
    connectorCalls: number;
    startedAtMs: number;
    }
    /**
    * True when another step would pass the cap.
    * Callers stop before the port call.
    */
    export function budgetAllows(budget: GuardrailBudget, counters: Counters, nowMs: number, kind: "model" | "connector"): boolean {
    if (counters.steps + 1 > budget.maxSteps) return false;
    if (nowMs - counters.startedAtMs > budget.maxWallMs) return false;
    if (kind === "model" && counters.modelCalls + 1 > budget.maxModelCalls) return false;
    if (kind === "connector" && counters.connectorCalls + 1 > budget.maxConnectorCalls) return false;
    return true;
    }
    /** Jitter in [0, cap]. Tests pass a fake random in [0, 1). */
    export function backoffMs(attempt: number, random: number, baseMs = 200): number {
    const cap = baseMs * 2 ** attempt;
    return Math.floor(Math.max(0, Math.min(0.999, random)) * cap);
    }

    budgetAllows is the line you want in a code review. Ports are called only after it returns true.

    Intermediate example: schema, circuit, checkpoint

    packages/guardrails/src/schema.ts

    typescript
    export interface ToolProposal {
    kind: "tool";
    tool: string;
    args: Record<string, unknown>;
    }
    export interface TerminalDraft {
    kind: "done";
    templateId: "cohort_reminder_v1";
    }
    export type ModelStep = ToolProposal | TerminalDraft;
    /**
    * Accepts a tool proposal or the terminal reminder draft.
    * Extra keys and prose wrappers are invalid.
    */
    export function parseModelStep(text: string): ModelStep | "invalid" {
    let value: unknown;
    try {
    value = JSON.parse(text);
    } catch {
    return "invalid";
    }
    if (!value || typeof value !== "object" || Array.isArray(value)) return "invalid";
    const record = value as Record<string, unknown>;
    const keys = Object.keys(record);
    if (record.done === true) {
    if (keys.length !== 2 || record.templateId !== "cohort_reminder_v1") return "invalid";
    return { kind: "done", templateId: "cohort_reminder_v1" };
    }
    if (keys.length !== 2 || typeof record.tool !== "string" || !record.args || typeof record.args !== "object" || Array.isArray(record.args)) {
    return "invalid";
    }
    return { kind: "tool", tool: record.tool, args: record.args as Record<string, unknown> };
    }

    packages/guardrails/src/circuit.ts

    typescript
    export interface CircuitState {
    failures: number;
    openUntilMs: number;
    }
    export const CIRCUIT_THRESHOLD = 3;
    export const CIRCUIT_OPEN_MS = 30_000;
    /** Half-open when now has passed openUntil. A failure should call recordFailure again. */
    export function circuitOpen(state: CircuitState | undefined, nowMs: number): boolean {
    if (!state) return false;
    return state.failures >= CIRCUIT_THRESHOLD && nowMs < state.openUntilMs;
    }
    export function recordFailure(state: CircuitState | undefined, nowMs: number): CircuitState {
    const failures = (state?.failures ?? 0) + 1;
    const openUntilMs = failures >= CIRCUIT_THRESHOLD ? nowMs + CIRCUIT_OPEN_MS : state?.openUntilMs ?? 0;
    return { failures, openUntilMs };
    }
    export function recordSuccess(): CircuitState {
    return { failures: 0, openUntilMs: 0 };
    }

    Enterprise example: the runner

    packages/guardrails/src/runner.ts

    typescript
    import { POLICY_VERSION, budgetAllows, backoffMs, LAB_BUDGET, type Counters, type FailureReason, type GuardrailBudget } from "./policy.js";
    import { parseModelStep, type ModelStep } from "./schema.js";
    import { circuitOpen, recordFailure, recordSuccess, type CircuitState } from "./circuit.js";
    export interface Checkpoint {
    workflowRunId: string;
    tenantId: string;
    completedSteps: string[];
    ticketId?: string;
    status: "running" | "paused" | "terminal";
    reason?: FailureReason | "awaiting_approval" | "completed";
    counters: Counters;
    policyVersion: string;
    }
    export interface GuardrailPorts {
    model(promptId: "plan" | "repair"): Promise<{ text: string } | { error: "timeout" | "unavailable" }>;
    read(operationId: string): Promise<{ ok: true } | { ok: false; reason: "timeout" | "rate_limited" | "not_found" | "upstream" }>;
    propose(operationId: string, idempotencyKey: string): Promise<{ ok: true; ticketId: string } | { ok: false; reason: "rejected" }>;
    save(checkpoint: Checkpoint): void;
    load(tenantId: string, workflowRunId: string): Checkpoint | undefined;
    circuit(operationId: string): CircuitState | undefined;
    setCircuit(operationId: string, state: CircuitState): void;
    sleep(ms: number): Promise<void>;
    random(): number;
    now(): number;
    }
    export interface RunInput {
    tenantId: string;
    workflowRunId: string;
    featureEnabled: boolean;
    /** Tools this run may propose. Refund is absent on a reminder run. */
    allowedTools: readonly string[];
    /** Stable key for the write. The runner must not replace it. */
    idempotencyKey: string;
    budget?: GuardrailBudget;
    }
    export type RunResult =
    | { ok: true; status: "completed" | "awaiting_approval"; checkpoint: Checkpoint }
    | { ok: false; reason: FailureReason; checkpoint: Checkpoint };
    /**
    * One fixture workflow: model plans, read enrollment, model finishes with a template, propose email.
    * Lesson 47 replaces the step list. The budget and retry rules stay.
    */
    export async function runGuardedStep(ports: GuardrailPorts, input: RunInput): Promise<RunResult> {
    const budget = input.budget ?? LAB_BUDGET;
    const existing = ports.load(input.tenantId, input.workflowRunId);
    if (existing?.status === "terminal" || existing?.status === "paused") {
    if (existing.status === "paused" && existing.reason === "awaiting_approval") {
    return { ok: true, status: "awaiting_approval", checkpoint: existing };
    }
    if (existing.status === "terminal" && existing.reason && existing.reason !== "completed" && existing.reason !== "awaiting_approval") {
    return { ok: false, reason: existing.reason, checkpoint: existing };
    }
    }
    const counters: Counters = existing?.counters ?? { steps: 0, modelCalls: 0, connectorCalls: 0, startedAtMs: ports.now() };
    const completed = new Set(existing?.completedSteps ?? []);
    if (!input.featureEnabled) {
    return stop(ports, input, counters, completed, "disabled", existing?.ticketId);
    }
    if (!completed.has("plan")) {
    const planned = await modelStep(ports, input, budget, counters, completed, "plan");
    if (!planned.ok) return planned.result;
    if (planned.step.kind === "tool" && !input.allowedTools.includes(planned.step.tool)) {
    return stop(ports, input, counters, completed, "tool_denied", existing?.ticketId);
    }
    completed.add("plan");
    }
    if (!completed.has("lookup")) {
    const read = await readWithRetry(ports, input, budget, counters, completed, "enrollment.lookup");
    if (!read.ok) return read.result;
    completed.add("lookup");
    }
    if (!completed.has("draft")) {
    const drafted = await modelStep(ports, input, budget, counters, completed, "plan");
    if (!drafted.ok) return drafted.result;
    if (drafted.step.kind !== "done") {
    return stop(ports, input, counters, completed, "invalid_model_output", existing?.ticketId);
    }
    completed.add("draft");
    }
    if (!completed.has("propose")) {
    if (!budgetAllows(budget, counters, ports.now(), "connector")) {
    return stop(ports, input, counters, completed, "budget_exceeded", existing?.ticketId);
    }
    counters.steps += 1;
    counters.connectorCalls += 1;
    const proposed = await ports.propose("messaging.email.send", input.idempotencyKey);
    if (!proposed.ok) return stop(ports, input, counters, completed, "upstream");
    completed.add("propose");
    const checkpoint = snapshot(input, counters, completed, "paused", "awaiting_approval", proposed.ticketId);
    ports.save(checkpoint);
    return { ok: true, status: "awaiting_approval", checkpoint };
    }
    const checkpoint = snapshot(input, counters, completed, "terminal", "completed", existing?.ticketId);
    ports.save(checkpoint);
    return { ok: true, status: "completed", checkpoint };
    }
    async function modelStep(
    ports: GuardrailPorts,
    input: RunInput,
    budget: GuardrailBudget,
    counters: Counters,
    completed: Set<string>,
    promptId: "plan" | "repair",
    ): Promise<{ ok: true; step: ModelStep } | { ok: false; result: RunResult }> {
    const call = async (which: "plan" | "repair") => {
    if (!budgetAllows(budget, counters, ports.now(), "model")) {
    return { ok: false as const, result: stop(ports, input, counters, completed, "budget_exceeded") };
    }
    counters.steps += 1;
    counters.modelCalls += 1;
    const response = await ports.model(which);
    if ("error" in response) {
    return { ok: false as const, result: stop(ports, input, counters, completed, response.error === "timeout" ? "timeout" : "upstream") };
    }
    return { ok: true as const, text: response.text };
    };
    const first = await call(promptId);
    if (!first.ok) return first;
    const parsed = parseModelStep(first.text);
    if (parsed !== "invalid") return { ok: true, step: parsed };
    const repair = await call("repair");
    if (!repair.ok) return repair;
    const repaired = parseModelStep(repair.text);
    if (repaired === "invalid") {
    const reason: FailureReason = repair.text === first.text ? "poison" : "invalid_model_output";
    return { ok: false, result: stop(ports, input, counters, completed, reason) };
    }
    return { ok: true, step: repaired };
    }
    async function readWithRetry(
    ports: GuardrailPorts,
    input: RunInput,
    budget: GuardrailBudget,
    counters: Counters,
    completed: Set<string>,
    operationId: string,
    ): Promise<{ ok: true } | { ok: false; result: RunResult }> {
    let attempt = 0;
    while (attempt < budget.maxReadAttempts) {
    if (circuitOpen(ports.circuit(operationId), ports.now())) {
    return { ok: false, result: stop(ports, input, counters, completed, "circuit_open") };
    }
    if (!budgetAllows(budget, counters, ports.now(), "connector")) {
    return { ok: false, result: stop(ports, input, counters, completed, "budget_exceeded") };
    }
    counters.steps += 1;
    counters.connectorCalls += 1;
    const response = await ports.read(operationId);
    if (response.ok) {
    ports.setCircuit(operationId, recordSuccess());
    return { ok: true };
    }
    if (response.reason === "not_found") {
    return { ok: false, result: stop(ports, input, counters, completed, "not_found") };
    }
    ports.setCircuit(operationId, recordFailure(ports.circuit(operationId), ports.now()));
    attempt += 1;
    if (attempt >= budget.maxReadAttempts || (response.reason !== "timeout" && response.reason !== "rate_limited" && response.reason !== "upstream")) {
    return { ok: false, result: stop(ports, input, counters, completed, response.reason === "upstream" ? "upstream" : response.reason) };
    }
    await ports.sleep(backoffMs(attempt, ports.random()));
    }
    return { ok: false, result: stop(ports, input, counters, completed, "upstream") };
    }
    function snapshot(
    input: RunInput,
    counters: Counters,
    completed: Set<string>,
    status: Checkpoint["status"],
    reason: Checkpoint["reason"],
    ticketId?: string,
    ): Checkpoint {
    return {
    workflowRunId: input.workflowRunId,
    tenantId: input.tenantId,
    completedSteps: [...completed],
    ticketId,
    status,
    reason,
    counters,
    policyVersion: POLICY_VERSION,
    };
    }
    function stop(
    ports: GuardrailPorts,
    input: RunInput,
    counters: Counters,
    completed: Set<string>,
    reason: FailureReason,
    ticketId?: string,
    ): RunResult {
    const checkpoint = snapshot(input, counters, completed, "terminal", reason, ticketId);
    ports.save(checkpoint);
    return { ok: false, reason, checkpoint };
    }

    packages/guardrails/src/runner.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { runGuardedStep, type GuardrailPorts, type Checkpoint } from "./runner.js";
    import type { CircuitState } from "./circuit.js";
    function world(script: Array<{ text: string }>, reads: Array<{ ok: true } | { ok: false; reason: "timeout" | "rate_limited" | "not_found" | "upstream" }>) {
    const saved: Checkpoint[] = [];
    const store = new Map<string, Checkpoint>();
    const circuits = new Map<string, CircuitState>();
    let modelCalls = 0;
    let readCalls = 0;
    let proposeCalls = 0;
    const ports: GuardrailPorts = {
    async model() {
    const next = script[modelCalls] ?? script[script.length - 1];
    modelCalls += 1;
    return next;
    },
    async read() {
    const next = reads[Math.min(readCalls, reads.length - 1)];
    readCalls += 1;
    return next;
    },
    async propose(_operationId, _key) {
    proposeCalls += 1;
    return { ok: true, ticketId: "tkt_01" };
    },
    save(checkpoint) {
    saved.push(checkpoint);
    store.set(checkpoint.workflowRunId, checkpoint);
    },
    load(_tenantId, workflowRunId) {
    return store.get(workflowRunId);
    },
    circuit(operationId) {
    return circuits.get(operationId);
    },
    setCircuit(operationId, state) {
    circuits.set(operationId, state);
    },
    async sleep() {
    return undefined;
    },
    random() {
    return 0;
    },
    now() {
    return 1_700_000_000_000;
    },
    };
    return {
    ports,
    counts: () => ({ modelCalls, readCalls, proposeCalls }),
    saved,
    };
    }
    const input = {
    tenantId: "northwind",
    workflowRunId: "run_reminder_01",
    featureEnabled: true,
    allowedTools: ["enrollment.lookup", "messaging.email.send"],
    idempotencyKey: "idem_mail_01",
    };
    test("a denied refund tool never proposes mail", async () => {
    const fixture = world([{ text: JSON.stringify({ tool: "billing.refund.create", args: { invoiceId: "inv_priya_1" } }) }], [{ ok: true }]);
    const result = await runGuardedStep(fixture.ports, input);
    assert.equal(result.ok, false);
    if (result.ok) return;
    assert.equal(result.reason, "tool_denied");
    assert.equal(fixture.counts().proposeCalls, 0);
    });
    test("a read timeout retries once and then proposes a single ticket", async () => {
    const fixture = world(
    [
    { text: JSON.stringify({ tool: "enrollment.lookup", args: { learnerId: "lrn_priya" } }) },
    { text: JSON.stringify({ done: true, templateId: "cohort_reminder_v1" }) },
    ],
    [{ ok: false, reason: "timeout" }, { ok: true }],
    );
    const result = await runGuardedStep(fixture.ports, input);
    assert.equal(result.ok, true);
    if (!result.ok) return;
    assert.equal(result.status, "awaiting_approval");
    assert.equal(fixture.counts().readCalls, 2);
    assert.equal(fixture.counts().proposeCalls, 1);
    assert.equal(JSON.stringify(result.checkpoint).includes("idem_mail_01") || result.checkpoint.ticketId === "tkt_01", true);
    });
    test("resume of a paused run does not propose again", async () => {
    const fixture = world(
    [
    { text: JSON.stringify({ tool: "enrollment.lookup", args: {} }) },
    { text: JSON.stringify({ done: true, templateId: "cohort_reminder_v1" }) },
    ],
    [{ ok: true }],
    );
    await runGuardedStep(fixture.ports, input);
    const second = await runGuardedStep(fixture.ports, input);
    assert.equal(second.ok, true);
    assert.equal(fixture.counts().proposeCalls, 1);
    assert.equal(fixture.counts().modelCalls, 2);
    });

    The refund test is the allow-list. The timeout test is the read retry. The resume test is the checkpoint: a second call sees paused and does not create another ticket. The checkpoint JSON in the success path has a ticket id and no prompt field.

    Run:

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/runner.test.ts

    sleep is a stub. No provider key is read.

    Architecture Diagram

    text
    Route
    |
    v
    runGuardedStep
    |
    +--> feature flag
    +--> checkpoint load (skip completed, stop if terminal or paused)
    +--> budgetAllows before each port
    +--> circuitOpen per operation
    +--> model + one repair
    +--> read retries for timeout, rate limit, upstream
    +--> propose once --> awaiting_approval
    |
    v
    Checkpoint (ids, counters, policy version)

    Retry split:

    text
    read timeout --> another attempt, same operation, counts against budget
    write timeout --> execution_unknown in Lesson 45, same idempotency key
    repeated invalid --> poison, terminal checkpoint

    Real-Time Enterprise Example

    In production the checkpoint table is keyed by tenant and workflow run id. Northwind's reminder policy uses LAB_BUDGET until finance replaces the numbers. The enrollment adapter returns timeout on a slow replica. The runner retries once, then drafts, then proposes. The lead sees one ticket. A billing incident opens the circuit after three upstream failures on billing.invoice.read. Reminder runs that only need enrollment continue. Runs that need billing fail fast with circuit_open.

    The kill switch drops featureEnabled. New model calls stop. A ticket already in approved can still be executed by the Lesson 45 route, which is not this runner. The runbook says that in the first line so nobody expects the flag to un-send mail or un-approve a refund.

    Challenge: the provider is down, the step budget is tight, and the user double-clicks Resume. The paused checkpoint absorbs the double-click and does not call the model. The read retry uses at most maxReadAttempts and still counts toward maxConnectorCalls. You do not add a second model vendor inside the timeout branch unless that vendor is in allowedProviderIds. You do not clear idempotencyKey to "help" the mail send succeed. If the circuit is open, the panel shows circuit_open and the time it will half-open. Staff can wait or start a new run id later. They cannot mark the circuit closed from the browser.

    Performance Optimization

    The runner's job is to do less, not to parallelize the planner. Model calls are the expensive steps. Cap them at two, including repair. Connector retries are capped and jittered so a 429 does not become a synchronized herd. sleep must be bounded by the remaining wall clock. If backoff would cross maxWallMs, stop with budget_exceeded instead of sleeping past the budget.

    Do not hold a request thread across human approval. Persist paused and return. Resume is a new invocation that hits the checkpoint and returns immediately when still paused. That keeps the API process free while a lead is in a meeting.

    Circuit state should be process-wide or in Redis, not a per-request object that forgets failures. The lab keeps it on the port. Production shares it so one Node worker's timeouts protect the others.

    Skip work you already completed. Re-reading enrollment after a resume is how you blow the connector budget during an outage. The checkpoint is the performance control as well as the safety control.

    Logs of each step should be counters and reasons. High-cardinality prompt text in your metrics backend will cost more than the model call you were trying to debug.

    Security

    • Kill switch. The flag is server-side. The body cannot enable a run.
    • Tool allow-list. A run that drafts mail cannot call refund. tool_denied happens before propose.
    • Schema. Extra keys and non-JSON stop the step. One repair, then poison.
    • Idempotency. The runner receives the key and does not rotate it.
    • Checkpoint privacy. No utterance, no secret handle, no upstream body.
    • Tenant. Load and save include tenantId. A run id from another tenant is a miss, and the runner starts nothing with the caller's tenant mixed into the other row.
    • Injection. Tool names are compared to a set. The model does not receive a shell.
    • Cost as a control. Budgets are a security limit when an attacker can trigger runs. Unbounded agents are an unrestricted resource consumption issue in the OWASP API list.
    • Circuit. Fast-fail reduces load on a dependency that is already failing. It is not an authorization bypass.
    • Approval. This runner proposes. It does not approve. Lesson 45 remains the only commit path.

    Common Mistakes

    1. Retrying a refund with a new idempotency key. Symptom: two charges. Cause: the catch block generated a UUID. Fix: writes use the ticket key or they do not retry.
    2. Unlimited tool loops. Symptom: the bill grows while the panel spins. Cause: the planner was trusted to stop. Fix: maxSteps and maxModelCalls.
    3. Retrying not_found. Symptom: a broader query appears on attempt two. Cause: empty was treated as transient. Fix: not_found is terminal for that step.
    4. Opening a second ticket on resume. Symptom: two emails wait for approval. Cause: propose ran again. Fix: paused checkpoints return immediately.
    5. Repairing forever. Symptom: three model calls for one bad brace. Cause: repair was a loop. Fix: one repair, then invalid_model_output or poison.
    6. Logging the prompt on the checkpoint. Symptom: learner text in the job database. Cause: "the replayer might need it." Fix: store step names and ticket ids.
    7. Letting the client close the circuit. Symptom: a button bypasses an outage control. Cause: circuit state was a request field. Fix: only the runner updates the breaker from port results.
    8. Counting only successful calls against the budget. Symptom: timeouts are free. Cause: the counter sat after the success branch. Fix: increment before the call.
    9. Sleeping the web request for the whole backoff. Symptom: the platform kills the process and the checkpoint never saves. Cause: the route waited in-process for a person. Fix: pause and return.
    10. Using the kill switch to hide an approved effect. Symptom: on-call thinks mail will not send, and the executor still sends. Cause: the flag and the ticket were conflated. Fix: document that approved tickets still execute.
    11. Falling back to a forbidden model vendor. Symptom: usage shows a vendor the tenant blocked. Cause: the timeout handler had a global default. Fix: unavailable stays unavailable.
    12. Marking poison runs resumable. Symptom: every resume pays for the same bad JSON. Fix: terminal checkpoint. A new attempt is a new run id.

    Best Practices

    1. Put budgets in a versioned policy constant.
    2. Check the budget before the port call.
    3. Count failures and retries as steps.
    4. Allow one schema repair.
    5. Treat identical invalid output as poison.
    6. Retry reads only for timeout, rate limit, and upstream.
    7. Do not retry not_found or invalid_args.
    8. Keep write idempotency keys stable.
    9. Resume execution_unknown through Lesson 45.
    10. Propose writes once, then pause.
    11. Open a circuit after a small failure threshold.
    12. Half-open with a single trial.
    13. Store checkpoints without prompts or secrets.
    14. Skip completed steps on resume.
    15. Make terminal runs stay terminal.
    16. Keep the feature flag as a spend kill switch.
    17. Leave already-approved tickets on the Lesson 45 path.
    18. Inject clock, sleep, and random so tests do not flake.
    19. Share circuit state across workers.
    20. Return typed reasons to the panel.
    21. Keep tool allow-lists on the run, not in the prompt alone.
    22. Test denied tools, read retry, and double resume.
    23. Document agent-guardrails-v1 next to the budget table.
    24. Start a new run id when a human wants a clean planner pass.

    Interview Questions & Answers

    Beginner

    1. What is the difference between a guardrail and a prompt instruction?
      A prompt asks the model to behave. A guardrail is code that refuses to call the tool when the name is not allowed or the budget is spent. The run remains safe when the model ignores the prompt.

    2. Why retry a read and not a refund?
      A read has no extra effect when it runs twice. A refund does. If a write timed out, you resume with the original idempotency key so the vendor can deduplicate. A new key looks like a new refund.

    3. What does the checkpoint remember?
      Completed step names, counters, tenant, run id, optional ticket id, and status. It does not remember the prompt or the API token.

    Intermediate

    1. How does the circuit breaker interact with retries?
      Retries handle a single blip. The circuit handles a broken dependency. After the failure threshold, new calls fail fast until the open interval passes, then one trial is allowed. That trial's failure opens the circuit again.

    2. What is a poison output?
      The model returned invalid JSON, the repair call returned the same invalid JSON, and another resume would waste the same calls. The run is terminal. A person starts a new run id if they still want the workflow.

    3. Why does a paused resume skip the model?
      The proposal already exists as a ticket. Calling the model again can change the plan and create a second ticket. The lead is the next actor. The runner waits.

    Senior

    1. How do you test recovery without a model account?
      Script the model port with strings. Script the read port with timeout then success. Stub sleep. Assert call counts, tool_denied with zero proposes, and a second runGuardedStep that does not propose again. Contract-test real adapters separately.

    2. Where should execution_unknown be retried?
      In executeApproved, with the ticket's key, not in a generic HTTP retry helper. The runner may call that function once when the checkpoint says the ticket is unknown. It must not call propose again.

    Architect

    1. How do you tune budgets per tenant?
      Store overrides next to the tenant policy, with agent-guardrails-v1 as the default. A higher cap is a change you can audit. The runner reads the override at start and copies the numbers onto the checkpoint so a later config edit does not rewrite history mid-flight.

    2. What should the kill switch stop?
      New model calls and new connector calls in this runner. It should not delete tickets or block a lead who is executing an already approved effect. Spend stops. A decided refund can still complete, and the audit still explains it.

    3. How do you avoid a thundering herd when a circuit half-opens?
      Allow one trial per operation per interval, shared across workers. Jitter the remaining retries. Do not let every paused run wake on the same cron second. A queue with a concurrency limit is the production form of the lab's single caller.

    4. How does this lesson relate to evaluation?
      Each reason code is a label. Fixtures for denied tools and valid terminal JSON give you false-allow and false-refuse rates without a vendor. Online, you chart budget_exceeded, poison, and circuit_open per tenant. A spike is a product signal, not only an outage signal.

    Knowledge Check

    1. What problem does this capability solve?

    It stops agent runs from looping, double-committing, or calling tools outside the run's allow-list, and it gives each failure a typed outcome: retry a read, pause on a ticket, open a circuit, or stop.

    2. What alternatives exist, and when would you choose each?

    A single request with one model call needs timeouts and a schema, not a checkpoint. A multi-step agent needs this runner. A workflow engine can host the same rules. The rules matter more than the product name. Unbounded retries fit a demo and will not fit a billable vendor.

    3. Which data, identity, and trust boundaries matter?

    The server owns the budget, the tool allow-list, the flag, and the idempotency key. The model owns neither the tool set nor the resume decision. Checkpoints omit prompts. Circuits are not client-controlled. Approval stays in Lesson 45.

    4. What can fail, and how should the system respond?

    Disabled flag, budget, circuit, denied tool, invalid or poison output, timeout, rate limit, and upstream each return a reason and a checkpoint. Reads retry inside the attempt cap. Writes pause or resume on the same key. not_found does not retry.

    5. How would you test quality, security, performance, and cost?

    Unit tests assert call counts for retry, deny, and double resume. Security tests assert a refund tool on a mail run never proposes. Performance tests assert completed steps are skipped. Cost tests assert model calls stay within maxModelCalls and a paused resume adds zero.

    Practical Exercise

    Implement packages/guardrails/src/ and run the tests. Add a poison case: both model responses are the string not-json, and assert reason poison with a terminal checkpoint. Write three sentences on how your route will return 202 when the result is awaiting_approval instead of sleeping on the web request.

    Deliverable and Rubric

    Submit the failure matrix, the guardrail package, the test output, the budget table you would put in a runbook, and the list of fields excluded from the checkpoint.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Policy version agent-guardrails-v1 is on the checkpoint.
    • Budgets are checked before port calls.
    • Attempts count toward the budget.
    • Reads retry with a cap. not_found does not.
    • Writes do not rotate idempotency keys.
    • Paused runs do not propose twice.
    • Poison and other terminal reasons stay terminal.
    • Circuits are server state.
    • Checkpoints omit prompts and secrets.
    • The kill switch stops new model and connector steps.
    • The runner does not approve tickets.
    • Tests cover deny, retry, and resume.

    Key Takeaways

    1. Guardrails are code, not prompt wishes.
    2. agent-guardrails-v1 caps steps, model calls, connector calls, and wall time.
    3. Count the call before you make it.
    4. One repair, then invalid or poison.
    5. Retry idempotent reads only.
    6. Keep write keys stable and resume them through Lesson 45.
    7. Propose once and pause for a person.
    8. Circuits fail fast after repeated upstream errors.
    9. Checkpoints store progress, not prompts.
    10. A paused or terminal run does not start over.
    11. The kill switch stops new spend.
    12. Approved effects remain on the approval executor.
    13. Tool allow-lists are per run.
    14. not_found is not a transient error.
    15. Lesson 47 will supply the workflow. This runner supplies the limits.

    Summary

    Lesson 46 makes TechLearningPro's agent runs stop on purpose. Budgets bound the bill, schemas bound the model, circuits bound a sick dependency, and checkpoints bound recovery so a retry is not a second email. Reads can try again. Writes keep the key Lesson 45 already defined. The next lesson is the workflow those limits were built to host.

    Next Lesson Preview

    Next is AI Workflow Automation Capstone. You will compose the connector, the approval ticket, and this runner into one TechLearningPro operations workflow: find stalled learners, draft a reminder, wait for a lead, send once, and recover without a second ticket. The guardrail constants stay in this package. The capstone should call them, not reimplement backoff in a route.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.