Module: L3-M01 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L03 · Next: L05
1. Introduction
When an agent answers wrongly or stops unexpectedly, the first question is what it did. With only the final answer, a tester has to guess. This lesson teaches how to record one run as a trace made of spans (units of work) and logs (log records) that are enough to answer the question without rerunning, and how to check that trace itself with a lint suite. This is the "instrument a mock agent" part of the module: we attach a recorder to the loop of L02.
Two definitions for this lesson (not quoted from any source). Observability is the ability to answer "what did this specific run do and why did it stop" from the records, without rerunning. Monitoring is tracking aggregate metrics over time (such as average cost per day); it answers "is the system healthy", not a question about one run. The lab does only the first. The vocabulary of traces and logs comes from two OpenTelemetry concept pages [R1][R2], but the lab does not use the OpenTelemetry SDK or its wire format.
2. Learning objectives
- Define trace, span, span event and log record using the vocabulary of [R1][R2]. Read: §4.1.
- Read the span tree of one agent run. Practice: §8.2 part A, §8.3 (lines 1 to 6).
- Explain the logical clock and deterministic ids, and their cost. Read: §4.3; practice: §8.4.
- Apply redaction of sensitive data and state what it does not catch. Practice: §8.2 part C, §8.3 (lines 7, 10 and 11), §9 (TODO 1).
- Lint a trace and state what the lint does not check. Practice: §8.2 parts B and D, §8.3 (lines 8 and 9), §9 (TODO 2).
- Repair a broken trace so that the lint is clean without changing any id or span name. Practice: §9.
3. Prerequisites and tools
- L02 (the loop, stop reasons), L01 (the tool layer); L1-M05-L05 (transcript). The lab code is
code-labs/l3-m01. - Separating the senses. A trace here is the span tree of one agent run; it differs from the "transcript" of L1-M05-L05 (a conversation record for golden-file comparison) and from the "trajectory" (a sequence of actions for evaluation, module L3-M04): a trace is the raw record, a trajectory is what an evaluator reads out of it. A span here is a unit of work with a start and an end, which differs from the "evidence span" of L2-M06. A trace also differs from the "reasoning trace" of ReAct in L03, which is the thought text; in the lab's trace, a thought is just an event. A log is a record attached to a span, not pytest's log. Step as in L02. The lab's clock is a logical counter, not real time.
4. Concept explanation
4.1 Trace, span and log in OpenTelemetry
The OpenTelemetry concept page on traces describes it this way: a trace gives the big picture of what happens when a request is sent to an application; a span is "a unit of work or operation" and is the building block of a trace [R1]. Each span carries an immutable context made of the trace id (the trace it belongs to) and its own span id; a root span has an empty parent id [R1]. A span has a start and an end time, attributes (key-value pairs annotating the work), events ("a structured log message (or annotation) on a Span", marking a point in time) and status (Unset, Error or Ok) [R1].
The page on logs describes a log as a timestamped text record, structured or not; a log record has a time, a severity, a body and attributes; the TraceId and SpanId fields let a log be tied to a trace and a span, and the page recommends structured logs for production [R2]. The lab takes these words (trace id, span id, parent id, start, end, status, attributes, events; clock, severity, body, attributes for logs) as the mold for its records. The lab's specific field names (such as start, end) are the lab's own.
4.2 The span tree of one agent run
The lab's convention: one run span (the root) contains step spans; each step contains one model span and, if a tool is called, one tool span. The recorded attributes: task, max_steps, budget on the run; step on each step; action on the model; tool.name, arguments, cost, and error if any on the tool; stop_reason, steps and used are written to the run at the end. The policy's "thought" is an event on the model span, the plan is an event on the step, and an abnormal stop reason is a WARN or ERROR log attached to the matching span.
4.3 The logical clock and deterministic ids
Each time a span starts or ends, or an event or log happens, the Tracer's counter goes up by one and hands out that number as the "time". Two identical runs give identical traces, tests do not depend on the machine's clock, and no random run-time effect makes tests flaky. Ids are deterministic too: the trace id is the first part of the SHA-256 of a seed, and the span id is a counter. The cost: the lab's trace has no real latency; the difference between two ticks only tells you order and nesting, not how long something took. Real latency analysis belongs to a later module (L3-M06).
5. Technical deep dive
5.1 Redacting sensitive data before writing
redact(value) returns a redacted copy and does not modify its input. For an object, an entry is replaced by [REDACTED] when its key, after NFKC normalization, lowercasing and removing everything except letters and digits, ends with a sensitive name (api key, password, token, secret, authorization, cookie, email, phone): so API-Key, user_password, x-api-key, the full-width form and a<invisible character>pi_key all match, while tokens does not. A string that is itself JSON text (such as the raw arguments of a tool call) is parsed and redacted inside, then written back as JSON. For any other string, after removing invisible characters and NFKC normalization, if it contains an e-mail address, a key of the form sk- (8 characters or more, upper or lower case) or a bearer token, the matching part is replaced. Nesting deeper than 20 levels is replaced as a whole block (fail closed). Tracer calls redact as soon as it records attributes, events and logs, so secrets of the known kinds never enter the trace in the first place; the tool itself still writes raw data into the sandbox, because that is the environment, not the trace.
Blind spots pinned by tests: name at example dot com, a short sk- key, a sentence like "my password is ...", people's names and addresses, keys that do not end in a known name (mail, pass, pwd, credentials), and any secret in a format the lab does not know. A redactor also cannot save a secret that has been split across two fields.
5.2 The trace structure lint
lint_trace(records) returns a sorted list of CODE:location strings; empty means no check fired. The groups of checks:
- Structure:
EMPTY_TRACE,MISSING_FIELD,BAD_KIND(a span kind outside the lab's five kinds),BAD_TYPE(a time that is not a non-negative integer;TrueandNaNare both rejected),DUPLICATE_SPAN_ID,MIXED_TRACE_IDS. - Parent-child relations:
NO_ROOT,MULTIPLE_ROOTS,ORPHAN_SPAN(the parent id does not exist),SELF_PARENT,PARENT_CYCLE. - Time:
UNENDED_SPAN,CLOCK_BACKWARDS(ends before it starts),CHILD_OUTSIDE_PARENT,EVENT_OUTSIDE_SPAN(an event whose time falls outside its span),BAD_STATUS. - Logs:
ORPHAN_LOG,LOG_CLOCK_ORDER,LOG_OUTSIDE_SPAN,BAD_SEVERITY. - Leftover sensitive data:
SENSITIVE_LEFT(reusing exactly the identifier ofredact). When malformed input makes the lint crash, it returnsMALFORMED_RECORD:<error type>instead of raising.
Two conventions to know: a span whose end time equals its start time is not reported (a real clock can repeat); and a log without a span_id is accepted (it is not tied to any span), but a log whose span_id points to a span that does not exist is ORPHAN_LOG.
5.3 The agent convention lint
lint_agent_trace checks the lab's conventions: exactly one root run span (NO_RUN_SPAN); stop_reason is one of the six values of L02 (BAD_STOP_REASON); the run's steps are numbered 1 to n in order of start (STEP_NUMBERING); every tool span sits under a step (TOOL_OUTSIDE_STEP) and has a tool.name (TOOL_NAME_MISSING); the number of steps does not exceed max_steps (STEPS_EXCEED_MAX); and if the stop reason is max_steps the number of steps must equal max_steps (STOP_REASON_MISMATCH); a later step must not start before the previous step ends (STEP_OVERLAP); and the lab's clock must not repeat a tick (DUPLICATE_TICK). It does not check whether the stop reason is the real cause or whether a tool result obeys its contract.
6. The QA perspective
6.1 The trace as evidence for tests
A test can assert on the trace instead of on the answer: the stop reason, a step count not above max_steps, the number of tool errors, the tool names in order. The lab's tests run every policy on the nine tasks and require both lints to be clean, then compare summarize(trace) with the loop's result: the stop reason and the step count must match. A report that says "three steps" when the trace has four steps is a bug in the report: the trace is the source to check against, but it needs a lint itself (§6.3).
6.2 Secrets and traces
Traces are often sent elsewhere (a log store, other people on the team), so redact before writing, not after. SENSITIVE_LEFT is the second layer: it catches a trace built from another source (an external tool, a hand edit) that the lab's redactor has not passed through. The lab gives no legal opinion about personal data; specific rules need official sources and a person with authority.
6.3 What the lint does not say
A trace with the right structure can still be wrong in content: the test test_the_agent_lint_does_not_check_content changes a tool name in a span and both lints stay clean. lint_trace does not check whether two sibling spans overlap or whether ticks repeat (only lint_agent_trace checks that, for steps and ticks). The lint does not know which tools were really called, does not know whether a step is missing a tool span (a step with an error and no tool span is still valid), does not know whether attributes follow any naming standard, and does not know whether the trace was sampled or truncated.
7. Real-world scenarios
Scenario 1 (fictional): "The report says three steps, the trace has four". A weekly report for HocVui Assistant says every t04 run used three steps. A test comparing summarize with the report finds four steps (look up the formula, compute, write the notebook, answer). The report's author had counted tools instead of steps. The bug is in the counting, not in the agent; record it and fix the report.
Scenario 2 (fictional): "An API key in a tool argument". A task that saves a contact calls notes_add with text containing an e-mail address and a key of the form sk-. Thanks to redact, the arguments attribute of the tool span records [REDACTED] in both places; the sandbox directory still holds the raw content, because that is the tool's doing (§8.3). QA records two things: the trace is clean, but the tool has stored sensitive data; the tool's design, not the trace, is where to fix it.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m01
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 79 passed
8.2 Run the demo
python -m lab.demo l04
Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions are identical). Every policy, tool and trace is simulated:
A. trace of react on t05 (logical clock, not wall time)
run [1-21] ok
step [2-8] error
model [3-5] ok tool_call
tool [6-7] error calc
step [9-15] ok
model [10-12] ok tool_call
tool [13-14] ok calc
step [16-20] ok
model [17-19] ok final
B. summary and lints: {'steps': 3, 'tool_spans': 2, 'tool_errors': 1, 'duration_ticks': 20, 'stop_reason': 'final'} [] []
C. redaction
{'API-Key': '[REDACTED]', 'note': 'mail [REDACTED]', 'n': 3}
D. broken traces
orphan span: ['ORPHAN_SPAN:sp-003']
end before start: ['CLOCK_BACKWARDS:sp-003', 'EVENT_OUTSIDE_SPAN:sp-003']
unended span: ['UNENDED_SPAN:sp-002']
secret left: ['SENSITIVE_LEFT:sp-004.attributes.password']
empty trace: ['EMPTY_TRACE']
Reading the output: part A is the span tree of task t05 (the calc tool fails transiently once): the numbers in square brackets are the start and end on the logical clock. The policy's thought event sits within the model span's range (tick 4 of span [3-5]) and is not printed in the tree. Step 1 has status error because the tool returned an error; step 2 retries and succeeds; step 3 is the final answer. Part B: three steps, two tool spans of which one is an error, the run lasts 20 ticks, stop reason final, both lints clean. Part C: redacting one dict. Part D: four times breaking the trace in one place and linting, and one empty trace (swapping the times of span sp-003 adds the code EVENT_OUTSIDE_SPAN, because that span's thought event falls outside the new range); the last example says sp-004.attributes.password, that is, span sp-004, field attributes, key password.
8.3 Try it yourself
Save it as try_l04.py in the lab's root directory (next to lab/, not inside lab/), run python try_l04.py, then delete the file:
import json
from lab import policies as P
from lab.loop import run_agent
from lab.tools import Sandbox
from lab.trace import Tracer, lint_trace, redact, render_tree
import tempfile
with tempfile.TemporaryDirectory() as root:
tr = Tracer("try-l04")
secret = {"kind": "tool_call", "tool": "notes_add",
"arguments": json.dumps({"name": "lien_he", "text": "gọi hs01@example.test, khóa sk-ABCDEFGH12345"})}
run_agent(P.Scripted([secret, {"kind": "final", "text": "Đáp án: xong"}]), Sandbox(f"{root}/s"), tracer=tr, task_id="demo")
recs = tr.records()
print(render_tree(recs))
print([r["attributes"]["arguments"] for r in recs if r["type"] == "span" and r["kind"] == "tool"])
print(lint_trace(recs), len(recs))
broken = [dict(r) for r in recs]
broken[2] = {**broken[2], "parent_id": "sp-099"}
print(lint_trace(broken))
print(redact({"Api-Key": "x", "ghi_chu": "ok", "n": 1}), redact("s\u200bk-ABCDEFGH12345"))
print(redact("liên hệ name at example dot com"))
Output (Python 3.14.6 and 3.12.14 identical):
run [1-12] ok
step [2-7] ok
model [3-4] ok tool_call
tool [5-6] ok notes_add
step [8-11] ok
model [9-10] ok final
['{"name": "lien_he", "text": "gọi [REDACTED], khóa [REDACTED]"}']
[] 6
['ORPHAN_SPAN:sp-003']
{'Api-Key': '[REDACTED]', 'ghi_chu': 'ok', 'n': 1} [REDACTED]
liên hệ name at example dot com
Reading it: lines 1 to 6 are the span tree of a two-step run. Line 7: the arguments attribute of the tool span is raw JSON; the lab parses it, redacts the e-mail and key inside, and writes it back. Line 8: the trace is clean and has 6 records: six spans (one run, two steps, two models, one tool), no logs. Line 9: changing the parent_id of the third record to an id that does not exist gives exactly one code, ORPHAN_SPAN:sp-003. Line 10: the key Api-Key is redacted despite the different capitalization; an sk- string with an invisible character in the middle is redacted too. Line 11: the string "name at example dot com" is not redacted: a blind spot.
8.4 Run the lesson's tests
python -m pytest tests/test_l04_trace.py -v
Result: 16 passed. Read test_ids_are_deterministic_and_the_logical_clock_never_repeats, test_redaction_handles_key_variants_and_hidden_characters, test_redaction_blind_spots_are_real, test_lint_flags_log_problems and test_the_agent_lint_does_not_check_content. The tests run on in-memory values and files in pytest's temporary directory.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
lint_trace returns EMPTY_TRACE for a non-empty list |
The elements do not have "type": "span" |
Check the type key of each record |
CHILD_OUTSIDE_PARENT after a hand edit |
Edited a span's start or end without editing the parent span |
Edit to fit the parent's range, or change the parent |
redact changes text in an ordinary string |
The string matches a pattern, and its invisible characters are dropped | That is the behavior: a string that matches a pattern is rewritten from the cleaned version |
9. Independent exercise
Problem: Write your own data redactor and repair a broken trace.
Requirements: complete exercises/test_l04_trace.py:
- TODO 1:
my_redact(value): return a copy with sensitive content replaced by[REDACTED], as described in the function's comment; do not modify the input. - TODO 2:
FIXED_TRACE: a copy ofBROKENrepaired so thatlint_tracereturns empty, changing as little as possible: the same ids, the same names, the same number of records.
Test data: exercises/ex_redact.json (four input cases), exercises/ex_trace.json (a simulated trace with three kinds of errors).
Deliverable: the function and variable above, in the file exercises/test_l04_trace.py itself.
Acceptance criteria: python -m pytest exercises/test_l04_trace.py passes (2 tests), compared with lab.trace.redact and lab.trace.lint_trace. The tests do not check whether you catch secrets beyond the given cases, and do not check whether the repaired trace reflects what really happened.
Hints: TODO 1: compare keys after normalizing them rather than verbatim, and handle both keys and string values. TODO 2: run lint_trace(BROKEN) to learn the codes, then fix each kind; a clock error can be fixed in several ways, choose the one that keeps the parent-child relations right.
10. Knowledge check
0/18 done · Results are kept in this browser only.
P02 · True or false
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
A colleague wrote their own redactor. The function masks the right keys at the top level but exposes a sensitive key of a tool call nested inside an object. Find the bug.
import re
SENSITIVE = ("password", "token", "secret", "apikey")
def my_redact(value):
if isinstance(value, dict):
return {k: "[REDACTED]" if re.sub(r"[^a-z0-9]", "", k.lower()).endswith(SENSITIVE) else v
for k, v in value.items()}
if isinstance(value, list):
return [my_redact(v) for v in value]
return valueP08 · Short answer
A trace of a two-step run (a lookup then the final answer) is edited by hand: the tool.name attribute of the tool span is changed from lookup to calc. What do lint_trace and lint_agent_trace return, does summarize change, why, and is there any way in the lab to see the mismatch?
P09 · Essay
Write 5-8 sentences about the following situation (fictional, simulated): a run calls notes_add with text equal to Phụ huynh em Mai: 0987654321; mat khau: abc123; luu y: ph@lop5a.example. The arguments attribute of the tool span records {"name": "lien_he", "text": "Phụ huynh em Mai: 0987654321; mat khau: abc123; luu y: [REDACTED]"}. State what redact masked and what it missed, why, and what must be done outside the trace.
P11 · Recall
Lesson: L3-M01-L02P12 · Recall
Lesson: L1-M05-L05P13 · Recall
Lesson: L3-M01-L01P14 · Multiple choice
P15 · Select all that apply
P16 · True or false
P17 · Match
P18 · Fill in the blank
11. Summary
- Concepts: trace, span, log, event, status, attributes in the vocabulary of [R1][R2]; the run-step-model-tool tree; the logical clock; redaction of sensitive data; the structure lint and the convention lint.
- Skills: reading a span tree, asserting on the trace instead of on the answer, redacting before writing, repairing a broken trace.
- Traps: believing the redactor is complete; believing a clean lint means a correct trace; reading the difference of two ticks as real time; redacting the trace while forgetting that the tool stored raw data.
- You can now: take an unfamiliar run and answer from the trace what it did, say which secrets may remain and which lint has not checked.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Traces (OpenTelemetry concepts) | OpenTelemetry (CNCF) | https://opentelemetry.io/docs/concepts/signals/traces/ | 2026-11-04 | Read the page text (definitions of trace, span, span context, parent id, attributes, events, status), checked against the fetch tool's automatic summary |
| R2 | Logs (OpenTelemetry concepts) | OpenTelemetry (CNCF) | https://opentelemetry.io/docs/concepts/signals/logs/ | 2026-11-04 | Read the page text (log record, fields, correlation with traces, structured logs), checked against the automatic summary; the specification was not read |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Observability | Khả năng quan sát: trả lời về một lần chạy cụ thể từ bản ghi |
| Monitoring | Giám sát: theo dõi chỉ số tổng hợp theo thời gian |
| Trace | Dấu vết: cây span của một lần chạy |
| Span | Đoạn việc có điểm bắt đầu và kết thúc, nằm trong cây của một trace |
| Span event | Sự kiện trên span: ghi chú có cấu trúc tại một thời điểm |
| Log record | Bản ghi nhật ký có thời điểm, mức nghiêm trọng, thân và thuộc tính |
| Logical clock | Đồng hồ logic: bộ đếm thay cho giờ thật |
| Redaction | Che dữ liệu nhạy cảm trước khi ghi |
| Trace lint | Lint trace: kiểm cấu trúc, quan hệ, thời gian, log và dữ liệu nhạy cảm còn sót |