Home › Study guides › CCDV-F › Domain 2 › Lesson 2.4
CCDV-F · Domain 2 · 20% of the exam · Lesson 2.4 · 22 min read Updated for the December 7, 2026 exam guide (v1.1)
Integration resilience: terminal events, error classes and file ingestion
Diagnose a failing Claude integration from its code and error output, then fix streaming end handling, retries by error class and Files API ingestion.
Written against skill 2.4 of the official CCDV-F exam guide (Version 1.1, effective December 7, 2026). An independent resource, not affiliated with Anthropic; the practice questions are written from scratch.
2.4.1 Why an integration that passed every demo still fails
Dagny writes the Python back-end of Tallyhaven, a small bookkeeping app for independent shops. Its headline feature is the month-end summary. A shop owner drops in the month's paperwork (bank statements as PDFs, phone photos of receipts, a sales export from the till), and Claude streams back a plain-language summary with anything that looks wrong. In the demo it worked every time.
The first real month-end produced three support tickets. Some summaries stopped mid-sentence, and the page showed them as finished. On the busiest evening, the retry loop turned a handful of errors into a flood of repeated requests, and a few owners waited twenty minutes for a summary that never came. And every owner who uploaded a spreadsheet got a generic "Something went wrong".
None of these is a model problem. Each is a defect in the integration code: the layer that sends requests, reads streams, handles errors and prepares files. The skill this lesson teaches is diagnosis. You read the failing code and its error output, find the defect, and choose the correction that matches how the API documents its own behaviour. Think of a mechanic who reads the fault code before reaching for a spanner.
From ticket to fix
type, stop_reason2.4.2 Reading a stream to its real end
Here is the question that trips people up, and the exam loves it: when is a streamed response finished? The intuitive answer is "when the text stops arriving", and it is wrong in two ways. A stream is a sequence of named server-sent events, small messages written one after another into a single HTTP response, and only one of them means the message is over.
The order is fixed. A message_start event opens the message with empty content. Then come the content blocks, one after another, and each block has its own content_block_start, any number of content_block_delta events and a content_block_stop. A reply can hold several blocks (some text, a tool call, more text), so a content_block_stop closes one block, not the message. After the blocks come one or more message_delta events, and then a single message_stop, the terminal event. Keep-alive ping events can appear anywhere. The docs also warn that new event types may be added, so your code skips types it does not know instead of crashing.
The event sequence of one streamed message
message_startempty content, stop_reason is nullcontent_block_start, deltas, content_block_stopmessage_deltacarries stop_reason and cumulative usagemessage_stopthe terminal eventmessage_start · once per content blockmessage_stop, and the reason it stopped arrives just before, in message_delta.The second half of "finished" is the stop reason: the field that says why generation stopped. In a stream, stop_reason is null in message_start, arrives in a message_delta, and appears in no other event. A handler that never reads it cannot tell a complete answer from a cut-off one. Here are the values a streaming handler must act on.
stop_reason |
What it means in plain terms | What the handler does |
|---|---|---|
end_turn |
Claude finished its answer naturally | Mark the summary complete |
max_tokens |
The reply hit the max_tokens you set |
Flag it as incomplete; raise the limit or continue |
model_context_window_exceeded |
The reply filled the model's context window | Flag it as incomplete |
refusal |
Claude declined; this is a normal response, not an error | Show the refusal path, not a half summary |
tool_use |
Claude wants a tool run before it continues | Run the tool and send the result |
Memorise end_turn, max_tokens and refusal with their actions; recognise the others. Dagny's corrected handler reads raw events from the SDK. Look at the message_delta branch, where the stop reason is captured, and the two checks after the loop.
stop_reason, finished = None, False
stream = await client.messages.create(model=MODEL, max_tokens=4000,
messages=msgs, stream=True)
async for event in stream:
if event.type == "content_block_delta" and event.delta.type == "text_delta":
await push(summary_id, event.delta.text)
elif event.type == "message_delta":
stop_reason = event.delta.stop_reason # the ONLY place stop_reason arrives
elif event.type == "message_stop":
finished = True # the TERMINAL event
# ping, content_block_stop and unknown types: skip, never crash
if not finished:
raise StreamCutOff(summary_id) # no message_stop: never show it as done
if stop_reason in ("max_tokens", "model_context_window_exceeded"):
await mark_incomplete(summary_id) # flagged, not presented as finished
One more stream defect shows up in traces. Tool calls stream their arguments as input_json_delta fragments, partial JSON strings that are not valid JSON on their own; you accumulate them and parse once that block's content_block_stop arrives, or let the SDK's helpers do it.
2.4.3 Sorting errors into classes before you retry
It is tempting to treat every failure as "the API had a bad moment, try again". Resist it completely. Some errors clear on their own, some never will, and a retry policy that cannot tell them apart either hammers a struggling service or repeats a broken request forever. Every error comes back as JSON with a top-level error object holding a type and a message, plus a request_id for support, and the HTTP status and type together name the error class.
| Error class | Status and type |
What the right response is |
|---|---|---|
| Invalid request | 400 invalid_request_error |
Fix the request; a retry sends the same mistake again |
| Rate limit | 429 rate_limit_error |
Wait as long as retry-after says, then retry; smooth bursts |
| Overloaded | 529 overloaded_error |
Retry with backoff; it is temporary and shared by all users |
| Timeout | 504 timeout_error, or your client gave up |
Stream long requests, or move them to batches |
| Server error | 500 api_error |
Retry unless the x-should-retry header says false |
Memorise the four classes the exam names (rate limit, overloaded, invalid request, timeout) and the response each calls for. Recognise the others: 401 and 403 are credential and permission problems, 404 is a missing resource, and 413 request_too_large is a payload over the size limit. None of those is cured by waiting.
Two 429s look alike and need opposite handling. A normal rate limit, measured per minute in requests, input tokens and output tokens, refills continuously, and the response usually carries a retry-after header in seconds. A sharp jump in traffic can also hit a ramp limit, which carries the error code ramp_limit_exceeded; the fix is to wait, then grow traffic gradually. But when an organisation reaches its tier's monthly spend cap, the response is also a 429 rate_limit_error, with no retry-after header and the error code enforced_spend_limit_reached in error.details.error_code. Retrying it fails until access resumes. A spend limit you set yourself is different again: it returns a 400.
The official SDKs already do the right thing for the transient classes. By default they retry up to two times (three attempts in all), on connection errors, timeouts, 408, 409, 429 and every status of 500 and above. They follow x-should-retry when the response carries it, wait as long as retry-after says, and otherwise back off exponentially. Two limits matter. The SDK does not retry an error event that arrives inside a stream, and its automatic retries of a spend-cap 429 keep failing until access resumes.
Four responses to four kinds of failure
Wait and retry
retry-afterapi_errorunless x-should-retry: falseFix the request
a retry repeats the defect
Stop and alert
enforced_spend_limit_reacheda human must act
Change the shape
stream it, or batch it
2.4.4 Retry and fallback that match the class
Now back to Tallyhaven's busiest evening. Dagny's original wrapper caught every exception, retried five times at once, then fell back to a different model. The SDK underneath was already retrying twice, so each click could produce up to eighteen requests in a few seconds. A 529 storm became a self-inflicted flood. A 400 caused by a bad file, which the SDK rightly does not retry, was still sent six times by the wrapper, then sent to a second model, which rejected the same malformed request. This is the defect at the heart of this skill: retry and fallback logic that does not distinguish the error classes.
A fallback is the alternative path you take when retries are exhausted: queue the work and notify the owner later, submit it as a batch job, or call another model where the product accepts that model's quality. A fallback helps only when the problem is capacity. It cannot help a malformed request, because the request travels unchanged to the fallback; it cannot help a spend cap, which applies to the whole organisation; and it cannot help a bad key.
Do not confuse this with the API's own fallback feature. The documented fallbacks request parameter, in beta behind the server-side-fallback-2026-07-01 header, reruns a request on another model inside the same API call, but only when a safety classifier declines it with a refusal stop reason. The SDK's refusal-fallback middleware does the same job on the client. A rate limit, overload or server error on the requested model comes back to you unchanged, so the fallback for a 529 stays in your own code.
The corrected wrapper lets the SDK own the transient retries and gives each remaining class its own branch. Look at the order of the except clauses: the narrow spend-cap class must come before the broader RateLimitError, which would otherwise catch it.
client = anthropic.AsyncAnthropic(timeout=90.0) # SDK keeps max_retries=2: ONE layer retries
async def summarise(req: dict, summary_id: str):
log.info("summary=%s start", summary_id) # YOUR id: a timeout returns no request_id
try:
return await client.messages.create(**req)
except anthropic.EnforcedSpendLimitReachedError:
page_ops("monthly spend cap reached") # NARROW first: retrying never helps
raise
except anthropic.BadRequestError as e: # 400: the request is wrong
log.error("summary=%s request_id=%s %s", summary_id, e.request_id, e.api_message)
raise # fix the code or the file; never resend
except (anthropic.RateLimitError, anthropic.OverloadedError) as e:
return await queue_retry_later(req, summary_id) # capacity: SDK retries exhausted
Streams need their own handling, because an error event arrives after the 200 status. The SDK ends the stream and raises an APIStatusError whose status is the stream's 200 or is missing, so a branch for RateLimitError or OverloadedError never fires. The docs say to check the error's type instead (for example e.type == "overloaded_error"). Then decide what to do with the partial text: discard it and start again, or resume. The streaming docs describe resuming as sending a new request that includes the partial response; for current models, the partial text goes into a user message with an instruction to continue. Tool-use and thinking blocks cannot be partially recovered. What you never do is replay the whole request and append the second answer to the first.
Timeouts get a design fix, not a retry fix. The Python SDK's default timeout is ten minutes, and a timed-out request is retried twice, so one stuck call can hold a user for half an hour. The docs recommend streaming for long requests, and the SDK raises an error before sending a non-streaming request it expects to take longer than about ten minutes. Set a timeout per call that matches what the user will wait for, and stream anything long.
2.4.5 Multi-format ingestion through the Files API
The spreadsheet ticket leads to the third defect family. The Files API lets you upload a file once, get back a file_id, and reference that id in later Messages requests instead of sending the bytes each time. It is now generally available, so it needs no beta header. Older code that still sends files-api-2025-04-14 keeps working and gets the older response shapes. The trap is in the word "file": an id says nothing about which content block the file may travel in, and the block must match the type.
| File type | How it reaches Claude | Common defect |
|---|---|---|
PDF (application/pdf) |
document block |
Password-protected or encrypted PDF; only standard PDFs work |
| Plain text, including .csv and .md | document block, uploaded as text/plain |
Uploaded under another type, then rejected |
| JPEG, PNG, GIF, WebP | image block |
An image sent in a document block: 400 |
| .xlsx, .docx | Not a document block: convert to text or PDF first |
Uploaded as-is and placed in a document block |
| Datasets for analysis | container_upload block for the code execution tool |
Read as text when the task needs calculation |
Tallyhaven's spreadsheet bug was the fourth row: the till exports .xlsx, and Dagny's code placed it in a document block. The Files API's documented errors map cleanly onto ingestion defects. A file type that does not match its block is a 400. A file larger than the context window is a 400, even though the upload succeeded. A file_id that does not exist, was deleted, or belongs to another workspace is a 404. An upload over 500 MB is a 413.
Dagny's fix routes each upload by type before any request is built. Look at the explicit text/plain for CSV files, the conversion branch for office formats, and the rejection at the end, which fails early with a message the owner can act on.
IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"}
async def block_for(upload) -> dict:
if upload.mime == "application/pdf":
f = await client.files.upload(file=(upload.name, upload.data, "application/pdf"))
return {"type": "document", "source": {"type": "file", "file_id": f.id}}
if upload.mime in IMAGE_TYPES:
f = await client.files.upload(file=(upload.name, upload.data, upload.mime))
return {"type": "image", "source": {"type": "file", "file_id": f.id}}
if upload.name.endswith((".csv", ".txt", ".md")):
f = await client.files.upload(file=(upload.name, upload.data, "text/plain")) # EXPLICIT type
return {"type": "document", "source": {"type": "file", "file_id": f.id}}
if upload.name.endswith((".xlsx", ".docx")):
return {"type": "text", "text": to_plain_text(upload)} # CONVERT: no document block
raise UnsupportedFile(upload.name) # reject early, with a message the owner can act on
Two lifecycle rules finish the picture. Files are scoped to a workspace, not to a user, so the docs warn never to accept a file_id from the browser. Keep the mapping between users and their files on your server, or one shop owner could read another's statements. And files persist until you delete them or they reach an expiry set at upload. A summary that reuses a file_id after a cleanup job deleted it gets a 404: a bookkeeping bug in your code, not an outage.
2.4.6 The exam traps
Each trap below is a reasonable-looking line of integration code that misreads what the API told it. A question usually shows the code or the error output and asks for the correction.
- ✗ Treating the first
content_block_stop, or the end of incoming text, as the end of the response. ✓ Wait formessage_stopand readstop_reasonfrommessage_delta, because a reply can hold several blocks and a cut-off reply looks complete. - ✗ Showing a
max_tokensorrefusalstop as a finished answer. ✓ Branch on the stop reason: flag truncation, handle refusal, and mark complete only onend_turn. - ✗ Retrying every exception the same way, including 400s. ✓ Classify by status and
error.type; retry only rate limits, overload, server errors and connection failures, and fix invalid requests. - ✗ Counting on the
fallbacksparameter to ride out a 529. ✓ It reroutes only refusals; overload, rate limits and server errors come back as they are, so capacity fallback stays in your code. - ✗ Stacking your own retry loop on top of the SDK's. ✓ Let one layer own retries, honour
retry-after, and keep the attempt count bounded. - ✗ Retrying a 429 that carries
enforced_spend_limit_reached. ✓ Catch that code before the general rate-limit branch, stop, and alert someone who can raise the limit. - ✗ Putting an .xlsx file or an image in a
documentblock, or accepting afile_idfrom the browser. ✓ Route each file to the block its type requires, convert office formats, and keep file ids on the server.
2.4.7 Put it together: diagnose and repair a fragile integration
You now have every piece. The event sequence ends at its terminal event, the stop reason says whether the text is whole, the error class decides whether a retry can help, and a file's type decides its content block. Diagnosis means reading that evidence first and letting it name the fix. The fastest way to make it stick is to break each piece on purpose and watch the evidence change.
This skill sits on the mechanics of a single request, which Messages API mechanics (2.1) covers in full: message structure, tool use, streaming and stop reasons as building blocks. Failure-mode diagnosis (4.2) takes the same evidence-first habit to traces, and adds the question of whether a failure starts in the integration layer or in the model's output. API key and credential handling (7.3) picks up the 401 and 403 branch.
Key takeaways
- ✓ Diagnose from evidence: the event log, the error
typeand thestop_reasonname the defect before you change any code. - ✓ A streamed message ends only at
message_stop;content_block_stopcloses one block, andstop_reasonarrives inmessage_delta. - ✓ Flag
max_tokens, context-window andrefusalstops instead of presenting the text as a finished answer, and treat a stream with nomessage_stopas cut off. - ✓ Classify every error by status and
error.type: retry rate limits, overload and server errors with backoff andretry-after; never retry invalid requests, missing files, credential errors or the spend-cap 429. - ✓ Let one layer own retries, fall back only for capacity failures, and handle a mid-stream error by its
type, then discard or resume the partial text explicitly. - ✓ Match each file to its block: PDFs and plain text in
document, images inimage, datasets incontainer_upload, office formats converted first, and file ids kept on the server.
Check your understanding
4 questions written for this lesson. Every answer option is explained, including the ones you did not pick. Nothing is stored.
CCDV-F practice questions are being rewritten
The 159 CCDV-F practice questions here were written for the previous exam guide and are tagged to its domains. New questions for the December 7, 2026 guide (v1.1) are being written. Until they are ready, the practice for the new guide is the questions at the end of every lesson, with every answer option explained. The old bank stays open for general practice.