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: Implementation · Build it. 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.

Implementation · Build it

Implement and observe · Audit actual usage and receipt events

Objectives of this level: Build a read-only report from route JSON, attribute recorded work without double counting, and clearly label missing production measurements.

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 after the recovery stage

From the extracted capstone directory, first complete the README flow through approval, fault-main and recover-main. Required input is work/recover-main.json, whose top level contains task, worker and merchant_audit. The task contains events, retrieval, proposal_hash, operation_key and receipt. Each event has id, kind, payload and created. Run the following from that directory. It only reads JSON and does not restart a model, service or task.

import json
from pathlib import Path

record = json.loads(Path("work/recover-main.json").read_text())
task = record["task"]
events = task["events"]
models = [e["payload"]["metadata"] for e in events if e["kind"] == "model_response"]
tools = [e["payload"] for e in events if e["kind"] == "tool"]
failures = [e for e in events if e["kind"] == "model_failure"]
requests = [e for e in events if e["kind"] == "model_request"]
usage = [m.get("usage") for m in models]
assert all(u is not None and u["source"] == "simulated" for u in usage)
receipt = task["receipt"]
count = sum(r["task_id"] == task["id"] for r in record["merchant_audit"]["returns"])
assert receipt["operation_key"] == task["operation_key"]
assert receipt["proposal_hash"] == task["proposal_hash"]
assert count == 1
print(json.dumps({"task_id": task["id"], "status": task["status"],
    "model_requests": len(requests), "model_responses": len(models), "model_failures": len(failures),
    "tool_events": len(tools), "input_simulated_units": sum(u["input_units"] for u in usage),
    "output_simulated_units": sum(u["output_units"] for u in usage),
    "business_returns_for_task": count}, sort_keys=True))
print(json.dumps({"model_work_ms": round(sum(m["latency_ms"] for m in models), 3),
    "tool_work_ms": round(sum(t["latency_ms"] for t in tools), 3),
    "retrieval_inside_tool_ms": task["retrieval"]["latency_ms"]}, sort_keys=True))
for e in events:
    if e["kind"] in {"action_request", "action_unknown", "receipt_lookup", "business_receipt"}:
        p = e["payload"]
        print(json.dumps({"event_id": e["id"], "kind": e["kind"],
            "operation_key": p.get("operation_key", p.get("payload", {}).get("operation_key",
                                 (p.get("receipt") or {}).get("operation_key"))),
            "found": p.get("found"), "reconciled": p.get("reconciled")}, sort_keys=True))

Interpret the output at the right boundary

The first row must report main-return, completed, four model requests/responses, zero model_failure events, three tool events, 3,856 input simulated units, 301 output simulated units and one merchant application for this task. These counts/units follow the standard deterministic route input; changed questions or prompts can change the units.

The second row prints durations from your actual record. They vary by run and machine. tool_work_ms includes the retrieval tool’s duration; retrieval_inside_tool_ms is a nested component, so adding it again double counts. Summing model/tool work is not an end-to-end wall-clock measurement; it omits route-stage pauses, review waiting and other uninstrumented work. These are local measured durations of a deterministic generator and service, not production model latency. The JSON includes no parent/span IDs or queue spans.

The last rows show receipt lookup, action request, unknown outcome, successful lookup and reconciled receipt. Correlate the payload shapes rather than assuming every event has an operation_key in the same place. Initial lookup may have no receipt and hence no payload key. The task-level operation key supplies the scope; check exact receipt binding before treating lookup as proof.

The source also records model_request before invoking the adapter and model_failure on a provider failure, with usage=null. In a general reporter, count requests, responses and failures separately and mark gaps; never substitute responses for all attempts or missing usage for zero. This standard route has no provider failure, and the script intentionally checks its simulated usage contract.

Independent reader work

Implement your own reporter in a separate scratch file before using this reference. Return the counts, usage source, per-task business application count and event IDs that connect the unknown outcome to its receipt. Identify one field needed for real spans and one log field that should be redacted. The teaching records store full model requests and tool arguments for local reproducibility; they are not a safe default production logging policy.

code example

Missing usage requires reconciliation

After a provider timeout, the response usage may be absent even if the provider did work. Preserve the missing state and the available request correlation, then reconcile with provider/account records if available. Replacing null by zero understates usage; applying a price to simulated units does not create an actual bill.

Acceptance task for this level

Implement a read-only summary for recover-main.json that reports actual attempt/event counts, labels simulated usage, links the unknown action to the bound receipt and lists missing span fields. Compare its counts with this reference without modifying inputs.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Can we add retrieval_inside_tool_ms to tool_work_ms to obtain total tool time?

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.