Fault injection for tools and the model

Study time
≈ 2 h (estimate)
Needs
L3-M05-L04
Updated
2026-11-05

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M06 · Duration: ~110 minutes (estimate, including the independent exercise) · Previous: L3-M05-L04 (session and user isolation) · Next: L02

1. Introduction

In the earlier modules, every ThuVien Mini tool (a fictional product) answered on time and in the right shape. The real world is not that polite: one tool call returns a server error; another waits forever; the service says "too many calls, wait a moment"; the model returns JSON cut off halfway; and, worst of all, the server finishes recording a loan and only then reports an error. This module asks: when those things happen, does the agent recover, report the failure honestly, or lie?

To answer it, you do not wait for faults to arrive on their own. You inject faults: you put a layer between the agent and its tools (and between the agent and the text the model returns), make exactly the call you choose fail in exactly the way you choose, and then read the outcome of the run. Chaos engineering describes the same idea at system scale: pick events that reflect "real-world events", including "malformed responses", and look for a difference from the steady state [R1]. This lesson does that for one agent, in a sandbox.

What the lesson produces: the fault-injection layer lab/faults.py (fault plans, a plan validator, an injector with a log), an outcome table of one task under five kinds of fault for three agent configurations, and in §9 a fault plan you write for a different task, plus the rule-matching part of an injector you write yourself.

2. Learning objectives

  1. Name the five kinds of fault the lab injects (tool error, timeout, rate limit, partial write, malformed model output) and map each one to a real API failure. Read: §4.1.
  2. Classify a run under faults as one of seven outcomes, and explain why silent_failure is more dangerous than loud_failure. Read: §4.2. Practice: §8.2 (parts B, C), §9 (TODO 1).
  3. Write a fault plan that passes validate_plan, read the injector's log to learn which faults really happened, and write the rule-matching part of an injector. Read: §5.1, §5.2. Practice: §8.3, §9 (TODO 2, TODO 3).
  4. Explain why a fault-injection test whose fault never happened (not_fired), or happened without the caller seeing it (not_observed), proves nothing about recovery. Read: §6.1. Practice: §8.2 (parts E, F).

3. Prerequisites and tools

  • L3-M02-L04 (fake tools, sandbox, idempotency keys), L3-M03-L04 (the end state differs from the message), L1-M06-L01 (non-determinism). Code lab code-labs/l3-m06.
  • Keep the meanings apart. A fault is something you cause at one call; an outcome is the label of the whole run (agent.classify). This word differs from the "outcome" of L3-M03-L01, where it meant the end state of the environment. Timeout is the caller's (the agent's) timeout: the agent stops waiting; the server may still be working. Effect keeps its meaning from L3-M02-L04: a loan, a notice that was sent.
  • The agent in the lab is a simulated, scripted program (data/tasks.json), not a language model; the tools are a Python object in a sandbox. Every student, book and number is fictional.

4. Concept explanation

4.1 Five kinds of fault, and where they resemble real failures

The lab injects five kinds of fault (faults.KINDS). Each is a simplified version of a real failure:

Kind What the lab does Matching real failure
tool_error the tool returns TRANSIENT at once and writes nothing a 500 (api_error) or 529 (overloaded_error) from the Claude API [R2]
timeout the tool takes delay_ms; effect: "after" means it still writes (the answer arrives late), "before" means it does not write timeout_error (504) [R2]; a timeout "doesn't necessarily mean that side effects haven't happened" [R5]
rate_limit the tool returns RATE_LIMITED with retry_after_ms, then opens a window of that length: every call to the same tool inside the window is limited too HTTP 429 "Too Many Requests", possibly with Retry-After [R3]; the Claude API's rate_limit_error [R2]
partial_write the tool finishes writing the effect and only then returns TRANSIENT A server that fails after writing
malformed_output the model's action text is cut off (truncated) or lacks the tool field (missing_field) A cut-off answer: stop_reason max_tokens is "The response reached your max_tokens limit"; for model_context_window_exceeded, "Treat the response as truncated" [R4]

The caller cannot tell partial_write from tool_error by the answer (both are TRANSIENT); only the environment's state shows whether the loan exists yet. For malformed_output, the agent parses the model's text itself (agent.parse_action returns NOT_JSON, NO_TOOL or BAD_ARGS). The lab deliberately does not inject failures of the model's own API, a network cut mid-stream, an agent that gets stopped, or two nested faults; they belong to the "not tested" section of the report (L05).

4.2 Seven outcomes of a run under faults

The record of one run (run_task) holds what the agent claims (claimed_success: does the last sentence say "Done") and the real end state (end_state: which effects are missing, duplicated or unexpected, compared with the task's expect). agent.classify reads those two, together with the injector's log and the attempts, and returns exactly one of seven outcomes, checked in this order:

  1. not_fired: there is a fault plan, but no fault happened. The run says nothing about faults (§6.1).
  2. duplicate: one effect was applied twice (two loans of the same book, two notices with the same content). The topic of L02.
  3. loud_failure: the agent says it did not finish (it stops with the reason tool_error:<code> or malformed_output).
  4. silent_failure: the agent says it finished, but the end state is wrong.
  5. not_observed: success, a fault fired, but the caller did not see it: every attempt returned ok and no model text was broken badly enough to be unreadable. Example: a 2000 ms timeout while the agent waits up to 3000 ms (§8.2, part F). The run says nothing about recovery.
  6. recovered: success (the claim is right, the state is right) after at least one fault the caller did see (an attempt returned an error, or parse_action returned an error code).
  7. ok: success, no fault fired.

loud_failure is annoying but honest: the student knows to ask the librarian. silent_failure is the most serious failure: the student is told "Done: S0042 borrowed B005" when there is no loan, the "the message says yes, the environment says no" relation of L3-M03-L04.

The lab's three configurations (agent.CONFIGS), the same model, differing only in how they handle faults:

Configuration Retry When a tool returns an error or the model output is broken
naive no stops at the first error and states the reason
ignore_errors no skips that step, carries on, then still claims success (a deliberate silent_failure bug)
safe up to 4 attempts, same key, honours Retry-After asks the model again once when the output is broken (mechanism in L02)

A fourth configuration, retry_new_key (retries but creates a new key on every attempt), is for L02.

An easy misreading: recovered does not mean the agent handled the fault correctly. Under borrow_timeout_after, ignore_errors also comes out recovered (§8.2, part B) because the server wrote before its late answer; under borrow_timeout_before it comes out silent_failure. An outcome is evidence about that run, not about the mechanism.

5. Technical deep dive

5.1 Fault plans and validate_plan

A fault plan is a list of rules. Each rule has a kind, a target (a tool name, or "model"), and exactly one trigger: on (the call numbers to that target, counted from 1, including retries) or rate (a probability 0 < rate ≤ 1 per call). Kind-specific parameters: effect and delay_ms for timeout, retry_after_ms for rate_limit, form for malformed_output; defaults are in faults._DEFAULTS (timeout defaults to effect: "before").

validate_plan(plan) returns a sorted list of error codes, empty when the plan can run, and never raises. Part A of the demo shows the common codes:

Code Meaning
BAD_TARGET malformed_output must target "model", the other kinds must not target "model"; partial_write only targets write tools
NO_TRIGGER neither, or both, of on and rate
BAD_ON, BAD_RATE on is not a non-empty list of positive integers (a True is caught too); rate outside (0, 1]
UNKNOWN_FIELD a field that does not belong to that kind, for example delay typed without _ms

The remaining codes (NOT_A_LIST, NOT_A_RULE, BAD_KIND, BAD_PARAM) are in the docstring of faults.validate_plan. Injector(plan) refuses to run (raises ValueError) when the plan has errors. This is a fail-closed choice: if the mistyped field delay were silently ignored, the timeout would use the default value and you would believe you had tried a different number. The validator checks shape only: it does not know whether the task calls the targeted tool.

5.2 The injector: call numbers, seeded probability, windows and the log

Injector.decide(target, now_ms) is called on every attempt of every tool call and on every model call. It counts calls per target, then checks the rules in order; the first matching rule wins. Because the count includes retries, "on": [1] breaks only the first attempt.

For a rate rule, the decision is rand.unit(seed, trial, target, n, i, "fault") < rate, a number in [0, 1) derived from SHA-256: same seed, same trial, same call number gives the same decision, whatever the run order. The lab uses no random and no real clock; every wait is SimClock.advance.

When a rate_limit rule fires at time t, the injector opens the window [t, t + retry_after_ms) for that target: every call inside the window also gets RATE_LIMITED and is logged with window: True, rule: None. A retry after 200 ms is still limited.

Every fault that fires is written to Injector.log (kind, target, n, at_ms, rule, window), kept in run["faults"]. fired(log) returns the kinds that happened, unfired_rules(plan, log) returns the rules that never fired.

6. QA perspective

6.1 A fault-injection test only means something when the fault happened

Part E of the demo (§8.2) runs notice_error_once (break the first send_notice call) on t01. t01 sends no notice, so the rule never fires: unfired_rules=[0], outcome not_fired. If you only looked at "the agent succeeded", you would write "the agent tolerates notice-sending errors", a false finding. As with the control check of L3-M05-L01: a fault rule that does not fire is a broken test.

From that, five habits for writing fault-injection tests:

  • Assert that the fault happened before asserting the outcome: F.unfired_rules(plan, run["faults"]) == []. With a multi-rule plan, one rule may fire while another does not.
  • Check whether the fault was seen. not_observed (part F), like not_fired, says nothing about recovery.
  • Check the broken configuration too. A good fault plan makes naive fail; if naive does not fail (ok, not_observed or recovered) under your plan, the plan does not reach the place it needs to reach.
  • Read the end state, not the agent's words. silent_failure only shows up when you compare end_state with expect.
  • One fault at a time, then mix. A one-rule plan gives each cell one cause; probabilistic plans (flaky) are for the repeated runs of L03.

7. Real-world scenarios

Scenario 1 (fictional): "It said I borrowed it, but I don't have the book". The assistant reports that the loan is done, but the desk has no loan; the log shows borrow_book returned a 500 at exactly that moment. The tester reproduces it with a one-rule plan (tool_error on borrow_book, on: [1]) and sees exactly the borrow_error_once row of §8.2: the configuration in production ignores the tool error and still writes the "Done" sentence. The regression test asserts that the fault fired and that the outcome is not silent_failure.

Scenario 2 (fictional): "The fault suite is all green". Twenty fault-injection tests all pass. The tester adds assert F.unfired_rules(plan, run["faults"]) == [] to each test. Seven tests turn red: a rule targets send_notice in a task that sends no notice, or targets call number 3 of a tool that is called only once. Those seven tests never tested anything.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m06
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 145 passed

8.2 Run the demo

python -m lab.demo l01

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; both versions gave identical output). Every run is simulated:

A. validate_plan on the shipped plans and on broken plans
   none: []
   borrow_error_once: []
   borrow_timeout_after: []
   borrow_timeout_before: []
   borrow_partial: []
   borrow_rate_limit: []
   model_truncated: []
   notice_error_once: []
   notice_partial: []
   flaky: []
   slow_search: []
   malformed output on a tool: ['BAD_TARGET']
   partial write on a read tool: ['BAD_TARGET']
   both on and rate: ['NO_TRIGGER']
   call number 0: ['BAD_ON']
   rate 0: ['BAD_RATE']
   a typo in a field: ['UNKNOWN_FIELD']
   not a list: ['NOT_A_LIST']
B. t01 (S0042 borrows B005) under single-fault plans: outcome / stop reason
   none: naive=ok (final) | ignore_errors=ok (final) | safe=ok (final)
   borrow_error_once: naive=loud_failure (tool_error:TRANSIENT) | ignore_errors=silent_failure (final) | safe=recovered (final)
   borrow_timeout_after: naive=loud_failure (tool_error:TIMEOUT) | ignore_errors=recovered (final) | safe=recovered (final)
   borrow_timeout_before: naive=loud_failure (tool_error:TIMEOUT) | ignore_errors=silent_failure (final) | safe=recovered (final)
   borrow_partial: naive=loud_failure (tool_error:TRANSIENT) | ignore_errors=recovered (final) | safe=recovered (final)
   borrow_rate_limit: naive=loud_failure (tool_error:RATE_LIMITED) | ignore_errors=silent_failure (final) | safe=recovered (final)
   model_truncated: naive=loud_failure (malformed_output) | ignore_errors=recovered (final) | safe=recovered (final)
   notice_error_once: naive=not_fired (final) | ignore_errors=not_fired (final) | safe=not_fired (final)
C. the silent failure, read from the run record (ignore_errors, borrow_error_once)
   claimed_success=True end_state={'missing': [['borrow', 'S0042', 'B005']], 'duplicate': [], 'unexpected': []} calls=[('search_books', 'ok'), ('get_book', 'ok'), ('borrow_book', 'TRANSIENT')]
D. the injector log (safe, borrow_rate_limit)
   {'kind': 'rate_limit', 'target': 'borrow_book', 'n': 1, 'at_ms': 2061, 'rule': 0, 'window': False}
   borrow_book attempts: [(1, 'RATE_LIMITED', 1500), (2, 'ok', 0)]
E. a plan that never fires on t01: fired=[] unfired_rules=[0] outcome=not_fired
F. a fault that fires but is never seen: borrow_book answers after 2000 ms, the client waits up to 3000 ms
   naive: fired=['timeout'] attempts=['ok'] outcome=not_observed
   safe: fired=['timeout'] attempts=['ok'] outcome=not_observed

Reading the output: part A: the lab's eleven plans are all clean; the seven broken plans are all caught. Part B is the outcome table of t01 (search for a book, view the book, borrow B005) under all five kinds of fault. naive fails honestly under every fault. ignore_errors gives silent_failure in three rows, and recovered in three rows by luck: under borrow_timeout_after and borrow_partial the server wrote before reporting the error; under model_truncated the skipped step is the search step. safe recovers in all six rows that have a fault. Part C: the third call returns TRANSIENT, claimed_success=True, end_state is missing the loan. Part D: the rate-limit error is on borrow_book call number 1, at 2061 ms; safe waits exactly 1500 ms. Part E is the rule that does not fire. Part F: the timeout rule fires, but 2000 ms is shorter than the 3000 ms the caller waits, so the attempt returns ok and both configurations are not_observed; writing recovered here would praise naive for recovering from a fault it never saw.

8.3 Try it yourself

Save this as try_l01.py in the lab's root folder (next to lab/), run python try_l01.py, then delete the file:

from lab import agent as A, faults as F

plan = [{"kind": "tool_error", "target": "return_book", "on": [1]},
        {"kind": "timeout", "target": "send_notice", "on": [1], "effect": "after", "delay_ms": 4000}]
print(F.validate_plan(plan))
for cfg in ("naive", "ignore_errors", "safe"):
    r = A.run_task("t02", cfg, plan)
    print(cfg, A.classify(r), r["stop_reason"], F.fired(r["faults"]), F.unfired_rules(plan, r["faults"]), [e["effect"][0] for e in r["effects"]])

Output (Python 3.14.6 and 3.12.3, Linux, identical):

[]
naive loud_failure tool_error:TRANSIENT ['tool_error'] [1] []
ignore_errors silent_failure final ['timeout', 'tool_error'] [] ['notice']
safe recovered final ['timeout', 'tool_error'] [] ['return', 'notice']

Reading: t02 returns book B004 and then sends a notice. With naive, the agent stops at step 1, so the second rule never fires ([1] in the unfired_rules column): the run says nothing about the notice timeout. ignore_errors ignores both faults and sends "B004 returned" when the book has not been returned: silent_failure. safe recovers from both.

8.4 Run the lesson's tests

python -m pytest tests/test_l01_faults.py -v

Result: 34 passed. Read test_outcome_table_of_the_lesson (the part B table, with a comment on the two "lucky" cells), test_each_broken_plan_is_caught_and_the_validator_never_raises and test_call_numbers_count_retries_and_the_first_matching_rule_wins.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: invalid fault plan: [...] The plan does not pass validate_plan Read the codes in the brackets and fix them using the table in §5.1
Outcome not_fired The task does not call that target, or does not reach that call number Look at run["calls"] to see what the task calls; use F.unfired_rules
The second rule never fires The first rule matches the same call (the first rule wins), or the agent stops earlier Change the order or the call number; run with safe so the agent carries on
"on": [1] but the retry still fails That is the rate-limit window (window: True), not the rule Read run["faults"]; lower retry_after_ms or wait longer
Outcome not_observed The fault fired but the caller did not see it, for example delay_ms is smaller than the policy's timeout_ms Set delay_ms larger than the caller's timeout, or target a different call

9. Independent exercise

Problem: Task t03: student S0315 borrows B002 and then gets the notice "B002 is ready at the desk." The file exercises/ex_faults_l01.json has six one-rule plans, one fault-coverage requirement and three call sequences.

Requirements: complete exercises/test_l01_faults.py:

  1. TODO 1: OUTCOMES: for each plan, the triple of outcomes under naive, ignore_errors and safe.
  2. TODO 2: PLAN: a plan of at most three rules such that on t03 with safe, the three kinds tool_error, rate_limit and partial_write each fire at least once, every rule fires, and the run is still recovered; and the same plan with naive is loud_failure.
  3. TODO 3: the function first_rules(plan, calls), the rule-matching part of an injector: given a plan with only on rules and the list of targets called in order, return the index of the rule that fires at each call (or None). The test compares it with F.Injector on the data file's three sequences and blocks F.Injector while your function runs.

Test data: exercises/ex_faults_l01.json.

Deliverable: the two variables and the function above, in the file exercises/test_l01_faults.py itself.

Acceptance criteria: python -m pytest exercises/test_l01_faults.py passes (3 tests).

Hints: do not copy the t01 table. For each plan in TODO 1, ask: does the rule touch any call of t03, does the caller see the fault, and does safe have enough attempts? For TODO 2, remember that the first matching rule wins and that retries are counted too; run, read run["faults"], then fix. For TODO 3, each target has its own counter, counting from 1.

10. Knowledge check

0/10 done · Results are kept in this browser only.

P02 · True or false

In the lab, a recovered outcome of a run under a fault proves that the agent configuration handles this kind of fault correctly.

P04 · Select all that apply

Without running code, using only §5.1: select every rule that validate_plan reports an error for.

P05 · Put in order

Put the steps for writing a meaningful fault-injection test for a write tool in order.

  1. Compare the outcome of step 4 with the outcome of the same plan under a configuration that does not retry; if neither fails (ok, not_observed or recovered), the plan does not reach the place it needs to reach
  2. Choose the step and the kind of fault, write a one-rule plan and check it with validate_plan
  3. Assert that the rule fired: unfired_rules(plan, run["faults"]) == []
  4. Run the task with the configuration under evaluation and read run["faults"]
  5. Assert the outcome from the end state and the agent's words with classify

P06 · Match

Match each observation in a run record to the outcome classify returns.

P07 · Spot the bug

A tester wrote this test to prove the agent tolerates an error while sending a notice. The test is green. Find the bug.

def test_agent_survives_a_notice_error():
    plan = [{"kind": "tool_error", "target": "send_notice", "on": [1]}]
    run = A.run_task("t01", "safe", plan)
    assert run["success"]

P08 · Essay

Write three to five sentences: why silent_failure is the most dangerous outcome for an agent with side effects, and which fields of the run record a test needs to read to catch it.

P10 · Recall

Lesson: L3-M02-L04

According to L3-M02-L04, when a borrow_book call with an idempotency key fails, how is the next call with the same key handled?

11. Summary

  • Concepts: five kinds of fault and the matching real failures [R2][R3][R4][R5]; seven outcomes of a run; the lab's three configurations; chaos-engineering-style experiments, in a sandbox [R1].
  • Skills: write fault plans that pass validate_plan; read the injector's log; write the rule-matching part of an injector; classify a run by its end state, the agent's words and the attempts.
  • Traps: trusting the "Done" sentence; tests with rules that never fire, or fire without anyone seeing; treating a lucky recovered as evidence about the mechanism; a mistyped field silently ignored.
  • You can now: build a fault-injection layer for an agent and prove that each fault test reached its fault.

12. References

ID Title Publisher URL Accessed Relevance
R1 Principles of Chaos Engineering principlesofchaos.org https://principlesofchaos.org/ 2026-11-05 Real-world events (including malformed responses), steady state
R2 Errors Anthropic (Claude API documentation) https://platform.claude.com/docs/en/api/errors 2026-11-05 Codes 429, 500, 504, 529 and the matching error types
R3 RFC 6585: Additional HTTP Status Codes IETF https://www.rfc-editor.org/rfc/rfc6585 2026-11-05 429 Too Many Requests, the Retry-After header
R4 Handling stop reasons Anthropic (Claude API documentation) https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons 2026-11-05 max_tokens; cut-off answers
R5 Timeouts, retries, and backoff with jitter Amazon Builders' Library (AWS Builder Center) https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/ 2026-11-05 A timeout or error does not mean the effect has not happened

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Fault injection Tiêm lỗi: cố ý làm hỏng một lời gọi đã chọn theo một cách đã chọn, trong sandbox
Fault plan / rule Kế hoạch lỗi / luật: loại, target, on hoặc rate, tham số
Partial write Ghi dở: máy chủ ghi tác động rồi mới báo lỗi
Rate limit (window) Giới hạn tốc độ (cửa sổ): bị giới hạn, và vẫn bị giới hạn cho tới hết retry_after_ms
Loud / silent failure Thất bại trung thực (agent nói chưa xong) / thất bại im lặng (agent nói xong, trạng thái sai)
Not fired Không kích hoạt: luật lỗi không chạm lời gọi nào; test đó không kiểm gì
Not observed Không được thấy: lỗi đã kích hoạt nhưng phía gọi chỉ thấy ok; lần chạy không nói gì về hồi phục