Claude Certified Developer · प्रोफेसनल

Module 6: Debugging and incident response

Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.

Practice this module

On this page

Study notes, not official course material. Our take on official course 6 (isolate multi-agent failures, lead incident response). Facts checked 2026-11-25. The incident in this module is a lab drill on fictional data.

The video opens at 02:14 with a page: "SEV2 · duplicate refunds · tenant birch". Five agents touched the affected tickets, and every one of them reports that it did its job. This module is the first 30 minutes of that incident, then the next morning: contain it, communicate, find the failing hop, prove the root cause with replay, fix it, undo the damage, and make sure it can't come back quietly.

What you'll be able to do

  • Run the first 30 minutes of an incident in an LLM system: roles, containment, the first status note.

  • Contain without guessing: a kill switch per risky tool, pinned prompt and model versions, and a draft-only mode for one tenant.

  • Start from a run id and follow the trace hop by hop to the step where the system went wrong.

  • Replay a recorded run with one variable changed at a time, often enough to tell a real bug from normal model variance.

  • Fix the root cause and add a second line of defence.

  • Use the audit log to find and undo customer impact.

  • Read the API's own failure signals (status codes, request_id, stop_reason, cache usage fields) and know what each one rules in or out.

  • Write a blameless review whose actions have owners and dates, and turn the incident into an eval case and an alert.

1. Why LLM incidents feel different

Classic incidents usually announce themselves: errors spike, a service is down, a stack trace points at a line. LLM-system incidents often don't:

  • Everything is 200 OK. The duplicate refunds in this drill produced no errors at all. Each API call succeeded; each agent returned valid JSON.

  • The same input can give different outputs. A failure that happens 3 times in 10 can look like "fixed" after one clean run.

  • The failure is spread over hops. Triage, billing, reviewer, refund tool, payment provider: the visible symptom (a second refund) is two or three steps away from the cause.

  • Every component has a plausible story. An agent's own summary of what it did ("I checked for prior refunds") is model output, not evidence.

So the method leans on three things built in earlier modules: traces (Module 3) to see what actually happened, audit logs (Module 5) to see what changed in the world, and replay (this module) to test explanations instead of arguing about them.

2. Roles: three hats, even when you're alone

RoleJobDoesn't do
Incident leadOwns decisions: severity, containment, when to escalate, when it's over. Keeps the timeline.Debug deep in the code.
FixerInvestigates and changes things, but only what the lead agreed to.Talk to customers.
CommsSends status notes on a fixed cadence to stakeholders and support staff.Speculate about cause.

On a small team, or at 02:14, you'll often be all three. Wear the hats on purpose: open a timeline document first, set a timer for the next status note, and write down each decision before you act on it. If a second person joins, hand them the fixer hat and keep the lead hat yourself; a lead who is also typing SQL stops seeing the whole incident.

Severity is about customer impact, not about how interesting the bug is. Money leaving the business incorrectly, on a live tenant, and still happening, is a high severity even if only one tenant is affected.

3. Contain first, diagnose second

The most common mistake in the first ten minutes is trying to understand the bug while it keeps happening. Each minute of debugging is another batch of duplicate refunds. Stop the bleeding first, with controls you built before you needed them.

Three containment levers, from narrowest to widest:

  1. Kill switch per risky tool. A feature flag that turns one tool off without a deploy. When it's off, the tool doesn't call the payment API; it returns an error result that tells the model what to do instead.

  2. Pin the last known good versions. Prompt version, model id and handoff-contract version are deployable values (Module 3), so "go back to yesterday's" is a flag change, not a code revert.

  3. Draft-only mode for one tenant. The agent still reads tickets and writes replies and refund requests, but nothing is sent or executed until a person approves it. Customers still get help, slower.

A minimal version of the flags and the tool dispatch:

TypeScript
// flags.ts: read from your flag store; cached for a few seconds at most
export type Flags = {
  disabledTools: Set<string>;     // e.g. "issue_refund"
  draftOnlyTenants: Set<string>;  // e.g. "birch"
  pinned: { promptVersion?: string; model?: string; contractVersion?: string };
};

export async function runTool(
  flags: Flags,
  tenantId: string,
  call: { id: string; name: string; input: unknown },
) {
  if (flags.disabledTools.has(call.name)) {
    return {
      type: "tool_result" as const,
      tool_use_id: call.id,
      is_error: true,
      content: `${call.name} is paused by an operator. Do not retry it. Tell the customer a person will follow up, then call escalate.`,
    };
  }
  if (flags.draftOnlyTenants.has(tenantId) && SIDE_EFFECT_TOOLS.has(call.name)) {
    await queueForApproval(tenantId, call); // a person approves in the support console
    return { type: "tool_result" as const, tool_use_id: call.id, content: "Queued for human approval." };
  }
  return execute(tenantId, call);
}

Note what the paused tool returns: a tool_result with is_error: true and plain instructions. Don't silently drop the call (the model will retry or invent a result), and don't throw an exception that kills the run halfway (that can leave the ticket in a worse state).

The first status note goes out within minutes, from a template, and says only what you know:

Text
[SEV2] Duplicate refunds, tenant birch. Status: contained, investigating.
Impact: some birch tickets since about 22:00 received two refunds.
Action taken: automatic refunds paused for all tenants; birch is in draft-only mode
(replies are reviewed by a person before sending).
Next update: 02:45 or sooner.

No guesses about cause, no promises about timing, a fixed time for the next update. Then keep the cadence even when there's nothing new; "still investigating, no change in impact" is useful information.

4. Find the hop: start from the run id

With the bleeding stopped, pick one affected ticket and get its run id from the audit row of the second refund. Open that run's trace (Module 3). A trace of one run looks like this:

Text
run 7f3c…  ticket birch-T-1182                                   total 41.2s
├─ agent.triage          model=claude-sonnet-5-5  prompt=v12      1.9s  → category=billing
├─ agent.billing         model=claude-opus-5-5    prompt=v31      9.7s
│   ├─ tool.get_order    order=B-2290  status=refunded             0.2s
│   └─ handoff → reviewer  contract=v3  {order_id, amount_cents, summary}
├─ agent.reviewer        model=claude-opus-5-5    prompt=v8       6.1s  → approve
└─ tool.issue_refund     order=B-2290  amount=4900               0.8s  → ok (2nd refund)

Read it hop by hop and ask the same question at each one: did this step have what it needed, and did it pass on what the next step needed?

  • get_order returned status=refunded. So billing knew the order had already been refunded.

  • The handoff to the reviewer used contract v3, and the payload has no already_refunded field.

  • The reviewer approved. Given what it was sent, approving was reasonable.

That points at the handoff, not at any agent's "judgement". Checking the deploy log: contract v3 shipped at 21:52, eight minutes before the first duplicate. In v3 the billing side renamed already_refunded to refund_status; the reviewer's schema still expected already_refunded, marked it optional with a default of false, and so read every order as "not yet refunded".

This is a hypothesis, not yet a root cause. A deploy eight minutes earlier is suggestive; it isn't proof. Replay turns it into proof.

Failure case: asking the agents

A tempting shortcut is to ask each agent "did you check for prior refunds?". Each will say yes, convincingly, in an answer generated now about a run it can't see. Evidence comes from the trace and the audit log, never from the model's account of itself.

5. Bisect with replay

Replay means running a recorded run again with the same inputs: the same ticket, the same retrieved documents, the same tool responses, while you change exactly one thing. Then you see which change moves the failure.

What a recording needs

For each run, store (under the access controls from Module 3, because this includes customer text):

  • the ticket input and the tenant,

  • each model request's parameters (model id, prompt version, contract version, tools list),

  • each tool call's input and response, so replay can serve the same responses back.

Tools in replay must not touch the world

The single most important rule of replay: tools return recorded responses, and side-effecting tools never run for real. A replay that calls the live issue_refund turns your debugging session into a third refund.

TypeScript
// replay.ts: a sketch; loadRun, runAgents and fixture lookup come from the lab repo
const run = await loadRun(runId); // recorded input, model params, tool responses

function replayTools(run: RecordedRun) {
  return {
    async execute(call: ToolCall) {
      const recorded = run.toolResponses.find((t) => t.name === call.name && sameArgs(t.input, call.input));
      if (SIDE_EFFECT_TOOLS.has(call.name)) return { ok: true, simulated: true }; // record the intent only
      if (!recorded) throw new Error(`no recording for ${call.name}`);      // fail loudly, don't go live
      return recorded.output;
    },
  };
}

async function failureRate(override: Partial<RunConfig>, n = 10) {
  let failures = 0;
  for (let i = 0; i < n; i++) {
    const out = await runAgents(run.input, { ...run.config, ...override, tools: replayTools(run) });
    if (out.refundIntents.length > 0 && run.wasAlreadyRefunded) failures++; // the bug: approving a second refund
  }
  return `${failures}/${n}`;
}

console.log("as recorded     ", await failureRate({}));
console.log("contract=v2     ", await failureRate({ contractVersion: "v2" }));
console.log("prompt=v30      ", await failureRate({ billingPrompt: "v30" }));
console.log("model=sonnet-5-5", await failureRate({ reviewerModel: "claude-sonnet-5-5" }));

Model calls in replay are live (that's how you measure variance); tools are fixtures. If a tool call's arguments don't match any recording, the replay stops instead of quietly calling production.

Run each variant several times

One replay run tells you almost nothing about a system that can vary. Run each variant N times and compare failure rates:

Variant (one change from the recording)Failures
as recorded (contract v3, prompt v31, current models)10/10
contract v20/10
billing prompt v3010/10
reviewer on a different model10/10
tool fixture: get_order returns status=open0/10

Only the contract version (and, as a sanity check, the order status) moves the failure rate. That's the root cause, proven: with v2 the reviewer gets already_refunded: true and rejects; with v3 it never sees it.

How many runs is enough? 10/10 against 0/10 is unambiguous. 3/10 against 2/10 is not; that gap is well within normal variation for 10 runs. When the difference is small, run more (50 or 100) before concluding anything, or look for a variable that moves the rate decisively. Don't name a root cause on a difference you could get by chance.

Failure case: it's the model, not the code

The video's hard-mode drill has a second incident where replay shows the as recorded variant failing 2/10 and every single-variable change also failing about 2/10. Nothing you change moves it. That pattern says the behaviour is model variance on this input, not a code bug. The fix is different: add a deterministic check in code (here: refuse to approve when get_order says the order is refunded, regardless of what the reviewer concludes), and add the input to the eval set so the rate is tracked. Replay told you which kind of fix you need.

6. Fix the cause, and add a second line of defence

The cause: a safety-relevant field was optional with a fail-open default, and the contract changed on one side only.

Fix 1, the contract. One shared schema, used by producer and consumer, and the field becomes required with no default:

TypeScript
import { z } from "zod";

// contracts/billing-to-reviewer.ts: imported by BOTH agents' code
export const BillingHandoff = z
  .object({
    contract_version: z.literal("v4"),
    ticket_id: z.string(),
    order_id: z.string(),
    amount_cents: z.number().int().positive(),
    already_refunded: z.boolean(), // required; no .default(false)
    summary: z.string().max(2000),
  })
  .strict(); // unknown keys are an error, so a renamed field fails loudly

export function parseHandoff(raw: unknown) {
  const r = BillingHandoff.safeParse(raw);
  if (!r.success) throw new HandoffError(r.error.message); // the run stops and escalates; it never "assumes false"
  return r.data;
}

The producer validates before sending and the consumer validates on receipt. A renamed or missing field now stops the run with a clear error, rather than quietly turning into false.

Fix 2, the contract test. In CI, feed recorded billing outputs through the reviewer's parser. If someone changes one side again, the build fails before deploy.

Fix 3, the second line of defence. The refund tool's idempotency key (Module 1: refund:<tenant>:<ticket>:<order>) and a check in code that refuses a refund for an order whose status is already refunded. Even if a future contract bug sneaks through, the money path has its own guard. One defence failing silently caused this incident; two independent ones make the next one much less likely.

Verify the fix with the same replay: contract v4, 0/10 failures; the old v3 recording now fails validation instead of approving.

7. Undo the customer impact

Fixing the code doesn't give back the money. The audit log (Module 5) records every tool call with tenant, ticket, order, run id and agent identity, so the damage list is a query, not a guess:

SQL
SELECT tenant_id, ticket_id, order_id,
       count(*)              AS refunds,
       array_agg(refund_id)  AS refund_ids,
       min(created_at)       AS first_at
  FROM audit_log
 WHERE action = 'issue_refund'
   AND outcome = 'ok'
   AND created_at >= '2026-11-24 21:52+00'   -- contract v3 deploy
 GROUP BY tenant_id, ticket_id, order_id
HAVING count(*) > 1
 ORDER BY first_at;

Then a person decides what to do with each row: reverse it, keep it as goodwill, or contact the customer first. That depends on the tenant's policy and the amounts, and an automatic reversal of real customers' money is itself a risky action. Draft the customer messages from a template and have support review them.

Don't ask a model to work out which refunds were duplicates from conversation transcripts. The audit log is exact; transcripts are text about what an agent intended.

8. The API's own signals, and what they rule out

Not every incident is in your own code. When the Claude API is involved, its responses tell you a lot, if you log them:

SignalWhat it meansWhat to do
400 invalid_request_errorYour request is malformed or uses something this model doesn't acceptFix the request; retrying won't help. Often follows a model or SDK change.
401 / 403 permission_errorCredential problem / not allowed for this credentialCheck keys, workspace, access.
404 not_found_errorWrong endpoint, or a model id your organisation can't useCheck the model id in config after any model switch. Don't retry.
413 request_too_largeRequest over the size limitShrink context (often a runaway tool output).
429 rate_limit_errorRate limited; honour retry-after. A monthly spend-cap 429 has no retry-afterBack off; for the spend cap, page a person.
500 api_error, 529 overloaded_errorProvider-side problem or overloadRetry with backoff inside your time budget; check the status page.
200 with stop_reason: "refusal"The model's safety classifiers declined; stop_details.category says which kindTreat as no answer, escalate, chart the refusal rate by tenant. A jump usually follows an input change (new docs, a new prompt).
200 with stop_reason: "max_tokens"Output cut offDon't act on a half answer.
cache_read_input_tokens drops to ~0Prompt cache stopped hitting; cost and latency rise with no errorsDiff two consecutive request bodies to find the first changed byte (Module 8).

Log the request_id. Every API error response carries one. Put it, together with your run id, model id and timestamp, on the span. When you need to ask the provider about a specific failed request, the request id is what lets them find it. Don't log your API key or full prompts in normal logs.

A newer failure: editing history the model has thought about

On the newest models (Claude Opus 5.5 among them), thinking blocks are bound to the conversation they came from. A harness that rewrites earlier messages (trimming old tool results in place, changing an earlier system prompt, reordering tools) can start getting a 400 whose message says a thinking block's signature is invalid because it is "bound to a different conversation". Two things to know for debugging:

  • Retrying the same body never clears it. It isn't transient; something in the history changed. Find the edit (diff the request bodies as above).

  • The lasting fix is in the harness: append to the conversation instead of editing it, and use the API's own context-management features for trimming. The error message also offers emergency workarounds (remove the named block, or a beta setting that drops mismatched blocks). Use them to restore service, not as the design.

Failure case: the cost incident with no errors

After a deploy, cost per ticket doubles and p95 latency rises by a second. No errors, no alerts except the cost one. The traces show cache_read_input_tokens near zero since the deploy. Diffing two consecutive requests shows a new Request id: … line near the top of the system prompt, added for "debugging". Moving it to the end of the last user message restores cache reads. This is an incident too: same method (contain by rolling back the prompt version, find the change, fix, add a check that a second identical request reads from cache).

9. The blameless review

Within a few days, write the review. "Blameless" doesn't mean "nobody is responsible for fixing things". It means you describe the conditions that made the mistake easy, because the next person in the same conditions would make it too.

A good review has:

  • A timeline from evidence: deploy at 21:52, first duplicate at 22:00, alert at 02:14 (why four hours? that's a finding), contained at 02:21, root cause proven by replay at 03:40.

  • Contributing factors, not a culprit:

    • no contract test between billing and reviewer,

    • a safety-relevant field was optional with a default of false,

    • the reviewer trusted upstream data instead of checking order status itself,

    • the refund tool had no "already refunded" guard,

    • the alert was on payment-provider errors, not on refunds per ticket, so it fired late.

  • Actions, each with an owner and a date:

ActionOwnerDue
Shared BillingHandoff schema, required field, .strict()billing team2026-11-27
Contract test in CI on recorded payloadsplatform2026-11-28
Refund tool refuses already-refunded ordersbilling team2026-11-26
Alert: more than one refund per ticket in 24 hon-call lead2026-11-26
Add the recorded run as an eval case (Module 4)evals owner2026-11-27
Drill: re-run this incident in a staging game dayincident lead2026-12-10

Rewrite "Engineer X shipped v3 without testing" as "contract changes could ship without a test that both sides agree". The first sentence teaches people to hide mistakes; the second fixes the system.

Close the loop. The incident's recorded run goes into the eval set with its expected behaviour (reject the second refund), so the release gate from Module 4 will fail any future change that brings it back. The new alert makes the next one visible in minutes instead of hours.

Trade-offs

  • Broad vs narrow containment. Pausing refunds for everyone is safe and fast but hurts tenants who weren't affected; birch-only draft mode is kinder but assumes you know the blast radius. Start broad when you're unsure, then narrow with evidence.

  • Replay fidelity vs safety. Live model calls show real variance; fixture tools keep replay safe. A full live-tools replay in an isolated staging copy is more realistic but costs more to build and keep in sync.

  • N runs vs time. Ten runs per variant is quick and usually enough for a clear signal; small differences need 50–100, which costs money and minutes. Decide by how close the rates are.

  • Recording everything vs privacy. Replay needs customer text and tool outputs. Keep recordings in an access-controlled store with retention limits, and redact what replay doesn't need.

  • Strict contracts vs flexibility. .strict() breaks loudly on harmless additions too; for safety-relevant handoffs, loud is right.

Common mistakes

  • Debugging while the damage continues, instead of reaching for the kill switch.

  • Having no kill switch, so containment means an emergency deploy.

  • Status notes that guess at the cause, or that stop when there's nothing new.

  • Asking agents what they did instead of reading the trace and the audit log.

  • Replaying with live side-effecting tools.

  • Declaring a root cause from one replay run, or from 3/10 against 2/10.

  • Changing two variables at once in a replay, so you can't tell which one mattered.

  • Fixing only the agent that "decided wrong", and not the contract that fed it bad data.

  • Optional fields with fail-open defaults on anything safety-relevant.

  • Reversing customer money automatically without a person reviewing the list.

  • Retrying 400s, including the thinking-signature 400; it will fail the same way.

  • Not logging request_id, then having no way to point at the failing request.

  • A postmortem that names a person, or whose actions have no owner or date.

Remember

  • Contain first: kill switch per risky tool, pinned versions, draft-only mode, then a status note on a fixed cadence.

  • Evidence beats stories. Start from the run id; follow the trace hop by hop; check each handoff against its contract.

  • Replay with recorded inputs and fixture tools. Change one thing at a time. Run each variant enough times to beat the noise.

  • Fix the cause and add a second, independent defence on the money path.

  • The audit log tells you exactly who was affected; a person decides how to make it right.

  • Blameless review, actions with owners and dates, and the incident becomes an eval case and an alert.

Check before relying on it

  • Thinking-block binding on claude-opus-5-5 and the "bound to a different conversation" 400: on 2026-11-25 enforcement of this history-editing check depended on the account (accounts created on or after 2026-08-31 were enforced) and on the model. The workaround setting (prefix_mismatch_behavior: "drop_block") was a beta (thinking-binding-controls-2026-08-01). Check the current docs for your account and model.

  • Cache diagnostics (the API comparing two requests and naming where they diverged) was a beta on the Claude API (cache-diagnosis-2026-04-07), and it must be sent on every request to work. Payload diffing works everywhere.

  • The error list (types and codes, including the spend-cap 429 with no retry-after, and 404 for a model your organisation can't use) matches the docs on 2026-11-25; check for new codes.

  • stop_details.category values for refusals are an open set and differ by model.

  • The replay harness, flags.ts and the audit-log schema are our course code, not an Anthropic feature.

↑ ↓ सार्नुहोस् · ↵ छान्नुहोस् · esc बन्द