Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Incident containment, evidence, and causal diagnosis
- Implement and explain denominator-correct metrics and first-stage diagnosis, preserve red-to-green evidence, then design containment and rollback without erasing business facts. Public checks do not prove authorship, semantic quality or real incident experience.
How does the mechanism work?
Step-by-step explanation
- How to monitor if the quality drops but HTTP 200 is normal?
Incident assessment must check business quality beyond HTTP status.
- What to do with in-progress tasks after rollback?
After containment and rollback, business operations still in flight require handling.
- What information should go into the incident log?
Causal diagnosis requires reliable records and a clear separation of facts from hypotheses.
Debugging · Diagnose failures
Diagnose failures · Incident containment, evidence, and causal diagnosis
Objectives of this level: Implement first-stage diagnosis and repair a misattributing checker with a preserved red-to-green diff.
Visual guide · From aggregate alarm to a task
Equal aggregate symptoms can have different causes. This fixture protocol finds an observed broken stage; missing observations remain unknown. Select the figure to open it at full size.
Diagnose without borrowing a different task's error
Start from the complete amber/violet data and your foundation submission. Before the optional postmortem, add a dated hypothesis, supporting task/event IDs, an alternative explanation and a discriminating observation to incident-evidence.md. The two cases are public fixed exercises. A genuine unannounced condition must be chosen separately by a reviewer; this page does not claim to provide one.
The intentionally faulty checker below picks a global 403 and attributes it to the first failed violet task. Save it as triage_before.py and run it. Its exit 1 is the expected diagnostic baseline, not a finished feature failure to hide. Inspect the IDs in its output before changing it.
from incident_lab import fixture
data = fixture("violet")
task = next(t for t in data["tasks"] if t["version"] == "v2" and not t["accepted"])
event = next(e for e in data["events"] if e["kind"] == "tool_call" and e["data"]["http_status"] == 403)
print({"task_id": task["task_id"], "hypothesis": "authorization",
"claimed_event_id": event["event_id"], "event_task_id": event["task_id"]}, flush=True)
assert event["task_id"] == task["task_id"], "global 403 does not locate this task failure"
Implement the first observed broken stage
first_failure(task, trace) receives one task dictionary and only that task's event list, with the same validation protocol as the implementation layer. Validate with that one task; an event for any other task raises ValueError("orphan_event"). Deduplicate identical event IDs and sort by (at_ms, event_id); use the earliest event per kind. Return exactly {"stage": str, "event_id": str_or_None, "reason": str}. Use these ordered checks; this is a bounded fixture protocol, not a causal inference engine for arbitrary production traces:
- Missing candidate →
unobserved / None / missing_candidate; a different candidate resource →routing / candidate event ID / wrong_resource. - Missing authority →
unobserved / None / missing_authority. If authority denies: missing terminal →unobserved / None / missing_terminal; expected, actual and terminal alldenied→none / None / correct_denial; otherwise →authorization / authority event ID / denial_not_preserved. A correct denied task requires no context event. - If authority allows: missing context →
unobserved / None / missing_context; required IDs not a subset of context IDs →context_assembly / context event ID / required_policy_missing. - Missing terminal →
unobserved / None / missing_terminal; expected ≠ actual, or terminal status ≠ actual →acceptance / terminal event ID / status_mismatch; otherwise →none / None / contract_satisfied.
The first violated fixture contract takes precedence over a later tool response. HTTP events alone do not determine a cause. The function does not claim that an unobserved event never happened, require every possible tool span to exist, assess natural-language evidence quality, or measure actual remote execution.
Preserve a red-to-green checker and independent negative controls
After writing your function, repair the faulty checker to select the same task's trace and use your function. This runnable checker shows the expected evidence binding and stage for this fixed task; save it as triage_after.py. It does not implement the student function for you.
from incident_lab import fixture
from incident_student import first_failure
data = fixture("violet")
task = next(t for t in data["tasks"] if t["version"] == "v2" and not t["accepted"])
trace = [e for e in data["events"] if e["task_id"] == task["task_id"]]
result = first_failure(task, trace)
event = next(e for e in trace if e["event_id"] == result["event_id"])
assert event["task_id"] == task["task_id"]
assert result["stage"] == "context_assembly"
print({"task_id": task["task_id"], "evidence": event, "result": result})
python3 triage_before.py
python3 triage_after.py
python3 incident_lab.py grade --module incident_student.py --out incident-grade.json
python3 incident_lab.py guided --case amber --out amber-guided.json
python3 incident_lab.py guided --case violet --out violet-guided.json
Expected exits: original checker 1; repaired checker 0 once your diagnosis function is correct; full grade 0 only after both functions meet the protocol; both guided commands 0. Run the guided summary only after your initial evidence submission. guided reports the supplied metrics, not a measured remediation result. Your actual change repairs a diagnostic checker/module; it does not fix a production Agent or turn all fixture task outcomes into success.
Submit original and repaired checker files, their diff, stdout/stderr and exits, your own module diff, and the final grader report. Include a first-stage finding for every failed v2 task, the relevant event ID and a rejected hypothesis. Also test an accepted task containing a 403, a trace missing context, changed resource/policy IDs, and a status mismatch with complete context. Do not “repair” the fixtures, expected results or grader. Keep the baseline inputs identical for the before/after reproduction.
Optional postmortem — read after the initial submission
In amber v2, tasks 2 and 3 propose other-order instead of their bound resource. The candidate event is the first violation; the following 403s and recorded retries amplify a routing mistake. In violet v2, tasks 2 and 3 have current authority denied at epoch 2 and correctly finish denied; their 403s are not failed tasks. Tasks 0 and 1 use their own resource and get HTTP 200 but assemble only base, losing required exception; the context event is the first violation and their eligible result fails the contract. Both cases share the three aggregate series but have distinct task-local failure evidence. v2 tenant t1 acceptance is 2/3 in amber and 1/3 in violet; retry counts are 2 and 0. These are fixture facts, not verified universal enterprise root causes.
Optional complete support program
Save this complete block as incident_lab.py. Save the manifest from the implementation layer's absolute HTTPS link as incident-cases.json beside it and your student module. Fixed amber/violet generation and the complete student contracts are already readable above; the larger public variant manifest is a separate downloadable asset. The grader imports and calls your functions against those pre-generated fixed/variant inputs and expected results, checking return shape, values, errors and unchanged input. It does not include a general-purpose metrics or diagnosis solution. The manifest's dataset arrays reference immutable records by zero-based index; the grader materializes deep copies. Public expected outputs allow reproduction, not proof of authorship; a learner can memorize public cases, so a reviewer must still select a fresh condition and inspect the implementation. Preserve both support files unchanged. guided reads only stored summaries for the two fixed examples.
"""Offline authored incident inputs and a public mechanical grader.
No provider, service, production or generic student solution is included.
Only import a student file you control: module import executes Python code.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import sys
LAB_VERSION = "incident-lab-v3"
CASES_PATH = Path(__file__).with_name("incident-cases.json")
COUNT_KEYS = {"task_count", "acceptance_known", "accepted_tasks", "pending_tasks",
"rounds_total", "tool_call_count", "tool_403_count", "tool_retry_count"}
RATE_KEYS = {"acceptance_rate", "rounds_per_task", "tool_403_rate"}
sys.dont_write_bytecode = True
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def manifest():
data = json.loads(CASES_PATH.read_text())
if data.get("schema_version") != 1 or data.get("lab_version") != LAB_VERSION:
raise ValueError("case_manifest_version")
return data
def materialize(data, key):
indexes = data["datasets"][key]
return {kind: [copy.deepcopy(data["records"][i]) for i in indexes[kind]] for kind in ["tasks", "events"]}
def fixture(case):
data = manifest()
if case not in data["fixtures"]:
raise ValueError("unknown_case")
return {"schema_version": 1, "source": "authored_redacted_fixture", "case": case,
"clock": "logical milliseconds; not measured latency", **materialize(data, data["fixtures"][case])}
def output_shape(actual, function):
if function == "summarize":
return (type(actual) is dict and set(actual) == COUNT_KEYS | RATE_KEYS
and all(type(actual[k]) is int for k in COUNT_KEYS)
and all(actual[k] is None or type(actual[k]) is float for k in RATE_KEYS))
return (type(actual) is dict and set(actual) == {"stage", "event_id", "reason"}
and type(actual["stage"]) is str and type(actual["reason"]) is str
and (actual["event_id"] is None or type(actual["event_id"]) is str))
def grade(student_path):
student_path = Path(student_path).resolve()
data = manifest()
spec = importlib.util.spec_from_file_location("incident_student", student_path)
if spec is None or spec.loader is None:
raise ValueError("student_import")
module = importlib.util.module_from_spec(spec)
sys.modules["incident_student"] = module
spec.loader.exec_module(module)
own = all(callable(getattr(module, name, None)) and getattr(getattr(module, name), "__module__", None) == "incident_student"
for name in ["summarize", "first_failure"])
checks = []
def record(name, passed, details):
try:
json.dumps(details)
except (TypeError, ValueError):
details = {"non_json_details": repr(details)}
checks.append({"name": name, "passed": bool(passed), "details": details})
record("student_functions", own, {"required": ["summarize", "first_failure"], "direct_import_alias_allowed": False})
if own:
for case in data["checks"]:
inputs = materialize(data, case["dataset"])
args = (inputs["tasks"], inputs["events"]) if case["function"] == "summarize" else (inputs["tasks"][0], inputs["events"])
before = digest(args)
kwargs = copy.deepcopy(case.get("kwargs", {}))
try:
actual = getattr(module, case["function"])(*args, **kwargs)
except Exception as exc:
passed = ("expected_error" in case and type(exc) is ValueError
and str(exc) == case["expected_error"] and digest(args) == before)
record(case["name"], passed, {"expected_error": case.get("expected_error"),
"actual_error": type(exc).__name__ + ":" + str(exc), "input_unchanged": digest(args) == before})
else:
passed = ("expected" in case and output_shape(actual, case["function"])
and actual == case["expected"] and digest(args) == before)
record(case["name"], passed, {"expected": case.get("expected"), "actual": actual,
"expected_error": case.get("expected_error"), "input_unchanged": digest(args) == before})
return {"source": "public_mechanical_grader", "lab_version": LAB_VERSION,
"cases_sha256": hashlib.sha256(CASES_PATH.read_bytes()).hexdigest(),
"student_sha256": hashlib.sha256(student_path.read_bytes()).hexdigest(),
"passed": all(c["passed"] for c in checks), "passed_checks": sum(c["passed"] for c in checks),
"total_checks": len(checks), "checks": checks,
"limits": "public fixed inputs and expected outputs; no authorship, semantic, production or unseen-interview certification"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["scaffold", "sample", "guided", "grade"])
parser.add_argument("--case", choices=["amber", "violet"], default="amber")
parser.add_argument("--module")
parser.add_argument("--out", required=True)
args = parser.parse_args(argv)
if args.command == "scaffold":
out = Path(args.out)
if out.exists():
parser.error("scaffold refuses to overwrite an existing student file")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text('''"""Implement both contracts yourself; disclose any guided/reference assistance."""
def summarize(tasks, events, *, version=None, tenant=None, start_ms=None, end_ms=None):
raise NotImplementedError("implement the complete metrics contract")
def first_failure(task, trace):
raise NotImplementedError("implement the evidence-stage contract")
''')
print(json.dumps({"out": str(out), "lab_version": LAB_VERSION, "source": "unimplemented_student_scaffold",
"sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, sort_keys=True))
return 0
try:
if args.command == "grade":
if not args.module:
parser.error("grade requires --module")
result = grade(args.module)
exit_code = 0 if result["passed"] else 1
elif args.command == "sample":
result, exit_code = fixture(args.case), 0
else:
data = manifest()
result = {"source": "authored_redacted_fixture", "lab_version": LAB_VERSION, "case": args.case,
"input_sha256": digest(fixture(args.case)), "metrics": copy.deepcopy(data["guided"][args.case]),
"meaning": "stored fixed fixture metrics; not measured provider tokens, cost, latency or an enterprise incident"}
exit_code = 0
except Exception as exc:
result = {"source": "public_mechanical_grader", "lab_version": LAB_VERSION,
"passed": False, "setup_error": type(exc).__name__ + ":" + str(exc)}
exit_code = 2
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
print(json.dumps({"out": str(out), "lab_version": LAB_VERSION, "source": result["source"],
"passed": result.get("passed"), "passed_checks": result.get("passed_checks"),
"total_checks": result.get("total_checks"), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, sort_keys=True))
return exit_code
if __name__ == "__main__":
sys.exit(main())
code example
A correct denial is a successful boundary
A currently denied task may have HTTP 403 and still satisfy its denied terminal contract. Compare it against a failed task whose calls are HTTP 200 but required policy evidence is absent. The fixture ordering, not the loudest global HTTP status, locates the first broken stage.
Acceptance task for this level
Implement first_failure, run the intentionally wrong checker at exit 1, repair its task binding and rerun at exit 0; submit both files/diff/logs, every failed v2 task’s first-stage event and correct-denial/missing-context/status-mismatch negative controls.
Reading this browser’s record…
Hide the answer and check your understanding
A task has current authority denied, two tool 403s and terminal denied. Another task has tool 200 but lacks required context. Must both be authorization failures?
Expand reference derivation
No. The first satisfies the denial contract (none/correct_denial); the second fails at context_assembly, identified by its own context event. A global 403 cannot identify the second task’s cause. Missing context observation instead returns unobserved/missing_context.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.
- OpenTelemetry:Generative AI semantic conventions
- Google SRE: canary release and comparison
- Google SRE: Roles and Records in Incident Response
- OpenTelemetry: Trace, Span and Asynchronous Causal Linking
- RFC 9110: 403 refusal
- Offline public incident lab source
- Pre-generated public incident inputs and expected outputs
- Project merchant source: identity and ownership boundaries