telemetry.pyTypes, labels, push and exporter; the info metric of the runInstruction session · Wednesday, December 9, 2026 · one hour of demonstration, one hour of application
The package of Lesson 7 runs the model in one command, but a run is only described by what it prints. This session gives the DataApp the three signals of observability, metrics, traces and logs, linked by the identifiers they share, and then closes the loop: a controller compares the indicators with their objectives and acts on the DataApp, calling a person only when it cannot correct it.
Project ritual
Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.
In the first hour the professor builds the reference of lab/lesson-10/ live with a coding agent, in four steps: the metrics, the traces and logs, the stack that links them and the controller that closes the loop. In the second hour each group applies the same method to its own DataApp.
telemetry.pyTypes, labels, push and exporter; the info metric of the runobservability.pySpans of run, task, request and SQL; JSON lines with the spanstack/Collector, Tempo, Loki, Grafana; from the alert to the log linecontrol.pySensor, comparator, controller, actuators and guardrailsA metric is a number kept over time, cheap to store and to evaluate, which says that something changed. A trace is the path of one execution as a tree of timed spans, which says where. A log is a record of a discrete event, which says what the program knew at that moment.
tcg_run_success 0, tcg:price_freshness_seconds. Aggregated by design, so the cost does not grow with the number of runs, only with the number of series. Prometheus evaluates them every 15 s and fires the alerts.
One run of 30.6 s is a trace of 38 spans: the run, 13 tasks, 20 requests to the source and 4 SQL files. The failing span carries the status ERROR, the attempts and the exception. Stored in Tempo.
JSON lines such as task.fail, with the attempt and the error text, written inside the span they describe. Stored in Loki and in out/logs/, and searched by any field.
The run_id names one run of the DataApp, the trace_id names its trace and the span_id names one operation inside it. Each signal carries the identifiers that lead to the next one, so the person on call goes from the alert to the line that explains it without guessing.
| Hop | Where | Identifier that leads on | Rehearsal of 08/11/2026 |
|---|---|---|---|
| 1 · alert | Prometheus, TcgRunFailed | its description reads tcg_run_info{run_id, trace_id} | "Run e44b5b8a34eb, trace 5d1d4930…" |
| 2 · metric | Grafana, table of tcg_run_info | the trace_id is a link to Tempo | one series per instance, replaced at each push |
| 3 · trace | Tempo, 17 spans | the span with status ERROR and its span_id | task extract_sets: 3 events "attempt failed" |
| 4 · log line | Loki, | span_id="ba8fc2d7…" | each line has the trace_id, a link back | 3 lines: ConnectionError: fault injected |
tcg_run_info, and in the traces and logs, which are built to hold one record per event.Step 01 · 0:22 · Metrics
The first step instruments the run without touching the layers: a module of telemetry owns the metrics, the client of the source is wrapped so that every request is timed, the run pushes at the end and an exporter reads the state of the warehouse.
telemetry.py, pipeline.py, cli.py (--push, metrics), tests/test_telemetry.py.
out/metrics.prom show the rows 7, 1490, 657, 896, 1153, 1414 and 1831?tcg_run_info, with the run and the trace?prometheus_client?[C] Character
You are a data engineer who operates pipelines in production. The package
tcg-dataapp of Lesson 7 runs the whole model in one command, but nobody
knows how a run went unless they read the terminal. The first of the three
signals is the metric: numbers kept over time, which a machine evaluates
every fifteen seconds even when nobody is looking.
[R] Request
Instrument the package with prometheus_client (version 0.4.1):
1. src/tcg_dataapp/telemetry.py with a class RunMetrics(run_id) that owns a
CollectorRegistry of its own and holds:
- tcg_task_attempts_total{task,status}, tcg_task_duration_seconds{task},
tcg_task_rows{task};
- tcg_source_request_duration_seconds{endpoint} (histogram, buckets 0.1
to 16 s) and tcg_source_request_errors_total{endpoint};
- tcg_quality_value{measure}, tcg_run_success, tcg_run_duration_seconds,
tcg_run_failed_tasks, tcg_run_last_success_timestamp_seconds (pushed
only after a success);
- tcg_run_info{run_id,trace_id} = 1, an info metric that names the run
and its trace, so an alert can lead to the trace.
2. An InstrumentedClient with the methods of TcgcsvClient that times every
call, so the etls layer does not import prometheus_client.
3. tcg-dataapp run --push URL: pushadd to a Pushgateway (job tcg_dataapp),
because a run of forty seconds ends before most scrapes; the same text
goes to out/metrics.prom.
4. tcg-dataapp metrics: an exporter on port 9108 whose collector reads the
warehouse at each scrape (rows and newest timestamp per tag, fact rows
and grain keys, last run) and reports tcg_warehouse_readable 0 instead of
failing while a run holds the DuckDB file.
5. Tests with the FakeClient: a good run, a failed run, the push and the
exporter.
Facts measured on 08/11/2026 (confirm before use):
- a real run: tcg_task_rows 7, 1490, 657, 896, 1153, 1414 and 1831;
fact_rows = fact_grain_keys = 5951; 13 requests; tcg_run_success 1.
[E] Example
tcg_task_rows{task="extract_prices_2026-11-07"} 1831.0
tcg_run_info{run_id="16fb5bb50f14",trace_id="5fddbb48a70b11fdd1df9bc8c0d4cf26"} 1.0
[A] Adjustments
- Names in snake_case with the prefix tcg_ and the unit as suffix; every
timestamp in Unix seconds.
- Labels with few values only (task, status, endpoint, measure). The run_id
appears only in tcg_run_info, which keeps a single series per instance
because each push replaces it.
- Call disable_created_metrics().
[T] Type of output
The files, the output of pytest and the lines of out/metrics.prom without
the buckets.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
The type says how the number may change and which functions make sense over it. Prometheus pulls from its targets every 15 s; a run of 30 s has no endpoint after it ends, so it pushes to a Pushgateway, which is scraped in its place.
| Type | Behaviour | In tcg-dataapp |
|---|---|---|
| Counter | only grows; read with rate() | tcg_task_attempts_total{task,status}, tcg_source_request_errors_total |
| Gauge | any value, up or down | tcg_task_rows, tcg_run_success, the freshness read by the exporter |
| Histogram | counts per bucket, plus sum and count | tcg_source_request_duration_seconds{endpoint}, 0.1 to 16 s |
| Info | a gauge always 1, whose labels are the data | tcg_run_info{run_id, trace_id} |
pushadd replaces only the metrics being sent, and the time of the last success is sent only after a success, so a failed run does not erase it.Step 02 · 0:30 · Traces and logs
The second step adds the other two signals with OpenTelemetry. The package calls only the API; the command line installs the SDK, which writes JSON lines to a file and, with an endpoint, sends spans and log records to a collector.
observability.py, spans in pipeline.py, telemetry.py and processors/gold.py, tests/test_signals.py.
[C] Character
You are the same data engineer. The metrics say that a run failed and how
long each task took, but not where inside the run the time went, nor what
the program said when it failed. Those are the other two signals: the trace,
which records the path of one run as a tree of spans, and the log, which
records discrete events. They are useful together only if they share
identifiers.
[R] Request
Add traces and structured logs with OpenTelemetry (opentelemetry-sdk and
opentelemetry-exporter-otlp-proto-http):
1. src/tcg_dataapp/observability.py:
- tracer() and logger() over the OpenTelemetry API, so the package does
nothing extra until a provider is installed;
- a JsonFormatter that writes one JSON object per line with ts (Unix
seconds), level, msg, service, run_id, trace_id and span_id of the
active span, and the fields passed in extra=;
- setup(log_path, otlp_endpoint): the JSON lines go to
out/logs/tcg-dataapp.jsonl; with TCG_OTLP_ENDPOINT, the spans go to
/v1/traces and the log records to /v1/logs of the collector, with a
batch processor; flush() at the end of each command.
2. Spans:
- tcg_dataapp.run, the root, with tcg.run_id, tcg.trigger and tcg.sets;
- task <name>, one per task, with an event "attempt failed" per failed
attempt, the exception recorded and the status ERROR when the task
fails for good; skipped tasks get tcg.status = skipped;
- tcgcsv.<endpoint>, one per request, kind CLIENT, with the server and
the number of records, from the InstrumentedClient;
- sql <file>, one per SQL file of build_gold, with db.statements.
3. Log lines run.start, task.ok, task.fail, task.skip and run.end, written
inside the span they describe, with a contextvar for the run_id.
4. tcg-dataapp run prints the trace_id next to the run_id, and
RunMetrics.finish receives the trace_id for tcg_run_info.
5. tests/test_signals.py with an InMemorySpanExporter installed once in
conftest.py: a run is one trace whose tasks are children of the root; a
failure marks its span and skips the dependents; every log line of a run
has its run_id and trace_id, and the line of a failing attempt has the
span_id of its task.
[E] Example
{"ts": 1794146637.498, "level": "error", "msg": "task attempt failed",
"run_id": "e44b5b8a34eb", "trace_id": "5d1d4930...", "span_id": "ba8fc2d7eb92ef1c",
"event": "task.fail", "task": "extract_sets", "attempt": 3,
"error": "ConnectionError: fault injected: source_down"}
[A] Adjustments
- The processors and the etls call only the OpenTelemetry API; the SDK is
configured by the command line and by the tests, never by a library.
- Spans of requests do not record the URL with parameters, only the
server and the endpoint.
- A JSON log line never carries data of the source, only counts and errors.
[T] Type of output
The files, the output of pytest, one trace printed as a tree (name,
duration, status) and the last five lines of the JSON log.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Each span records its start and end, its parent, attributes that describe it, events that happened inside it and a status. The tree of spans of one run shows the time that each part took and the exact place of a failure.
tcg_dataapp.run 30.6 s run_id 16fb5bb50f14 ├─ task extract_sets 1.07 s │ └─ tcgcsv.groups 1 request ├─ task extract_products 7.02 s │ └─ tcgcsv.products × 7 ├─ task extract_prices_2026-03-01 3.01 s │ └─ tcgcsv.archive records 657 ├─ ... (5 more extractions) ├─ task build_gold 0.05 s │ └─ sql 01_dimensions.sql … sql 04_live_reports.sql ├─ task check_quality 0.08 s └─ task write_report 0.17 s
{"ts": 1794146686.73,
"level": "error",
"msg": "task attempt failed",
"run_id": "e44b5b8a34eb",
"trace_id": "5d1d4930…6173a2",
"span_id": "ba8fc2d7eb92ef1c",
"event": "task.fail",
"task": "extract_sets",
"attempt": 2,
"error": "ConnectionError: fault
injected: source_down"}Step 03 · 0:38 · Stack and correlation
The third step brings up six containers and links them. The DataApp sends traces and logs to one address, the OpenTelemetry collector, which routes each signal; Grafana reads the three stores and turns the identifiers into links.
stack/compose.yaml, otel/config.yaml, tempo/tempo.yaml, grafana/provisioning/datasources/datasources.yml, prometheus/rules.yml.
promtool test rules print SUCCESS, with the trace in TcgRunFailed?TCG_FAULT=source_down, does the alert name the run and the trace?[C] Character
You are the same data engineer, now responsible for the place where the
three signals are read. A person on call receives an alert and must reach
the line that explains it in less than a minute: from the alert to the
metric, from the metric to the trace, from the failing span to its log lines.
[R] Request
Write stack/ with Docker Compose and verify the path of correlation:
1. compose.yaml with Prometheus v3.15.0, Pushgateway v1.11.2, the
OpenTelemetry collector contrib 0.141.0 (OTLP on 4317 and 4318), Tempo
2.10.10 (traces), Loki 3.6.3 (logs, with its OTLP endpoint) and Grafana
13.2.4, with anonymous access and viewers allowed in Explore.
2. otel/config.yaml: the traces pipeline exports to Tempo, the logs
pipeline to http://loki:3100/otlp.
3. grafana/provisioning/datasources/datasources.yml:
- Tempo with tracesToLogsV2 to Loki, filtering by the span:
{service_name="tcg-dataapp"} | span_id="${__span.spanId}";
- Loki with a derived field on the structured metadata trace_id that
opens the trace in Tempo.
4. prometheus.yml (Pushgateway with honor_labels, the exporter) and
rules.yml with the recording rule tcg:price_freshness_seconds and the
alerts TcgRunFailed, TcgNoSuccessfulRun, TcgRunTooSlow, TcgPricesStale,
TcgGrainBroken and TcgExporterDown. The description of TcgRunFailed
reads the run_id and the trace_id from tcg_run_info with the template
function query.
5. The dashboard: the panels of the run, a table of tcg_run_info whose
trace_id is a link to Tempo, a table of traces with an error and a panel
of the error and warning lines from Loki.
6. A run that fails on purpose (TCG_FAULT=source_down) and the path, with
the commands and the answers: alert → trace_id → span with status ERROR
→ its log lines in Loki.
Facts measured on 08/11/2026 (confirm before use):
- a good run with --with-today: 38 spans in Tempo, 15 log lines in Loki;
- the failed run: TcgRunFailed fired with "Run e44b5b8a34eb, trace
5d1d4930...", the span task extract_sets had 3 events "attempt failed",
and Loki returned its 3 lines by span_id.
[E] Example
curl -s -G localhost:3100/loki/api/v1/query_range \
--data-urlencode 'query={service_name="tcg-dataapp"} | span_id="ba8fc2d7eb92ef1c"'
[A] Adjustments
- promtool check config and promtool test rules must pass, run from the
image of Prometheus; rules_test.yml covers TcgRunFailed with its trace.
- Port 3000 may be taken: GRAFANA_PORT=3001.
- docker compose down -v at the end.
[T] Type of output
The files, the output of promtool, and a table with the four hops of the
path (where, query or click, what it returned).
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Each signal has its store and its language, and the questions of the person on call cross them. Values of the rehearsal of 08/11/2026.
| Signal and store | Query | Answer |
|---|---|---|
| metrics · Prometheus | topk(3, tcg_task_duration_seconds) | products 9.52 s, prices of 07/11 8.12 s, of today 6.83 s |
| metrics · Prometheus | tcg_gold_fact_rows - tcg_gold_fact_grain_keys | 0: the grain is intact |
| traces · Tempo (TraceQL) | {name="tcg_dataapp.run" && status=error} | the runs with source_down and duplicate_prices |
| traces · Tempo (TraceQL) | {name=~"tcgcsv.*" && duration > 3s} | the archives of the past dates |
| logs · Loki (LogQL) | {service_name="tcg-dataapp"} | trace_id="5d1d…" | 17 lines: 4 errors, 12 skipped tasks, 1 start |
| logs · Loki (LogQL) | … | event="control.tick" | one line per decision of the controller |
TcgRunFailed, TcgNoSuccessfulRun (26 h), TcgPricesStale (36 h), TcgGrainBroken, TcgRunTooSlow (120 s) and TcgExporterDown, each tested with promtool before it reaches production.A closed loop measures the output of a process, compares it with a reference and acts on the process to reduce the difference. Each element of the diagram has a counterpart in the DataApp, and the observability of the previous steps is only one of them: the sensor.
error = SLI − SLO. A positive error is a violation: data older than 36 h, a source failing above 50 %, a grain broken.
decide(), a pure function of the SLIs, the state and the clock, which returns one action per tick.
The next tick reads the effect of the last action. Without it, the system acts blindly, which is an open loop.
Metrics, traces and logs measure the process and show it. A dashboard and an alert give the measurement to a person, who then decides and acts. The loop closes only where something compares the measurement with the setpoint and acts on the process.
| Open loop | Loop closed by a person | Automatic closed loop | |
|---|---|---|---|
| In the DataApp | cron runs the DataApp at 06:00, whatever happened | the alert calls the person on call, who reruns or fixes | tcg-dataapp control reruns, opens the breaker or quarantines |
| Sensor | none | metrics, traces and logs | the same SLIs, read every tick |
| Decision | fixed in advance | a person, when awake and available | a rule, tested, every 5 minutes |
| Time to act | the next day | minutes to hours | one tick |
| Risk | stale or wrong data for a day | fatigue, nights, holidays | acting wrongly fast, which the guardrails limit |
An automatic action changes the process that the sensor reads next. A rerun against a source that is down fails again; a threshold crossed back and forth turns the action on and off at every tick. Guardrails bound what the controller may do, so its failure modes are slow and visible.
The data becomes stale above 36 h and fresh again only below 30 h. Between them, the previous state holds, so a value near the threshold does not flap.
When the source fails, the controller stops calling it. It probes after 300 s, then 600 s, then 1,200 s, and escalates at the fourth opening.
Reruns are at least 600 s apart. When the budget is spent, the problem is not transient, and the controller escalates.
After escalating, the controller holds every automatic action until the SLIs recover or a person runs control --acknowledge.
Step 04 · 0:46 · Closed loop
The last step writes the controller and the faults that rehearse it. The decision is a pure function, so every rule has a test with a fake clock; the actions run in the real DataApp, and each tick is itself a trace, a log line and a metric.
control.py, faults.py, config.py (setpoints and guardrails), cli.py (control), tests/test_control.py.
[C] Character
You are a reliability engineer who knows control theory. Everything built
so far is the sensor and the display of a loop: the DataApp is measured and
a person is warned. The loop is still open, because nothing compares the
measurement with the setpoint and acts on the process. Close it, and make
sure that it cannot oscillate nor act forever without a person.
[R] Request
Write src/tcg_dataapp/control.py and the command tcg-dataapp control:
1. Setpoints in config.py, from TCG_* variables: freshness 36 h (and 30 h
to leave the stale state: hysteresis), run duration 120 s, error rate of
the source 50 %, plus the grain and the success of the last run.
2. sense(con, now): the SLIs read from the warehouse (newest price, last
run of ops.pipeline_runs with its failed tasks and the class of the
error: source, quality or other; error rate of the extractions; grain).
3. errors(): SLI minus SLO; decide(sli, state, settings, now, history): a
pure function that returns one action:
- quarantine when the quality gate failed: move every batch that is not
in ops.good_batches (tag, timestamp, rows, md5 digest, recorded by
the last good run) to quarantine.db_ingestion, rebuild and check gold;
the frozen reports are tables and stay as they are; a second
quarantine within the window also escalates;
- open_breaker when the source failed; hold while it is open; probe
after a backoff that doubles at every opening; escalate at the fourth
opening;
- rerun (with the prices of today) when the data is stale or the run
failed for another reason, with a cooldown of 600 s and a budget of 3
reruns per 6 h; escalate when the budget is spent;
- resolve when every SLI is back within its SLO; none otherwise.
4. Escalation happens once: it sets state.escalated, optionally posts to
TCG_ESCALATION_WEBHOOK, and every later tick holds until the SLIs
recover or a person runs tcg-dataapp control --acknowledge.
5. The loop is observable: a span control.tick with control.sense and
control.act <action> (the rerun is a child of it), one JSON log line,
one row of ops.controller_actions with the trace_id, and the metrics
tcg_controller_* pushed as job tcg_controller.
6. faults.py: TCG_FAULT=source_down or duplicate_prices, applied to the
client of the run and of the probe.
7. tests/test_control.py with a fake clock: stale data is rerun and the
loop settles; a source down opens, backs off and escalates once without
any rerun; a source that returns closes the breaker alone; a bad batch
is quarantined and a repeated one escalates without oscillating; a
failure without a specific actuator is rerun within the budget.
[E] Example
tick 4a1b2d5ed253 open_breaker the source failed: error rate 100% against an SLO of 50%
→ breaker open for 20 s (opening 1)
tick df512f4b8f19 probe backoff elapsed; probing the source
→ probe failed (ConnectionError); breaker open for 80 s (opening 3) · escalated to a person
[A] Adjustments
- decide() never touches the database or the clock: everything comes in
its arguments, so each rule has a test.
- Protection (quarantine) is not limited by the budget; remediation
(rerun, probe) is.
- An SLI without an actuator, such as the duration of the run, is only
measured and alerted: say so in the code.
[T] Type of output
The files, the output of pytest, and a real rehearsal with short
guardrails (TCG_BREAKER_BACKOFF=20, --interval 10) for source_down and for
duplicate_prices, with the line of each tick.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Each failure has an action that is safe to repeat and a limit beyond which the action stops helping. Protection, which keeps a wrong number from being served, comes before remediation, which tries to bring the data back.
| Failure measured | Actuator | Guardrail | Escalates when |
|---|---|---|---|
| data older than 36 h | rerun with the prices of today | 600 s of cooldown, 3 per 6 h | the budget is spent |
| the source fails above 50 % | circuit breaker: hold, probe after a doubling backoff | no rerun while open | the fourth opening |
| a batch breaks the quality gate | quarantine every batch not in the last good state; rebuild and check gold | protection, outside the budget | the second quarantine in 6 h |
| the run takes more than 120 s | none | always: an alert to a person |
db_ingestion with its rows and an md5 digest in ops.good_batches. The quarantine moves every batch that differs to quarantine.db_ingestion, so the views of gold serve the last good numbers again; the frozen reports are tables and are not touched.The real DataApp with a fault injected and short guardrails: a backoff of 20 s, ticks every 10 s and escalation at the third opening of the breaker.
open_breaker error rate 100%, SLO 50% → open 20 s
hold breaker open 9 s more
probe probe failed → open 40 s
hold · hold · hold
probe probe failed → open 80 s
escalated to a person
hold · hold waiting for a person
(a person reruns the DataApp)
resolve breaker closed, escalation resolved
none every SLI within its SLOtransient
quarantine 3 batches, 5,159 rows
gold 5,951 rows = 5,951 keys
frozen September: 1,226 rows kept
rerun ok: 7,782 rows
none every SLI within its SLO
persistent, within 6 h
quarantine gold 5,951 = 5,951
second quarantine → escalated
hold · hold · hold · holdcontrol.tick, control.sense, control.act rerun and the whole run under it. TcgControllerEscalated fired in Prometheus when the controller gave up.The controller of the DataApp is small, but its structure is the one of the control loops that run most production systems: a declared desired state, a measurement of the current state, and an action that reduces the difference.
Each controller compares the desired state of a resource with the observed state and acts until they match: a Deployment of three replicas recreates a pod that died.
A setpoint of CPU or of a custom metric, a sensor in the metrics API, and an actuator on the number of replicas, with a stabilisation window against oscillation.
An alert sent to a webhook that runs a playbook closes the loop for a known failure; routing, grouping and silences are its guardrails.
The SLO allows a measured amount of failure. While budget remains, changes go out; when it is spent, releases stop. It is a feedback loop on how a team works.
Each group applies the method to its own DataApp, the package of Lesson 7 or the flow of Lesson 8, with prompt 05. The measure of success is a failure rehearsed on purpose and followed from the alert to the log line, and one SLO whose loop either recovers or escalates once.
promtool testReadings and a video assigned on Adalove for this week, on the metric types of Prometheus, its architecture and its relation with OpenTelemetry, with the reading material of the session.
Official description of counters, gauges, histograms and summaries in Prometheus.
A Prometheus co-founder presents its architecture, dimensional data model and pull-based collection.
Comparison of metric types and collection models in Prometheus and OpenTelemetry. The reading material of this session is Lesson 10 material.
Metrics and Telemetry · 09/12/2026 · Prof. Afonso
By the end of the session, students should be able to instrument a DataApp with metrics, traces and structured logs linked by run, trace and span identifiers, follow a failure from the alert to the log line that explains it, and close the loop on one SLO with a controller that compares the indicator with its setpoint, acts within guardrails and escalates to a person when it cannot recover.
Demonstration followed by application. In the first hour the professor builds the observability of the Lesson 7 package live with a coding agent and four CREATE prompts, injecting faults to follow a failure through the three signals and to watch the controller recover or escalate, and distinguishes observability, the sensor and display of the loop, from control, which compares and acts. In the second hour each group applies the method to its own DataApp with prompt 05.