Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Task causality and resource attribution

String business tasks, model requests and tool calls into queryable links, and use quality regression to supplement operating indicators.

Learning objectives: Observability is about connecting a user task to real models, tools, and business effects. The timeline is used to explain waiting, and the resource account is used to explain costs. The two cannot be replaced by model self-statement or simple accumulation.

Content checked: 2026-10-30 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Task causality and resource attribution
Observability is about connecting a user task to real models, tools, and business effects. The timeline is used to explain waiting, and the resource account is used to explain costs. The two cannot be replaced by model self-statement or simple accumulation.

How does the mechanism work?

Step-by-step explanation
  1. How does an asynchronous worker restore the trace context? What should I do if the context is missing?

    After a task outlives its HTTP request, maintain traceable correlations.

  2. Why can't the time consumption of concurrent spans be added directly?

    After breaking down the components, explain the difference between measured component durations and the user's wait time.

  3. If I/O logging is turned off, how can I retain the minimum evidence of a reproducible problem?

    Evidence is required for troubleshooting, but the scope of recording is subject to data minimization.

Debugging · Diagnose failures

Debug · A cumulative-snapshot counting regression

Objectives of this level: Reproduce a false usage increase from real route records, repair an independent analysis file and prove unchanged source inputs.

Visual guide · Snapshots are not new events

Snapshots are not new events

The route snapshots share the same ledger events. Simulated resource units remain simulated after correcting the count; missing provider usage is unknown. Select the figure to open it at full size.

Measurement version: the capstone event counts, simulated usage and route outputs in this track refer to the original immutable enterprise-after-sales-agent-v1.zip and its bundled README/records. Extract that original archive for those exact observations. The 1.0.1 evidence-contract archive changes prompt/tool data; do not reuse these numbers for it. The separate new SDK/OTLP exercise below records its own version and results.

Start with the failed report

Assume an analyst reports twelve model calls and 11,568 input simulated units for main-return after recovery. Before blaming prompt growth, inspect their input files. work/tool.json, work/fault-main.json and work/recover-main.json each contain the same four earlier model_response events. Their later differences are approval and business-write/reconciliation events, not new model rounds.

From the extracted directory after those stages are complete, save this faulty reader as a separate scratch file such as usage_check.py. The tool/recovery wrapper uses task; the fault wrapper uses task_after_crash. It only reads the three JSON files. Execute it; its assertion is intentionally expected to fail.

import json
from pathlib import Path

snapshots = []
for name in ["tool", "fault-main", "recover-main"]:
    record = json.loads(Path("work/" + name + ".json").read_text())
    snapshots.append(record.get("task", record.get("task_after_crash")))

def model_events(tasks):
    # BUG: each record is a cumulative snapshot, not a fresh event batch.
    return [(t["id"], e) for t in tasks for e in t["events"]
            if e["kind"] == "model_response"]

rows = model_events(snapshots)
print(json.dumps({"counted_model_responses": len(rows),
    "input_simulated_units": sum(e["payload"]["metadata"]["usage"]["input_units"] for _, e in rows),
    "output_simulated_units": sum(e["payload"]["metadata"]["usage"]["output_units"] for _, e in rows)}, sort_keys=True), flush=True)
assert len(rows) == 4, "cumulative snapshots were counted as new model calls"
assert [e["id"] for _, e in rows] == sorted(e["id"] for _, e in rows)

Locate, repair and rerun

Before repair the script prints 12 counted responses, 11,568 input simulated units and 903 output simulated units, then raises AssertionError: cumulative snapshots were counted as new model calls. The traceback points to an invariant; the cause is the flattening of snapshots inside model_events, not extra model requests in the task.

Modify only model_events in your copied analysis file. Build a dictionary keyed by (task_id, event_id) for this one ledger, verify that duplicate keys have identical payloads, and return unique entries ordered by event ID. If a duplicate key has conflicting content, raise an error rather than silently choosing one. Do not deduplicate by response_id or timestamp: simulated IDs repeat across tasks, and near times do not establish identity. If merging different ledgers, include ledger identity in the key.

Rerun the unchanged assertions. It must exit zero and print four responses, 3,856 input simulated units and 301 output simulated units. Hash the three source files before/after or retain their original copies; they must be unchanged. Record the false total, duplicate event IDs, flattening cause and corrected aggregation. This repairs an independently edited reader; running the capstone’s existing tests alone does not demonstrate the repair.

After the count is correct, another question remains: simulated usage cannot establish paid provider cost. More accurate counting does not change the measurement’s source.

code example

Retry attempts and business effects have different denominators

Two recorded model attempts belong to one task even when the second recovers the first. Both belong in attempt/usage accounting, while the business completion denominator still counts one task and merchant audit counts committed applications. A completed task can therefore have a failed attempt without two effects.

Acceptance task for this level

Save and run the faulty reader against the completed route records; capture the failing output. Implement event-identity deduplication with conflict detection, rerun the unchanged assertions, and submit before/after outputs plus unchanged input hashes.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why would deduplicating every task on metadata.response_id create a different bug?

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.