Module 8 Β· Information Systems Β· Lesson 10 Β· Week 9

Metrics and Telemetry

Reference material for the session in which the professor makes the Python package of Lesson 7 observable, live and with a coding agent: metrics in Prometheus, traces in Tempo and structured logs in Loki, linked by the identifiers they share, and then a controller that closes the loop on the objectives of the DataApp, with guardrails and one escalation to a person. In the second hour each group applies the same method to its own DataApp.

About this session

Metrics and Telemetry Β· 09/12/2026 Β· Prof. Afonso

Learning objective

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.

Session strategy

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.

Session structure

  1. Daily β€” 15 min
  2. The three signals and their correlation (7 min)
  3. Step 01 β€” metrics in Prometheus (8 min)
  4. Step 02 β€” traces and structured logs with OpenTelemetry (8 min)
  5. Step 03 β€” the stack; from the alert to the log line (4 min)
  6. The closed loop, and why observability alone does not close it (4 min)
  7. Step 04 β€” the controller of the DataApp with injected faults (14 min)
  8. Second hour β€” the groups apply it to their DataApp (60 min)
Part IFoundations

1. How to read this material

This material accompanies Lesson 10, which has two hours. In the first, the professor builds live, with a coding agent and four CREATE prompts, the observability of the Python package of Lesson 7: its metrics, its traces and its structured logs, a stack that stores and links the three signals, and a controller that closes the loop on the objectives of the DataApp. In the second hour each group applies the same method to its own DataApp.

Part I explains what each signal answers and how the three are linked. Parts II, III and IV follow the first three steps of the session: the metrics, the traces and logs, and the stack in which a person goes from an alert to the log line that explains it. Part V presents the closed loop in the vocabulary of control theory, argues that observability alone does not close it, and describes the controller of step four with its guardrails. Part VI gathers the prompts, the tests, the reference numbers and what the rehearsal revealed. Every number was measured on 08/11/2026 with the reference of lab/lesson-10/: the package tcg_dataapp 0.4.1, the OpenTelemetry SDK 1.45.2, prometheus-client 0.26.0, DuckDB 2.0.0, Prometheus 3.15.0, the Pushgateway 1.11.2, the OpenTelemetry collector 0.141.0, Tempo 2.10.10, Loki 3.6.3 and Grafana 13.2.4. Every date is Unix time in seconds.

2. Why a DataApp must be observed

The package of Lesson 7 records every attempt of every task in ops.pipeline_runs, which explains a run once someone decides to look at it. A DataApp that runs every day at six in the morning fails when nobody is looking, and the failures that matter most are often silent: a scheduler that stopped calling the run, a source that answers without new prices, a batch that arrives duplicated. Observability is the property of a system whose internal state can be inferred from what it emits, and it rests on three kinds of telemetry, each answering a different question of the person who operates the DataApp.

Question of the operatorSignal that answers itIn tcg-dataapp
Is something wrong right now?metrictcg_run_success, tcg:price_freshness_seconds and the alerts on them
Where, inside the run, did it go wrong or slow down?tracethe span with status ERROR among the 38 spans of a run
What exactly did the program know at that moment?logthe JSON line task.fail with the attempt and the error text
Which run, which trace and which operation is this?the identifiers shared by the threerun_id, trace_id, span_id

3. Metrics, traces and logs

A metric is a numeric measurement aggregated over time. Its cost depends on the number of series and not on the number of events, which makes it cheap to store and fast to evaluate, and therefore the signal on which alerts are built; the price of this economy is that a metric says that something changed but not which execution caused it. A trace records the path of one execution as a tree of spans, each one an operation with a start, an end, a parent, attributes, events and a status; it shows where the time went and where the failure happened, at the cost of one record per operation. A log records discrete events with their context; it carries the most detail, such as the text of an exception, and it is the most expensive to keep and the hardest to aggregate unless it is structured.

MetricsTracesLogs
unita sample of a seriesa span of a tracea line, one event
answerswhether and how muchwhere and how longwhat and why
cost grows withthe number of seriesthe number of operationsthe number of events and their size
store in the labPrometheusTempoLoki and out/logs/
query languagePromQLTraceQLLogQL
in one good runone push at the end1 trace of 38 spans15 lines

OpenTelemetry, the subject of the third self-study, standardises the three signals and the protocol that carries them, OTLP, so that the code is instrumented once and the stores can change. Prometheus defines the format of metrics that most tools read. The package uses both: prometheus_client for the metrics, as in the curriculum of the module, and the OpenTelemetry SDK for traces and logs.

4. Correlation: three identifiers

Three tools that do not share identifiers give three partial views, and the person on call must guess which log line belongs to which alert. The package therefore writes the same identifiers in every signal. The run_id names one run of the DataApp and is the key of ops.pipeline_runs; the trace_id names the trace of that run; the span_id names one operation inside it. Each signal carries the identifier that leads to the next, which turns an investigation into four hops.

HopWhereIdentifier that leads onIn the rehearsal of 08/11/2026
1 Β· alertPrometheus, TcgRunFailedthe description reads tcg_run_info{run_id, trace_id}"Run e44b5b8a34eb, trace 5d1d4930…"
2 Β· metricGrafana, table of tcg_run_infothe trace_id is a link to Tempoone series per instance
3 Β· traceTempo, 17 spansthe span with status ERROR and its span_idtask extract_sets, 3 events "attempt failed"
4 Β· log lineLoki, | span_id="ba8fc2d7eb92ef1c"each line has the trace_id, a link back3 lines with ConnectionError

The identifiers obey the rule of cardinality of Part II. The run_id is never a label of every metric, because each run would create new series; it appears in one info metric, tcg_run_info, whose single series per instance is replaced at every push, and in the traces and logs, whose stores are built to hold one record per event.

Part IIMetrics

5. Prometheus: targets, types and the push of a batch job

Prometheus collects by pulling. Every fifteen seconds it requests the endpoint /metrics of each target and stores each line as a sample of a time series, identified by a name and a set of labels. Because Prometheus initiates the scrape, it knows when a target does not answer and records it in the series up. A run of the DataApp, however, lasts about thirty seconds and has no endpoint after it ends, so it pushes its metrics to a Pushgateway, which keeps the last values of each group and is scraped in its place. The push uses pushadd, an HTTP POST that replaces only the metrics being sent, so a failed run does not erase tcg_run_last_success_timestamp_seconds, which is sent only after a success. Numbers that belong to the data rather than to a run, such as the age of the newest price, are read by an exporter, tcg-dataapp metrics, which opens the DuckDB file at each scrape.

TypeBehaviourIn tcg-dataapp
Counteronly grows; read with rate() or increase()tcg_task_attempts_total{task,status}, tcg_source_request_errors_total{endpoint}
Gaugeany valuetcg_task_rows, tcg_run_success, the timestamps, everything the exporter reads
Histogramobservations per cumulative bucket, with sum and counttcg_source_request_duration_seconds{endpoint}, 0.1 to 16 s
Infoa gauge always 1 whose labels are the informationtcg_run_info{run_id, trace_id}

6. Names, labels and cardinality

The name of a metric starts with the prefix of the application, tcg_, and ends with its unit in base units, _seconds, with _total closing a counter and _timestamp_seconds a moment in Unix time, so that time() - metric is an age. Each distinct combination of label values is a series that Prometheus indexes, and the number of series, the cardinality, is the product of the values of each label. The labels of the package (task, status, endpoint and measure) have at most a dozen values each. An identifier of run or of product would create a series per run or per card; such identifiers belong to the traces, to the logs and to the gold layer.

7. The telemetry module

telemetry.py owns every metric in a registry of its own, so that the tests can create as many runs as they need. RunMetrics holds the metrics of one run; InstrumentedClient wraps the client of tcgcsv.com, times each call into the histogram and, since this lesson, also opens a child span per request; WarehouseCollector reads the warehouse at each scrape and reports tcg_warehouse_readable 0 instead of failing while a run holds the DuckDB file, which accepts one writer process and no reader while it writes.

src/tcg_dataapp/telemetry.py
"""Metrics of the DataApp in the Prometheus format (traces and logs are in observability.py).

Two ways of reaching Prometheus, because the DataApp has two kinds of process:

    RunMetrics   the batch run (tcg-dataapp run) lives for about forty seconds,
                 shorter than the scrape interval, so it records its metrics while
                 it runs and pushes them to a Pushgateway at the end; it also writes
                 them to out/metrics.prom, in the text format.
    WarehouseCollector
                 the exporter (tcg-dataapp metrics) is a long-running process that
                 Prometheus scrapes; at every scrape it reads the state of the
                 warehouse (freshness, volume, grain, last run) from the DuckDB file.

Every timestamp is Unix time in seconds, which is also what Prometheus uses.
Every metric lives in a registry of its own, never in the global one, so the
tests can create as many as they need.
"""
from __future__ import annotations

import time
from pathlib import Path

import duckdb
from opentelemetry.trace import SpanKind, Status, StatusCode
from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram, disable_created_metrics, generate_latest
from prometheus_client.exposition import pushadd_to_gateway
from prometheus_client.core import GaugeMetricFamily

from tcg_dataapp.observability import tracer

# The *_created series (when each counter started) only add noise to a job that lives forty seconds.
disable_created_metrics()

JOB = "tcg_dataapp"
SOURCE_BUCKETS = (0.1, 0.25, 0.5, 1, 2, 4, 8, 16)


class RunMetrics:
    """The metrics of one run of the pipeline."""

    def __init__(self, run_id: str):
        self.run_id = run_id
        self.registry = CollectorRegistry()
        r = self.registry
        self.task_attempts = Counter("tcg_task_attempts", "Attempts of each task in this run, by outcome",
                                     ["task", "status"], registry=r)
        self.task_duration = Gauge("tcg_task_duration_seconds", "Duration of the last attempt of each task",
                                   ["task"], registry=r)
        self.task_rows = Gauge("tcg_task_rows", "Rows written to db_ingestion by each extraction task", ["task"], registry=r)
        self.source_latency = Histogram("tcg_source_request_duration_seconds",
                                        "Duration of the requests to tcgcsv.com, by kind of request",
                                        ["endpoint"], buckets=SOURCE_BUCKETS, registry=r)
        self.source_errors = Counter("tcg_source_request_errors", "Requests to tcgcsv.com that raised an error",
                                     ["endpoint"], registry=r)
        self.quality = Gauge("tcg_quality_value", "Numbers measured by check_quality", ["measure"], registry=r)
        self.run_success = Gauge("tcg_run_success", "1 when every task of the run succeeded, 0 otherwise", registry=r)
        self.run_duration = Gauge("tcg_run_duration_seconds", "Duration of the whole run", registry=r)
        self.run_failed_tasks = Gauge("tcg_run_failed_tasks", "Tasks that failed or were skipped in the run", registry=r)
        # An info metric: always 1, its labels say which run (and which trace) the series above describe.
        # One series per instance, replaced at every push, so the cardinality stays at one.
        self.run_info = Gauge("tcg_run_info", "Identifiers of the last run: run_id and trace_id, to open its trace",
                              ["run_id", "trace_id"], registry=r)
        self.run_completion = Gauge("tcg_run_last_completion_timestamp_seconds",
                                    "Unix time at which the last run ended, successful or not", registry=r)
        # Pushed only after a successful run, so a failure does not erase it.
        self.success_registry = CollectorRegistry()
        self.run_last_success = Gauge("tcg_run_last_success_timestamp_seconds",
                                      "Unix time at which the last successful run ended",
                                      registry=self.success_registry)
        self.succeeded = False
        self._started = time.perf_counter()

    # hooks called by the pipeline
    def attempt(self, task: str, status: str, seconds: float | None = None, result: object = None) -> None:
        self.task_attempts.labels(task=task, status=status).inc()
        if seconds is not None:
            self.task_duration.labels(task=task).set(seconds)
        if status == "success" and task.startswith("extract_") and isinstance(result, int):
            self.task_rows.labels(task=task).set(result)
        if status == "success" and task == "check_quality" and isinstance(result, dict):
            for measure in ("fact_rows", "fact_grain_keys", "fact_without_set", "dates", "cube_cells"):
                if measure in result:
                    self.quality.labels(measure=measure).set(result[measure])

    def finish(self, failed: list[str], trace_id: str = "") -> None:
        now = time.time()
        self.run_info.labels(run_id=self.run_id, trace_id=trace_id).set(1)
        self.run_duration.set(time.perf_counter() - self._started)
        self.run_failed_tasks.set(len(failed))
        self.run_success.set(0 if failed else 1)
        self.run_completion.set(now)
        self.succeeded = not failed
        if self.succeeded:
            self.run_last_success.set(now)

    # the client of the source, wrapped so that every request is measured
    def instrument(self, client):
        return InstrumentedClient(client, self)

    # exposition
    def text(self) -> str:
        body = generate_latest(self.registry)
        if self.succeeded:
            body += generate_latest(self.success_registry)
        return body.decode()

    def write(self, path: Path) -> Path:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(self.text(), encoding="utf-8")
        return path

    def push(self, gateway: str, instance: str = "local") -> None:
        """Push to a Pushgateway, in the group job=tcg_dataapp, instance=<instance>.

        pushadd (HTTP POST) replaces only the metrics with the names being pushed, so
        tcg_run_last_success_timestamp_seconds, pushed only after a success, keeps
        the time of the last good run when a run fails.
        """
        key = {"instance": instance}
        pushadd_to_gateway(gateway, job=JOB, registry=self.registry, grouping_key=key, timeout=10)
        if self.succeeded:
            pushadd_to_gateway(gateway, job=JOB, registry=self.success_registry, grouping_key=key, timeout=10)


class InstrumentedClient:
    """Same methods as TcgcsvClient. Each call is one child span (tcgcsv.<endpoint>), timed
    into tcg_source_request_duration_seconds and, when it raises, counted in
    tcg_source_request_errors_total and recorded in the span with status ERROR."""

    METHODS = {"groups": "groups", "products": "products", "prices_today": "prices", "prices_archive": "archive"}

    def __init__(self, client, metrics: RunMetrics):
        self._client = client
        self._metrics = metrics

    def __getattr__(self, name):
        target = getattr(self._client, name)
        endpoint = self.METHODS.get(name)
        if endpoint is None or not callable(target):
            return target

        base = getattr(self._client, "base_url", "")

        def call(*args, **kwargs):
            t0 = time.perf_counter()
            with tracer().start_as_current_span(f"tcgcsv.{endpoint}", kind=SpanKind.CLIENT,
                                                record_exception=False, set_status_on_exception=False) as span:
                span.set_attribute("http.request.method", "GET")
                span.set_attribute("server.address", base.split("//")[-1].split("/")[0])
                span.set_attribute("tcg.endpoint", endpoint)
                if args:
                    span.set_attribute("tcg.argument", str(args[0]))
                try:
                    result = target(*args, **kwargs)
                except Exception as error:
                    self._metrics.source_errors.labels(endpoint=endpoint).inc()
                    span.record_exception(error)
                    span.set_status(Status(StatusCode.ERROR, f"{type(error).__name__}: {error}"))
                    raise
                finally:
                    self._metrics.source_latency.labels(endpoint=endpoint).observe(time.perf_counter() - t0)
                size = sum(len(v) for v in result.values()) if isinstance(result, dict) else len(result)
                span.set_attribute("tcg.records", size)
                return result

        return call


class WarehouseCollector:
    """A custom collector: reads the warehouse at each scrape, as an exporter does.

    The DuckDB file accepts one writer process at a time, so while a run is
    writing the scrape cannot open it; the collector then reports
    tcg_warehouse_readable 0 instead of failing the whole scrape. The same
    happens when the file exists but the gold layer was never built.
    """

    def __init__(self, db_path: Path):
        self.db_path = Path(db_path)

    def collect(self):
        readable = GaugeMetricFamily("tcg_warehouse_readable", "1 when the exporter could read the DuckDB file at this scrape")
        if not self.db_path.exists():
            readable.add_metric([], 0)
            yield readable
            return
        try:
            con = duckdb.connect(str(self.db_path), read_only=True)
        except duckdb.Error:
            readable.add_metric([], 0)
            yield readable
            return
        try:
            families = list(self._read(con))
        except duckdb.Error:  # a warehouse without the gold layer yet, after a run that failed early
            families = []
        finally:
            con.close()
        yield from families
        readable.add_metric([], 1 if families else 0)
        yield readable

    def _read(self, con):
        rows = GaugeMetricFamily("tcg_ingestion_rows", "Rows of db_ingestion, by data tag", labels=["data_tag"])
        last = GaugeMetricFamily("tcg_ingestion_last_timestamp_seconds",
                                 "Unix time of the newest record of db_ingestion, by data tag", labels=["data_tag"])
        batches = GaugeMetricFamily("tcg_ingestion_batches", "Distinct capture timestamps, by data tag", labels=["data_tag"])
        for tag, n, newest, distinct in con.execute(
                "SELECT data_tag, count(*), max(timestamp), count(DISTINCT timestamp) FROM db_ingestion GROUP BY 1 ORDER BY 1").fetchall():
            rows.add_metric([tag], n)
            last.add_metric([tag], newest)
            batches.add_metric([tag], distinct)
        yield rows
        yield last
        yield batches

        fact_rows, fact_keys = con.execute(
            "SELECT count(*), count(DISTINCT (date_unix, product_id, variant)) FROM gold.fact_price").fetchone()
        g = GaugeMetricFamily("tcg_gold_fact_rows", "Rows of gold.fact_price")
        g.add_metric([], fact_rows)
        yield g
        g = GaugeMetricFamily("tcg_gold_fact_grain_keys", "Distinct keys (date, product, variant) of gold.fact_price")
        g.add_metric([], fact_keys)
        yield g

        status = GaugeMetricFamily("tcg_pipeline_last_run_tasks", "Task attempts of the last run in ops.pipeline_runs, by status",
                                   labels=["status"])
        ended = GaugeMetricFamily("tcg_pipeline_last_run_end_timestamp_seconds", "Unix time of the end of the last run")
        last_run = con.execute("SELECT run_id FROM ops.pipeline_runs ORDER BY started_at DESC, rowid DESC LIMIT 1").fetchone()
        if last_run:
            for st, n in con.execute("SELECT status, count(*) FROM ops.pipeline_runs WHERE run_id = ? GROUP BY 1 ORDER BY 1",
                                     [last_run[0]]).fetchall():
                status.add_metric([st], n)
            ended.add_metric([], con.execute("SELECT max(ended_at) FROM ops.pipeline_runs WHERE run_id = ?",
                                             [last_run[0]]).fetchone()[0])
        yield status
        yield ended


def exporter_registry(db_path: Path) -> CollectorRegistry:
    registry = CollectorRegistry()
    registry.register(WarehouseCollector(db_path))
    return registry


def serve(db_path: Path, port: int, addr: str = "0.0.0.0"):
    """Start the HTTP endpoint /metrics of the exporter; returns the server and its thread."""
    from prometheus_client import start_http_server

    return start_http_server(port, addr=addr, registry=exporter_registry(db_path))
Part IIITraces and logs

8. The anatomy of a trace

A span is an operation with a name, a start and an end, a parent, attributes that describe it, events that happened inside it and a status. The spans of one execution share a trace_id and form a tree through their parents, so the tree of a run shows how its time was spent and where it failed. The package opens four kinds of span: the root tcg_dataapp.run, one task <name> per task, one tcgcsv.<endpoint> per request to the source, of kind CLIENT, and one sql <file> per SQL file of the gold layer.

the trace of a good run of 08/11/2026 (38 spans, 30.6 s)
tcg_dataapp.run                     30.6 s   run_id 16fb5bb50f14, trigger manual
β”œβ”€ 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
β”œβ”€ ... five more extractions, the prices of today included
β”œβ”€ task build_gold                   0.05 s
β”‚  └─ sql 01_dimensions.sql Β· 02_fact.sql Β· 03_cube_and_mart.sql Β· 04_live_reports.sql
β”œβ”€ task check_quality                0.08 s
β”œβ”€ task freeze_reports               0.17 s
β”œβ”€ task export_marts                 0.10 s
└─ task write_report                 0.17 s

A failure leaves three marks on its span. Each failed attempt adds an event "attempt failed" with the type and the message of the exception; the last one records the exception itself, with its stack; and the status becomes ERROR with a short description. Tasks skipped because a dependency failed get the attribute tcg.status = skipped, and the root ends with ERROR when any task failed. In the run with the source down, the span task extract_sets had three events "attempt failed", one per attempt, and its three child spans tcgcsv.groups were also marked ERROR.

9. The observability module

The package calls only the API of OpenTelemetry, through tracer(), which does nothing until a provider is installed. The command line installs it in setup(): a batch processor that sends spans to /v1/traces of the collector and log records to /v1/logs, both by HTTP and protobuf, and a file handler that writes the same events as JSON lines. A library never configures the SDK, because the application that uses it decides where its telemetry goes; the tests install their own provider with an in-memory exporter, once per process, which is the only number of providers OpenTelemetry accepts.

src/tcg_dataapp/observability.py
"""Traces and structured logs of the DataApp, with OpenTelemetry.

Metrics are in telemetry.py (Prometheus). This module adds the other two signals:

    traces  one span per run, one per task, and child spans for every request to
            tcgcsv.com and every SQL file of the gold layer; a failure sets the
            status of the span to ERROR and records the exception as a span event.
    logs    one JSON object per line, written to out/logs/tcg-dataapp.jsonl, with the
            run_id, the trace_id and the span_id of the span that was active when
            the line was written; with an OTLP endpoint, the same records also go
            to the collector, which delivers them to Loki.

The three signals meet in two identifiers: the run_id (in the logs, in
ops.pipeline_runs and in the metric tcg_run_info) and the trace_id (in the
spans, in the logs and in tcg_run_info). From an alert, the metric gives the
trace_id; the trace gives the failing span; the span_id gives the log line.

The rest of the package calls only the OpenTelemetry API (trace.get_tracer),
which does nothing until setup() installs a provider. So the tests install
their own provider with an in-memory exporter, and a run without a collector
still writes its JSON logs.
"""
from __future__ import annotations

import contextvars
import json
import logging
import time
from pathlib import Path

from opentelemetry import trace

from tcg_dataapp import __version__

SERVICE = "tcg-dataapp"
LOGGER = "tcg_dataapp"

# The run that is executing, so that every log line can carry it.
current_run_id: contextvars.ContextVar[str] = contextvars.ContextVar("current_run_id", default="")

# Attributes of a LogRecord that are not fields given by the caller in extra=.
_STANDARD = set(vars(logging.LogRecord("", 0, "", 0, "", (), None))) | {"message", "asctime", "taskName"}


def tracer():
    return trace.get_tracer(LOGGER, __version__)


def logger() -> logging.Logger:
    return logging.getLogger(LOGGER)


def ids() -> tuple[str, str]:
    """(trace_id, span_id) of the active span, in hexadecimal, or ("", "") outside a span."""
    ctx = trace.get_current_span().get_span_context()
    if not ctx.is_valid:
        return "", ""
    return f"{ctx.trace_id:032x}", f"{ctx.span_id:016x}"


class JsonFormatter(logging.Formatter):
    """One JSON object per line: time in Unix seconds, level, message, run and trace context, extra fields."""

    def format(self, record: logging.LogRecord) -> str:
        trace_id, span_id = ids()
        line = {
            "ts": round(record.created, 3),
            "level": record.levelname.lower(),
            "logger": record.name,
            "msg": record.getMessage(),
            "service": SERVICE,
            "run_id": current_run_id.get(),
            "trace_id": trace_id,
            "span_id": span_id,
        }
        for key, value in vars(record).items():
            if key not in _STANDARD and key not in line:
                line[key] = value if isinstance(value, (str, int, float, bool)) or value is None else str(value)
        if record.exc_info:
            line["exception"] = self.formatException(record.exc_info)
        return json.dumps(line, ensure_ascii=False)


class RunIdFilter(logging.Filter):
    """Adds run_id as an attribute of every record, so that the OTLP handler exports it too."""

    def filter(self, record: logging.LogRecord) -> bool:
        if not getattr(record, "run_id", ""):
            record.run_id = current_run_id.get()
        return True


_configured = False


def setup(log_path: Path | None, otlp_endpoint: str = "", instance: str = "local") -> None:
    """Install the providers once per process: JSON logs to a file and, with an endpoint, OTLP export.

    otlp_endpoint is the base URL of an OpenTelemetry collector (http://localhost:4318);
    traces go to /v1/traces and logs to /v1/logs, by HTTP and protobuf.
    """
    global _configured
    if _configured:
        return
    _configured = True
    log = logger()
    log.setLevel(logging.INFO)
    log.propagate = False
    log.addFilter(RunIdFilter())
    if log_path is not None:
        log_path.parent.mkdir(parents=True, exist_ok=True)
        handler = logging.FileHandler(log_path, encoding="utf-8")
        handler.setFormatter(JsonFormatter())
        log.addHandler(handler)
    if not otlp_endpoint:
        return

    from opentelemetry._logs import set_logger_provider
    from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
    from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
    from opentelemetry.sdk.resources import Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor

    base = otlp_endpoint.rstrip("/")
    resource = Resource.create({"service.name": SERVICE, "service.version": __version__,
                                "service.instance.id": instance})
    provider = TracerProvider(resource=resource)
    provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=f"{base}/v1/traces", timeout=5)))
    trace.set_tracer_provider(provider)
    logs = LoggerProvider(resource=resource)
    logs.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=f"{base}/v1/logs", timeout=5)))
    set_logger_provider(logs)
    log.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logs))


def flush() -> None:
    """Send what the batch processors still hold; called at the end of a command."""
    from opentelemetry._logs import get_logger_provider

    for provider in (trace.get_tracer_provider(), get_logger_provider()):
        force = getattr(provider, "force_flush", None)
        if force:
            force(5000)


def timed() -> float:
    return time.perf_counter()

10. Structured logs inside their span

A log line in free text is read by a person; a structured line is read by a machine as well, because each field has a name. The JsonFormatter writes one JSON object per line with the time in Unix seconds, the level, the message, the service, the run_id taken from a context variable, and the trace_id and span_id of the span active at the moment of the call. The pipeline writes each line inside the span it describes, which is what makes the span_id of the line equal to the span_id of the failing task.

a line of out/logs/tcg-dataapp.jsonl, from the run with the source down
{"ts": 1794146686.73, "level": "error", "logger": "tcg_dataapp", "msg": "task attempt failed",
 "service": "tcg-dataapp", "run_id": "e44b5b8a34eb", "trace_id": "5d1d493014dd2ecc409d7593266173a2",
 "span_id": "ba8fc2d7eb92ef1c", "event": "task.fail", "task": "extract_sets", "attempt": 2,
 "attempts": 3, "error": "ConnectionError: fault injected: source_down"}

Five events cover a run: run.start, task.ok, task.fail, task.skip and run.end. A line never carries records of the source, only counts and errors, so the logs can be kept and shared without the data. When the OTLP endpoint is configured, the same records go to Loki, which keeps the attributes as structured metadata and filters them after the stream selector.

11. The instrumented pipeline

The pipeline opens the root span, sets the run_id in the context variable and runs each task inside its own span, adding the events, the status and the log lines described above. At the end of a successful run it records each batch of db_ingestion, with its rows and an md5 digest of its content, in ops.good_batches: the last known good state that the controller of Part V restores. The trace_id of the run is passed to the metrics, where it becomes the label of tcg_run_info.

src/tcg_dataapp/pipeline.py
"""The pipeline: tasks with dependencies, run in order, with retries and a log of every run.

Each task is a function of the run context. A task runs only after all the
tasks it depends on succeeded; a failure is retried, and a task that still
fails stops every task that depends on it. Every attempt is recorded in
ops.pipeline_runs, with Unix times, so a run can be audited afterwards.

Lesson 10: the run emits the three signals of observability.

    metrics  a telemetry.RunMetrics object (attempts, durations, rows, requests to
             the source, quality numbers, outcome, and tcg_run_info with the
             trace_id), pushed to a Pushgateway and written to out/metrics.prom;
    traces   a root span tcg_dataapp.run, one span per task, and the child spans
             of the requests to the source and of the SQL files;
    logs     one JSON line per event, carrying run_id, trace_id and span_id.

At the end of a successful run, the batches of db_ingestion are recorded in
ops.good_batches: the last known good state, which the controller of
control.py restores when a new batch breaks the quality gate.
"""
from __future__ import annotations

import time
import uuid
from dataclasses import dataclass, field
from typing import Callable

import duckdb
from opentelemetry.trace import Status, StatusCode

from tcg_dataapp.config import Settings
from tcg_dataapp.etls import extract
from tcg_dataapp.etls.tcgcsv import TcgcsvClient
from tcg_dataapp.observability import current_run_id, ids, logger, tracer
from tcg_dataapp.processors import gold, quality
from tcg_dataapp.telemetry import RunMetrics
from tcg_dataapp.views import report

LOG_DDL = """
CREATE SCHEMA IF NOT EXISTS ops;
CREATE TABLE IF NOT EXISTS ops.pipeline_runs (
    run_id     VARCHAR,
    task       VARCHAR,
    attempt    INTEGER,
    status     VARCHAR,
    started_at BIGINT,
    ended_at   BIGINT,
    detail     VARCHAR
);
CREATE TABLE IF NOT EXISTS ops.good_batches (
    data_tag    VARCHAR,
    timestamp   BIGINT,
    rows        BIGINT,
    digest      VARCHAR,
    run_id      VARCHAR,
    recorded_at BIGINT
);
"""

# One row per batch of db_ingestion, with a digest of its content: the same key
# (tag, timestamp) can be loaded again with other records.
BATCH_DIGEST = """
SELECT data_tag, timestamp, count(*) AS rows,
       md5(string_agg(data_json::VARCHAR, '|' ORDER BY data_json::VARCHAR)) AS digest
FROM db_ingestion GROUP BY 1, 2
"""


@dataclass
class Task:
    name: str
    run: Callable[["Context"], object]
    depends_on: tuple = ()
    retries: int | None = None


@dataclass
class Context:
    settings: Settings
    con: duckdb.DuckDBPyConnection
    client: TcgcsvClient
    run_id: str
    captured_at: int
    metrics: RunMetrics | None = None
    results: dict = field(default_factory=dict)
    trace_id: str = ""


def build_tasks(settings: Settings, with_today: bool = False) -> list[Task]:
    tasks = [
        Task("extract_sets", lambda c: extract.extract_sets(c.con, c.client, c.settings.sets, c.captured_at)),
        Task("extract_products", lambda c: extract.extract_products(c.con, c.client, c.settings.sets, c.captured_at),
             depends_on=("extract_sets",)),
    ]
    price_tasks = []
    for day in settings.price_dates:
        name = f"extract_prices_{day}"
        tasks.append(Task(name, lambda c, d=day: extract.extract_prices_archive(c.con, c.client, c.settings.sets, d),
                          depends_on=("extract_products",)))
        price_tasks.append(name)
    if with_today:
        tasks.append(Task("extract_prices_today",
                          lambda c: extract.extract_prices_today(c.con, c.client, c.settings.sets, extract.today()),
                          depends_on=("extract_products",)))
        price_tasks.append("extract_prices_today")
    tasks += [
        Task("build_gold", lambda c: gold.build_gold(c.con), depends_on=tuple(price_tasks), retries=0),
        Task("check_quality", lambda c: quality.check_gold(c.con), depends_on=("build_gold",), retries=0),
        Task("freeze_reports", lambda c: gold.freeze_month(c.con, c.settings.frozen_month),
             depends_on=("check_quality",), retries=0),
        Task("export_marts", lambda c: [p.as_posix() for p in report.export_marts(c.con, c.settings.out_dir)],
             depends_on=("check_quality",)),
        Task("write_report", lambda c: report.write_report(c.con, c.settings.out_dir, c.run_id).as_posix(),
             depends_on=("freeze_reports", "export_marts")),
    ]
    return tasks


def order(tasks: list[Task]) -> list[Task]:
    """Topological order of the tasks; raises on an unknown dependency or a cycle."""
    by_name = {t.name: t for t in tasks}
    for t in tasks:
        for d in t.depends_on:
            if d not in by_name:
                raise ValueError(f"task {t.name} depends on unknown task {d}")
    done, ordered, visiting = set(), [], set()

    def visit(t: Task):
        if t.name in done:
            return
        if t.name in visiting:
            raise ValueError(f"cycle at task {t.name}")
        visiting.add(t.name)
        for d in t.depends_on:
            visit(by_name[d])
        visiting.discard(t.name)
        done.add(t.name)
        ordered.append(t)

    for t in tasks:
        visit(t)
    return ordered


def _log(con, run_id, task, attempt, status, started, ended, detail):
    con.execute("INSERT INTO ops.pipeline_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
                [run_id, task, attempt, status, started, ended, str(detail)[:500]]).fetchall()


def record_good_state(con, run_id: str) -> int:
    """Replace ops.good_batches with the batches present now; returns how many."""
    con.execute("DELETE FROM ops.good_batches").fetchall()
    con.execute(f"INSERT INTO ops.good_batches SELECT data_tag, timestamp, rows, digest, ?, ? FROM ({BATCH_DIGEST})",
                [run_id, extract.now_unix()]).fetchall()
    return con.execute("SELECT count(*) FROM ops.good_batches").fetchone()[0]


def _summary(result) -> str:
    return str(result)[:200]


def run(settings: Settings, tasks: list[Task] | None = None, client: TcgcsvClient | None = None,
        con: duckdb.DuckDBPyConnection | None = None, with_today: bool = False,
        echo: Callable[[str], None] = print, metrics: bool = True, trigger: str = "manual") -> Context:
    own = con is None
    if own:
        settings.db_path.parent.mkdir(parents=True, exist_ok=True)
        con = duckdb.connect(str(settings.db_path))
    for statement in con.extract_statements(LOG_DDL):
        con.execute(statement).fetchall()
    run_id = uuid.uuid4().hex[:12]
    token = current_run_id.set(run_id)
    log = logger()
    m = RunMetrics(run_id) if metrics else None
    source = client or TcgcsvClient(settings.base_url, settings.category)
    if settings.fault:
        from tcg_dataapp.faults import FaultyClient
        source = FaultyClient(source, settings.fault)
    ctx = Context(settings=settings, con=con, client=m.instrument(source) if m else source,
                  run_id=run_id, captured_at=extract.now_unix(), metrics=m)
    failed: set[str] = set()
    t_run = time.perf_counter()
    try:
        with tracer().start_as_current_span("tcg_dataapp.run") as root:
            root.set_attribute("tcg.run_id", run_id)
            root.set_attribute("tcg.trigger", trigger)
            root.set_attribute("tcg.sets", len(settings.sets))
            root.set_attribute("tcg.with_today", with_today)
            if settings.fault:
                root.set_attribute("tcg.fault", settings.fault)
            ctx.trace_id = ids()[0]
            log.info("run started", extra={"event": "run.start", "trigger": trigger, "fault": settings.fault})
            for task in order(tasks or build_tasks(settings, with_today)):
                _run_task(ctx, task, failed, echo)
            ctx.results["_failed"] = sorted(failed)
            if failed:
                root.set_status(Status(StatusCode.ERROR, f"failed: {', '.join(sorted(failed))}"))
            else:
                ctx.results["_good_batches"] = record_good_state(con, run_id)
            root.set_attribute("tcg.failed_tasks", len(failed))
            log.log(40 if failed else 20, "run finished", extra={
                "event": "run.end", "status": "failed" if failed else "ok", "failed_tasks": ",".join(sorted(failed)),
                "duration_s": round(time.perf_counter() - t_run, 3)})
    finally:
        if own:
            con.close()
        current_run_id.reset(token)
    if m:
        m.finish(ctx.results["_failed"], ctx.trace_id)
    return ctx


def _run_task(ctx: Context, task: Task, failed: set, echo) -> None:
    con, settings, m, log = ctx.con, ctx.settings, ctx.metrics, logger()
    with tracer().start_as_current_span(f"task {task.name}") as span:
        span.set_attribute("tcg.task", task.name)
        if any(d in failed for d in task.depends_on):
            failed.add(task.name)
            span.set_attribute("tcg.status", "skipped")
            span.set_status(Status(StatusCode.ERROR, "a dependency failed"))
            _log(con, ctx.run_id, task.name, 0, "skipped", extract.now_unix(), extract.now_unix(), "a dependency failed")
            log.warning("task skipped", extra={"event": "task.skip", "task": task.name})
            echo(f"  skip  {task.name}  (a dependency failed)")
            if m:
                m.attempt(task.name, "skipped")
            return
        attempts = 1 + (settings.retries if task.retries is None else task.retries)
        for attempt in range(1, attempts + 1):
            started = extract.now_unix()
            t0 = time.perf_counter()
            try:
                result = task.run(ctx)
            except Exception as error:  # noqa: BLE001 - every failure is logged and retried
                detail = f"{type(error).__name__}: {error}"
                _log(con, ctx.run_id, task.name, attempt, "failed", started, extract.now_unix(), detail)
                span.add_event("attempt failed", {"tcg.attempt": attempt, "exception.type": type(error).__name__,
                                                  "exception.message": str(error)[:300]})
                log.error("task attempt failed", extra={"event": "task.fail", "task": task.name, "attempt": attempt,
                                                        "attempts": attempts, "error": detail[:300]})
                if m:
                    m.attempt(task.name, "failed", time.perf_counter() - t0)
                echo(f"  fail  {task.name}  attempt {attempt}/{attempts}: {detail}")
                if attempt == attempts:
                    failed.add(task.name)
                    span.record_exception(error)
                    span.set_status(Status(StatusCode.ERROR, detail[:200]))
                    span.set_attribute("tcg.status", "failed")
                else:
                    time.sleep(settings.retry_delay * attempt)
                continue
            seconds = time.perf_counter() - t0
            ctx.results[task.name] = result
            _log(con, ctx.run_id, task.name, attempt, "success", started, extract.now_unix(), result)
            span.set_attribute("tcg.status", "success")
            span.set_attribute("tcg.attempts", attempt)
            span.set_attribute("tcg.result", _summary(result))
            log.info("task succeeded", extra={"event": "task.ok", "task": task.name, "attempt": attempt,
                                              "duration_s": round(seconds, 3), "result": _summary(result)})
            if m:
                m.attempt(task.name, "success", seconds, result)
            echo(f"  ok    {task.name}  {seconds:5.2f} s  {result}")
            return
Part IVStack and correlation

12. Six containers, one entry point

The stack of the lab has six containers, each pinned to a version. The DataApp knows only one address for traces and logs, the OpenTelemetry collector, which receives OTLP and routes each signal: the traces to Tempo, by OTLP over gRPC, and the logs to the native OTLP endpoint of Loki. Metrics keep their own path through the Pushgateway and the exporter to Prometheus. Grafana reads the three stores. Placing a collector between the application and the stores lets the stores change, or a second destination be added, without touching the code of the DataApp.

stack/compose.yaml
# Lesson 10 Β· the observability stack of the DataApp: the three signals and the loop.
#
#   metrics  the run pushes to the Pushgateway, the exporter is scraped  β†’ Prometheus
#   traces   the run sends OTLP to the collector                         β†’ Tempo
#   logs     the run sends OTLP to the collector (and writes JSON lines) β†’ Loki
#   Grafana reads the three and links them: metric β†’ trace β†’ log line.
#
#   docker compose up -d       Prometheus :9090 Β· Pushgateway :9091 Β· collector :4318 Β·
#                              Tempo :3200 Β· Loki :3100 Β· Grafana :3000 (GRAFANA_PORT)
#   docker compose down -v     stops and removes everything
#
# The DataApp runs on the host:
#   TCG_OTLP_ENDPOINT=http://localhost:4318 TCG_PUSHGATEWAY=localhost:9091 tcg-dataapp run --with-today
#   tcg-dataapp metrics                      (exporter, port 9108)
#   tcg-dataapp control --interval 60        (the closed loop)
name: tcg-observability

services:
  prometheus:
    image: prom/prometheus:v3.15.0
    command:
      - --config.file=/etc/prometheus/prometheus.yml
      - --storage.tsdb.retention.time=15d
      - --web.enable-lifecycle
    ports: ["9090:9090"]
    volumes:
      - ./prometheus:/etc/prometheus:ro
      - prometheus-data:/prometheus
    extra_hosts: ["host.docker.internal:host-gateway"]

  pushgateway:
    image: prom/pushgateway:v1.11.2
    ports: ["9091:9091"]

  # One entry point for traces and logs: the DataApp knows only this address,
  # and the collector decides where each signal goes.
  otel-collector:
    image: otel/opentelemetry-collector-contrib:0.141.0
    command: ["--config=/etc/otelcol/config.yaml"]
    ports: ["4317:4317", "4318:4318"]
    volumes:
      - ./otel/config.yaml:/etc/otelcol/config.yaml:ro
    depends_on: [tempo, loki]

  tempo:
    image: grafana/tempo:2.10.10
    user: "0"                       # writes its blocks to the named volume
    command: ["-config.file=/etc/tempo/tempo.yaml"]
    ports: ["3200:3200"]
    volumes:
      - ./tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
      - tempo-data:/var/tempo

  loki:
    image: grafana/loki:3.6.3       # default config: single binary, OTLP at /otlp/v1/logs
    ports: ["3100:3100"]

  grafana:
    image: grafana/grafana:13.2.4
    ports: ["${GRAFANA_PORT:-3000}:3000"]
    environment:
      GF_AUTH_ANONYMOUS_ENABLED: "true"
      GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer
      GF_USERS_VIEWERS_CAN_EDIT: "true"        # lets the class open Explore to follow a trace
      GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/tcg_dataapp.json
    volumes:
      - ./grafana/provisioning:/etc/grafana/provisioning:ro
      - ./grafana/dashboards:/var/lib/grafana/dashboards:ro
    depends_on: [prometheus, tempo, loki]

volumes:
  prometheus-data:
  tempo-data:
stack/otel/config.yaml
# Lesson 10 Β· the OpenTelemetry collector: receives OTLP from the DataApp and routes each signal.
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  batch: {}

exporters:
  otlp/tempo:                 # traces β†’ Tempo, by OTLP over gRPC
    endpoint: tempo:4317
    tls:
      insecure: true
  otlphttp/loki:              # logs β†’ Loki, by its native OTLP endpoint
    endpoint: http://loki:3100/otlp

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp/tempo]
    logs:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlphttp/loki]

14. Three stores, three query languages

Each store has its language. PromQL selects series by name and labels and operates on whole vectors; TraceQL selects spans by their attributes, status and duration; LogQL selects streams by labels and then filters lines by content or by structured fields. The questions of the person on call cross the three, and the answers below are those of the rehearsal; stack/queries.md keeps the complete list.

Signal and storeQueryAnswer on 08/11/2026
metrics Β· Prometheustopk(3, tcg_task_duration_seconds)products 9.52 s, prices of 07/11 8.12 s, prices of today 6.83 s
metrics Β· Prometheustcg_gold_fact_rows - tcg_gold_fact_grain_keys0
metrics Β· Prometheustcg_controller_error{job="tcg_controller"}freshness βˆ’35,293 s; duration βˆ’80 s; source errors βˆ’0.5
traces Β· Tempo{name="tcg_dataapp.run" && status=error}the runs with source_down and duplicate_prices
traces Β· Tempo{name="control.tick" && span.tcg.decision="rerun"}one trace of 41 spans
logs Β· Loki{service_name="tcg-dataapp"} | trace_id="5d1d…"17 lines: 4 errors, 12 skipped tasks, 1 start
logs Β· Loki{service_name="tcg-dataapp"} | span_id="ba8fc2d7eb92ef1c"3 lines, attempts 1, 2 and 3

15. Alerts on symptoms, tested

An alerting rule is a PromQL expression that creates an alert while it returns series. Each rule of the lab describes a symptom that someone must act on, with a threshold that comes from how the DataApp runs: a failed run, no success for 26 hours (a daily run plus two hours), prices older than 36 hours, a run over 120 seconds (three times the reference), rows above the grain, and an exporter that cannot read the warehouse for two minutes. The description of TcgRunFailed uses the template function query to read tcg_run_info, so the alert itself carries the run and the trace. Three more rules cover the controller of Part V: an escalation, a breaker open for two hours and a controller that stopped ticking. The recording rules sit in the same group as the alerts that read them, before them. The rules of one group are evaluated in order, so TcgPricesStale reads the freshness computed in the same evaluation; in separate groups the order is not fixed, and the test of the alert in rules_test.yml failed about one run in three, depending on which group Prometheus evaluated first.

stack/prometheus/rules.yml
# Lesson 10 Β· recording and alerting rules of the DataApp.
# Check with: promtool check rules rules.yml
groups:
  # The recording rules come first, in the same group as the alerts that read them:
  # the rules of one group are evaluated in order, so TcgPricesStale reads the
  # freshness of the same evaluation. In separate groups the order is not fixed,
  # and the alert could read the value of the previous minute.
  - name: tcg_dataapp
    rules:
      # Seconds since the newest price was captured. Written once, reused by the
      # dashboard and by the alert below. The prices of today are stored at noon
      # UTC, which is in the future for a run in the morning, so the age is
      # clamped at zero instead of going negative.
      - record: tcg:price_freshness_seconds
        expr: clamp_min(time() - tcg_ingestion_last_timestamp_seconds{data_tag="tcgplayer.price.v1"}, 0)
      # 95th percentile of the requests to tcgcsv.com in the last pushed run, by endpoint.
      # The histogram of a pushed run holds only that run, so there is no rate() here.
      - record: tcg:source_request_duration_seconds:p95
        expr: histogram_quantile(0.95, sum by (le, endpoint) (tcg_source_request_duration_seconds_bucket{job="tcg_dataapp"}))

      - alert: TcgRunFailed
        expr: tcg_run_success{job="tcg_dataapp"} == 0
        labels:
          severity: critical
        annotations:
          summary: "The last run of tcg-dataapp on {{ $labels.instance }} failed"
          # The alert carries the trace of the run: tcg_run_info has the trace_id as a label.
          description: >-
            {{ with query "tcg_run_info{job='tcg_dataapp'}" }}{{ with first . }}Run {{ .Labels.run_id }}, trace {{ .Labels.trace_id }}: open it in Tempo, then the log lines of the failing span in Loki.{{ end }}{{ end }}

      - alert: TcgNoSuccessfulRun
        # the run is scheduled daily; two hours of tolerance
        expr: time() - tcg_run_last_success_timestamp_seconds{job="tcg_dataapp"} > 26 * 3600
        labels:
          severity: critical
        annotations:
          summary: "No successful run of tcg-dataapp for more than 26 hours"

      - alert: TcgRunTooSlow
        # the reference run takes about 40 s; three times that is a symptom
        expr: tcg_run_duration_seconds{job="tcg_dataapp"} > 120
        labels:
          severity: warning
        annotations:
          summary: "The last run took {{ $value | humanizeDuration }}"

      - alert: TcgPricesStale
        expr: tcg:price_freshness_seconds > 36 * 3600
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "The newest price in db_ingestion is {{ $value | humanizeDuration }} old"

      - alert: TcgGrainBroken
        expr: tcg_gold_fact_rows != tcg_gold_fact_grain_keys
        labels:
          severity: critical
        annotations:
          summary: "gold.fact_price has more rows than keys of its grain"

      - alert: TcgExporterDown
        expr: up{job="tcg_exporter"} == 0 or tcg_warehouse_readable == 0
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "Prometheus cannot read the state of the warehouse"

  # Lesson 10 Β· the closed loop. These alerts are the human part of the loop:
  # they fire only when the controller cannot correct the DataApp on its own.
  - name: tcg_controller_alerts
    rules:
      - alert: TcgControllerEscalated
        expr: tcg_controller_escalated{job="tcg_controller"} == 1
        labels:
          severity: critical
        annotations:
          summary: "The controller of tcg-dataapp handed the loop to a person"
          description: "ops.controller_state has the reason; tcg-dataapp control --acknowledge clears it after the fix."

      - alert: TcgControllerBreakerOpenTooLong
        expr: max_over_time(tcg_controller_breaker_open{job="tcg_controller"}[2h]) == 1 and tcg_controller_breaker_open{job="tcg_controller"} == 1
        for: 2h
        labels:
          severity: warning
        annotations:
          summary: "The circuit breaker on tcgcsv.com has been open for two hours"

      - alert: TcgControllerSilent
        # the loop itself can stop; nobody would notice without this rule
        expr: time() - tcg_controller_last_tick_timestamp_seconds{job="tcg_controller"} > 3 * 300
        labels:
          severity: warning
        annotations:
          summary: "The controller has not ticked for {{ $value | humanizeDuration }}"

promtool test rules runs the rules over series written in a test file, at simulated times, and compares the alerts with the expected ones, including the text of the description with its trace. The file of the lab has four scenarios, and the command printed SUCCESS; promtool check config found eleven rules.

16. The path of a failed run

The rehearsal reproduced a failure and followed it through the four hops. With TCG_FAULT=source_down and two retries, every request raised a ConnectionError; the run failed in 3.0 seconds, skipped twelve tasks and pushed tcg_run_success 0 with its tcg_run_info. At the next evaluation Prometheus fired TcgRunFailed with the description "Run e44b5b8a34eb, trace 5d1d493014dd2ecc409d7593266173a2: open it in Tempo, then the log lines of the failing span in Loki." The trace had 17 spans, and the only task with its own error was extract_sets, with three events "attempt failed" and three child requests marked ERROR. Its span_id, ba8fc2d7eb92ef1c, selected three lines in Loki, one per attempt, each with the message of the exception.

the four hops, by their APIs
$ TCG_FAULT=source_down TCG_RETRIES=2 TCG_RETRY_DELAY=1 tcg-dataapp run --with-today
run e44b5b8a34eb: FAILED (13 tasks) Β· trace 5d1d493014dd2ecc409d7593266173a2

GET :9090/api/v1/alerts            TcgRunFailed firing Β· "Run e44b5b8a34eb, trace 5d1d4930…"
GET :3200/api/v2/traces/5d1d4930…  17 spans Β· task extract_sets: STATUS_CODE_ERROR,
                                   events attempt failed Γ— 3, exception
GET :3100/loki/api/v1/query_range  {service_name="tcg-dataapp"} | span_id="ba8fc2d7eb92ef1c"
                                   ERROR task.fail extract_sets 1 Β· 2 Β· 3
                                   ConnectionError: fault injected: source_down
Part VThe closed loop

17. The elements of a closed loop

Control theory describes a closed loop as a process whose output is measured and compared with a reference, so that the difference drives an action on the process. The reference is the setpoint; the measurement comes from a sensor; the comparator subtracts one from the other and produces the error; the controller turns the error into a decision; the actuator applies the decision to the process, which the theory calls the plant; and the new measurement returns to the comparator, which is the feedback that gives the loop its name. In site reliability engineering the setpoint is a service level objective (SLO) and the measurement a service level indicator (SLI).

The closed loop of the DataApp The setpoint, the SLO, enters a comparator that subtracts the SLI measured by the sensor. The error goes to the controller, which chooses an action; the actuator applies it to the plant, the DataApp and its source. The sensor measures the plant again, and the measurement returns to the comparator: that return is the feedback. setpointSLO: 36 h Ξ£+βˆ’ controllerdecide() actuatorsrerun Β· breaker Β· quarantine plantDataApp + tcgcsv.com sensormetrics Β· traces Β· logs β†’ SLI escalation to a persononce, when the guardrails are spent error feedback: SLI
ElementIn the theoryIn tcg-dataapp
setpointthe desired value of the outputthe SLOs of config.py: data younger than 36 h, source errors below 50 %, a run under 120 s, the grain intact
sensormeasures the outputsense(): the SLIs read from db_ingestion, gold.fact_price and ops.pipeline_runs
comparatorerror = reference βˆ’ measurementerrors(): SLI βˆ’ SLO, positive when the objective is violated
controllerturns the error into a decisiondecide(), a pure function of the SLIs, the state and the clock
actuatoracts on the processrerun, circuit breaker, quarantine, escalation
plantthe process under controlthe DataApp and its source, tcgcsv.com
feedbackthe measurement returns to the comparatorthe next tick reads the effect of the last action

18. Observability alone is not a closed loop

The first three steps of the session built a sensor and a display. Metrics, traces and logs measure the DataApp, and Grafana and the alerts show the measurement. Nothing in them compares the measurement with the objective and acts on the DataApp: an alert hands that decision to a person. The loop is then closed by a human, which is slow, depends on someone being awake and available, and degrades with fatigue, nights and holidays. It is also intermittent, because between the alert and the action the DataApp keeps serving stale or wrong data. A scheduler that runs the DataApp every morning is an open loop: it acts without measuring, and repeats the same action whether the previous one worked or not.

Open loopLoop closed by a personAutomatic closed loop
in the DataAppcron runs it at 06:00the alert calls the person on calltcg-dataapp control acts
sensornonemetrics, traces and logsthe same SLIs, read every tick
decisionfixed in advancea person, when availablea rule, tested
time to actthe next dayminutes to hoursone tick
main riskstale or wrong data for a dayfatigue and absenceacting wrongly fast, limited by guardrails

Closing the loop does not remove the person. The controller acts only on failures that have a known and safe action, and escalates, once, everything that persists or has no actuator. Observability remains necessary in the closed loop, as its sensor, and becomes the record of what the controller did, because each decision is itself a span, a log line and a metric.

19. Stability: hysteresis, backoff and guardrails

An automatic action changes the process that the sensor reads next, and a badly designed loop oscillates or amplifies the failure. A threshold crossed back and forth turns an action on and off at every tick; a rerun against a source that is down fails again and adds load to a system that is already failing; an action repeated without limit hides a failure that is not transient. The controller of the lab has a guardrail for each of these modes.

GuardrailRule in the labFailure mode it prevents
hysteresisstale above 36 h, fresh again only below 30 hflapping around the setpoint
circuit breaker with backoffno call to the source while open; probe after 300 s, then 600 s, then 1,200 sretry storms against a source that is down
cooldownreruns at least 600 s apartactions faster than their effect can be measured
budget per windowat most 3 reruns in 6 hrepeating an action that does not help
escalation onceone call to a person, then hold until the SLIs recover or --acknowledgepaging the same person at every tick
protection before remediationquarantine is not limited by the budgetserving a wrong number while waiting for the budget

20. The controller

control.py implements the loop in four functions and one class. sense() reads the SLIs and classifies the error of the last run as a failure of the source, of quality or of another kind. errors() subtracts the setpoints. decide() chooses one action with no access to the database or to the clock, so every rule has a test with a fake clock. quarantine() moves every batch that is not in ops.good_batches, compared by rows and digest, to quarantine.db_ingestion, rebuilds the views of gold and checks them; the frozen reports are tables and are not touched. The class Controller runs the ticks, applies the actuators, keeps its state in ops.controller_state and its actions in ops.controller_actions, and pushes its metrics as job=tcg_controller.

Failure measuredActuatorEscalates when
data older than 36 hrerun with the prices of todaythe budget of 3 reruns in 6 h is spent
source failing above 50 %open the breaker; probe after a doubling backoff; rerun if the probe worksthe fourth opening
quality gate failedquarantine and restore the last good statethe second quarantine in 6 h
run longer than 120 snone: measured and alerted onlythe alert goes to a person
src/tcg_dataapp/control.py
"""The closed loop of the DataApp: a controller that reads the SLIs, compares them with the SLOs and acts.

Observability alone is the sensor and the display of the loop: the metrics, traces
and logs say what happened, and an alert tells a person. The loop closes only
when something compares the measured value with the setpoint and acts on the
process. This module is that something, in the vocabulary of control theory:

    setpoint    the SLOs of config.py (freshness, success, duration, source errors, grain)
    sensor      sense(): the SLIs read from the warehouse (db_ingestion, gold, ops.pipeline_runs)
    comparator  error = SLI - SLO, with a dead band (hysteresis) on the freshness
    controller  decide(): a pure function of the SLIs, the state and the clock
    actuators   rerun the pipeline; open, probe and close a circuit breaker on the
                source; quarantine the batches that broke the quality gate, which
                restores the last state that passed it; escalate to a person
    plant       the DataApp and its source, tcgcsv.com
    feedback    the next tick reads the effect of the last action

Guardrails keep the loop from oscillating: a cooldown between reruns, a budget
of reruns per window, a backoff that doubles at every reopening of the breaker,
and one escalation that holds every automatic action until the SLIs are back
within the SLOs. Each tick is itself observable: a span control.tick (whose
children are the spans of the actions, including the run that a rerun starts),
one JSON log line, one row of ops.controller_actions and the metrics
tcg_controller_*, pushed to the Pushgateway as job tcg_controller.
"""
from __future__ import annotations

import json
import time
import urllib.request
import uuid
from dataclasses import asdict, dataclass, field
from typing import Callable

import duckdb
from opentelemetry.trace import Status, StatusCode
from prometheus_client import CollectorRegistry, Gauge, pushadd_to_gateway
from prometheus_client.core import CounterMetricFamily

from tcg_dataapp import pipeline
from tcg_dataapp.config import Settings
from tcg_dataapp.etls.tcgcsv import TcgcsvClient
from tcg_dataapp.observability import ids, logger, tracer
from tcg_dataapp.processors import gold, quality

STATE_DDL = """
CREATE SCHEMA IF NOT EXISTS ops;
CREATE TABLE IF NOT EXISTS ops.controller_state (id INTEGER PRIMARY KEY, state JSON, updated_at BIGINT);
CREATE TABLE IF NOT EXISTS ops.controller_actions (
    tick_id VARCHAR, acted_at BIGINT, action VARCHAR, reason VARCHAR, outcome VARCHAR, trace_id VARCHAR
);
CREATE SCHEMA IF NOT EXISTS quarantine;
CREATE TABLE IF NOT EXISTS quarantine.db_ingestion (
    timestamp BIGINT, data_json JSON, data_tag VARCHAR, run_id VARCHAR, reason VARCHAR, quarantined_at BIGINT
);
"""

# Errors that mean "the source did not answer", as written in ops.pipeline_runs.detail.
SOURCE_ERRORS = ("ConnectionError", "URLError", "HTTPError", "TimeoutError", "RemoteDisconnected",
                 "ConnectionResetError", "ConnectionRefusedError", "gaierror", "IncompleteRead")
QUALITY_TASKS = ("build_gold", "check_quality")



@dataclass
class State:
    """What the controller remembers between ticks, kept in ops.controller_state."""
    breaker: str = "closed"        # closed | open
    open_until: float = 0
    opens: int = 0                 # reopenings since the breaker last closed for good
    stale: bool = False            # the freshness is outside the band (hysteresis)
    handled_run: str = ""          # last failed run already answered by a quarantine
    escalated: str = ""            # reason of the open escalation; "" when none

    @classmethod
    def load(cls, con) -> "State":
        row = con.execute("SELECT state FROM ops.controller_state WHERE id = 1").fetchone()
        return cls(**json.loads(row[0])) if row else cls()

    def save(self, con, now: float) -> None:
        con.execute("INSERT OR REPLACE INTO ops.controller_state VALUES (1, ?, ?)",
                    [json.dumps(asdict(self)), int(now)]).fetchall()


@dataclass
class Sli:
    freshness_s: float | None = None
    last_run_id: str = ""
    last_status: str = "none"      # ok | failed | none
    failed_tasks: list = field(default_factory=list)
    error_class: str = ""          # source | quality | other
    run_duration_s: float = 0
    source_error_rate: float = 0
    grain_ok: bool | None = None


@dataclass
class Decision:
    action: str                    # none | hold | rerun | open_breaker | probe | quarantine | escalate | resolve
    reason: str
    escalate: bool = False         # also escalate after the action


def sense(con, now: float) -> Sli:
    """The sensor: SLIs read from the warehouse, the same numbers that the exporter publishes."""
    s = Sli()
    try:
        newest = con.execute("SELECT max(timestamp) FROM db_ingestion WHERE data_tag = 'tcgplayer.price.v1'").fetchone()[0]
    except duckdb.Error:
        newest = None
    s.freshness_s = None if newest is None else max(now - newest, 0)
    last = con.execute("SELECT run_id FROM ops.pipeline_runs ORDER BY started_at DESC, rowid DESC LIMIT 1").fetchone()
    if last:
        s.last_run_id = last[0]
        rows = con.execute("SELECT task, attempt, status, started_at, ended_at, detail FROM ops.pipeline_runs "
                           "WHERE run_id = ? ORDER BY started_at, attempt", [s.last_run_id]).fetchall()
        final = {}
        for task, _attempt, status, *_ in rows:
            final[task] = status
        s.failed_tasks = sorted(t for t, st in final.items() if st in ("failed", "skipped"))
        s.last_status = "failed" if s.failed_tasks else "ok"
        s.run_duration_s = max(r[4] for r in rows) - min(r[3] for r in rows)
        extract_attempts = [r for r in rows if r[0].startswith("extract_") and r[2] in ("success", "failed")]
        source_failures = [r for r in extract_attempts if r[2] == "failed" and str(r[5]).startswith(SOURCE_ERRORS)]
        s.source_error_rate = len(source_failures) / len(extract_attempts) if extract_attempts else 0
        roots = [t for t, st in final.items() if st == "failed"]
        if any(t in QUALITY_TASKS for t in roots):
            s.error_class = "quality"
        elif roots and all(t.startswith("extract_") for t in roots) and source_failures:
            s.error_class = "source"
        elif roots:
            s.error_class = "other"
    try:
        rows, keys = con.execute("SELECT count(*), count(DISTINCT (date_unix, product_id, variant)) FROM gold.fact_price").fetchone()
        s.grain_ok = rows == keys
    except duckdb.Error:
        s.grain_ok = None
    return s


def errors(sli: Sli, st: Settings) -> dict:
    """The comparator: SLI minus setpoint; a positive error is a violation."""
    return {
        "freshness_s": None if sli.freshness_s is None else sli.freshness_s - st.slo_freshness_s,
        "run_duration_s": sli.run_duration_s - st.slo_run_duration_s,
        "source_error_rate": round(sli.source_error_rate - st.slo_source_error_rate, 4),
        "run_failed": 1 if sli.last_status == "failed" else 0,
        "grain_broken": 1 if sli.grain_ok is False else 0,
    }


def stale_with_hysteresis(sli: Sli, state: State, st: Settings) -> bool:
    """Enter the stale state above slo_freshness_s and leave it only below slo_freshness_ok_s.

    Without the dead band, a freshness that hovers around the setpoint would
    turn the reruns on and off at every tick.
    """
    if sli.freshness_s is None:
        return True
    if sli.freshness_s > st.slo_freshness_s:
        return True
    if sli.freshness_s < st.slo_freshness_ok_s:
        return False
    return state.stale


def decide(sli: Sli, state: State, st: Settings, now: float, history: list[tuple]) -> Decision:
    """The controller: a pure function, so every rule can be tested with a fake clock.

    history is the list of (at, action) of ops.controller_actions inside the window.
    """
    stale = stale_with_hysteresis(sli, state, st)
    state.stale = stale
    quality_bad = sli.grain_ok is False or (sli.last_status == "failed" and sli.error_class == "quality")
    source_bad = sli.last_status == "failed" and (sli.error_class == "source"
                                                  or sli.source_error_rate > st.slo_source_error_rate)
    run_failed = sli.last_status == "failed"
    healthy = not (stale or quality_bad or run_failed)

    if healthy:
        if state.breaker != "closed" or state.escalated or state.opens:
            return Decision("resolve", "every SLI is within its SLO")
        return Decision("none", "every SLI is within its SLO")

    # Protection comes before everything, even with an open escalation: a broken
    # gold layer is quarantined at once, so the views never serve a wrong number.
    if quality_bad and sli.last_run_id != state.handled_run:
        strikes = sum(1 for _, a in history if a == "quarantine") + 1
        return Decision("quarantine", f"quality gate failed in run {sli.last_run_id} ({', '.join(sli.failed_tasks)})",
                        escalate=strikes >= 2)

    if state.escalated:
        return Decision("hold", f"escalated ({state.escalated}); waiting for a person")

    if state.breaker == "open":
        if now < state.open_until:
            return Decision("hold", f"circuit breaker open for {int(state.open_until - now)} s more")
        return Decision("probe", "backoff elapsed; probing the source")

    if source_bad:
        return Decision("open_breaker", f"the source failed: error rate {sli.source_error_rate:.0%} "
                                        f"against an SLO of {st.slo_source_error_rate:.0%}")

    reruns = [at for at, a in history if a == "rerun"]
    if len(reruns) >= st.control_max_actions:
        return Decision("escalate", f"{len(reruns)} reruns in {st.control_window_s} s did not restore the SLOs")
    if reruns and now - max(reruns) < st.control_cooldown_s:
        return Decision("hold", f"cooldown: last rerun {int(now - max(reruns))} s ago")
    if run_failed:
        return Decision("rerun", f"run {sli.last_run_id} failed ({sli.error_class}: {', '.join(sli.failed_tasks)})")
    return Decision("rerun", f"prices are {int(sli.freshness_s or 0)} s old, SLO {st.slo_freshness_s} s")


def quarantine(con, run_id: str, reason: str, now: float) -> dict:
    """Move every batch that is not in the last known good state to quarantine.db_ingestion.

    A batch is good when its tag, timestamp, rows and digest are those recorded by
    the last successful run in ops.good_batches. Removing the others brings
    db_ingestion back to that state, so the views of gold (rebuilt and checked
    here) serve the last good numbers again; the frozen reports are tables and
    are not touched. The quarantined rows stay available for a person to inspect.
    """
    good = con.execute("SELECT count(*) FROM ops.good_batches").fetchone()[0]
    if not good:
        raise RuntimeError("no known good state to restore")
    con.execute("CREATE OR REPLACE TEMP TABLE _digest AS " + pipeline.BATCH_DIGEST).fetchall()
    bad = con.execute("""
        SELECT d.data_tag, d.timestamp FROM _digest d
        LEFT JOIN ops.good_batches g USING (data_tag, timestamp)
        WHERE g.data_tag IS NULL OR g.rows IS DISTINCT FROM d.rows OR g.digest IS DISTINCT FROM d.digest
    """).fetchall()
    moved = 0
    con.execute("BEGIN TRANSACTION").fetchall()
    try:
        for tag, ts in bad:
            moved += con.execute("SELECT count(*) FROM db_ingestion WHERE data_tag = ? AND timestamp = ?", [tag, ts]).fetchone()[0]
            con.execute("INSERT INTO quarantine.db_ingestion SELECT timestamp, data_json, data_tag, ?, ?, ? "
                        "FROM db_ingestion WHERE data_tag = ? AND timestamp = ?", [run_id, reason[:300], int(now), tag, ts]).fetchall()
            con.execute("DELETE FROM db_ingestion WHERE data_tag = ? AND timestamp = ?", [tag, ts]).fetchall()
        con.execute("COMMIT").fetchall()
    except Exception:
        con.execute("ROLLBACK").fetchall()
        raise
    gold.build_gold(con)
    checked = quality.check_gold(con)
    return {"batches": len(bad), "rows": moved, "fact_rows": checked["fact_rows"], "grain_keys": checked["fact_grain_keys"]}


class ControllerMetrics:
    """The metrics of the loop itself, pushed as job tcg_controller."""

    def __init__(self, con):
        self.registry = CollectorRegistry()
        r = self.registry
        self.sli = Gauge("tcg_controller_sli", "SLI read by the controller at the last tick", ["sli"], registry=r)
        self.slo = Gauge("tcg_controller_slo", "Setpoint (SLO) of each SLI", ["sli"], registry=r)
        self.error = Gauge("tcg_controller_error", "SLI minus SLO at the last tick; positive is a violation", ["sli"], registry=r)
        self.breaker = Gauge("tcg_controller_breaker_open", "1 while the circuit breaker on the source is open", registry=r)
        self.escalated = Gauge("tcg_controller_escalated", "1 while an escalation to a person is open", registry=r)
        self.tick = Gauge("tcg_controller_last_tick_timestamp_seconds", "Unix time of the last tick", registry=r)
        con_rows = con.execute("SELECT action, count(*) FROM ops.controller_actions GROUP BY 1 ORDER BY 1").fetchall()
        family = CounterMetricFamily("tcg_controller_actions", "Actions of the controller recorded in ops.controller_actions",
                                     labels=["action"])
        for action, n in con_rows:
            family.add_metric([action], n)

        class Fixed:
            def collect(self_inner):
                yield family

        r.register(Fixed())


def _connect(path, tries: int = 5, pause: float = 0.5):
    """Open the warehouse for writing; the exporter may be reading it for a few milliseconds."""
    for attempt in range(tries):
        try:
            return duckdb.connect(str(path))
        except duckdb.IOException:
            if attempt == tries - 1:
                raise
            time.sleep(pause)


class Controller:
    def __init__(self, settings: Settings, client_factory: Callable[[], object] | None = None,
                 now: Callable[[], float] = time.time, echo: Callable[[str], None] = print):
        self.settings = settings
        self.client_factory = client_factory or (lambda: TcgcsvClient(settings.base_url, settings.category))
        self.now = now
        self.echo = echo

    def tick(self) -> Decision:
        st, now, log = self.settings, self.now(), logger()
        st.db_path.parent.mkdir(parents=True, exist_ok=True)
        con = _connect(st.db_path)
        tick_id = uuid.uuid4().hex[:12]
        try:
            for statement in con.extract_statements(pipeline.LOG_DDL + STATE_DDL):
                con.execute(statement).fetchall()
            with tracer().start_as_current_span("control.tick") as span:
                span.set_attribute("tcg.tick_id", tick_id)
                state = State.load(con)
                with tracer().start_as_current_span("control.sense"):
                    sli = sense(con, now)
                err = errors(sli, st)
                history = con.execute("SELECT acted_at, action FROM ops.controller_actions WHERE acted_at >= ? ORDER BY acted_at",
                                      [int(now - st.control_window_s)]).fetchall()
                decision = decide(sli, state, st, now, history)
                for k, v in asdict(sli).items():
                    if isinstance(v, (int, float, str, bool)):
                        span.set_attribute(f"tcg.sli.{k}", v)
                span.set_attribute("tcg.decision", decision.action)
                span.set_attribute("tcg.reason", decision.reason)
                outcome = self._act(con, decision, state, sli, now)
                if decision.escalate and not state.escalated:
                    outcome += " Β· " + self._escalate(con, state, decision.reason, now)
                if decision.action in ("open_breaker", "quarantine", "escalate", "probe") and "fail" in outcome:
                    span.set_status(Status(StatusCode.ERROR, outcome[:200]))
                state.save(con, now)
                trace_id = ids()[0]
                if decision.action != "none":
                    con.execute("INSERT INTO ops.controller_actions VALUES (?, ?, ?, ?, ?, ?)",
                                [tick_id, int(now), decision.action, decision.reason[:300], outcome[:300], trace_id]).fetchall()
                level = 20 if decision.action in ("none", "hold", "resolve") else 30
                if state.escalated and decision.action == "escalate":
                    level = 40
                log.log(level, "control tick", extra={
                    "event": "control.tick", "tick_id": tick_id, "action": decision.action, "reason": decision.reason,
                    "outcome": outcome, "breaker": state.breaker, "escalated": state.escalated,
                    "freshness_s": sli.freshness_s, "last_run": sli.last_run_id, "last_status": sli.last_status,
                    "error_class": sli.error_class, "grain_ok": sli.grain_ok})
                self.echo(f"tick {tick_id}  {decision.action:12} {decision.reason}  β†’  {outcome}")
                self._push(con, sli, err, state, now)
        finally:
            con.close()
        return decision

    # actuators
    def _act(self, con, d: Decision, state: State, sli: Sli, now: float) -> str:
        st = self.settings
        with tracer().start_as_current_span(f"control.act {d.action}") as span:
            if d.action in ("none", "hold"):
                return "no action"
            if d.action == "resolve":
                closed = f"breaker {state.breaker} β†’ closed" if state.breaker != "closed" else "breaker closed"
                was = state.escalated
                state.breaker, state.open_until, state.opens, state.escalated = "closed", 0, 0, ""
                return closed + (f"; escalation resolved ({was})" if was else "")
            if d.action == "rerun":
                return self._rerun(con, span)
            if d.action == "open_breaker":
                return self._open(state, now)
            if d.action == "probe":
                try:
                    with tracer().start_as_current_span("control.probe"):
                        client = self.client_factory()
                        if st.fault:                       # a rehearsed fault applies to the probe too
                            from tcg_dataapp.faults import FaultyClient
                            client = FaultyClient(client, st.fault)
                        client.groups()
                except Exception as error:  # noqa: BLE001 - a failed probe reopens the breaker
                    span.record_exception(error)
                    result = f"probe failed ({type(error).__name__}); " + self._open(state, now)
                    if state.opens >= st.breaker_max_opens and not state.escalated:
                        result += " Β· " + self._escalate(con, state, f"source down after {state.opens} openings of the breaker", now)
                    return result
                state.breaker, state.open_until = "closed", 0
                return "probe ok, breaker closed; " + self._rerun(con, span)
            if d.action == "quarantine":
                try:
                    q = quarantine(con, sli.last_run_id, d.reason, now)
                except Exception as error:  # noqa: BLE001
                    span.record_exception(error)
                    return "quarantine failed: " + self._escalate(con, state, f"cannot restore a good state: {error}", now)
                state.handled_run = sli.last_run_id
                return (f"{q['batches']} batches ({q['rows']} rows) quarantined; gold back to the last good state, "
                        f"{q['fact_rows']} rows = {q['grain_keys']} keys")
            if d.action == "escalate":
                return self._escalate(con, state, d.reason, now)
        return "unknown action"

    def _rerun(self, con, span) -> str:
        ctx = pipeline.run(self.settings, client=self.client_factory(), con=con, with_today=True,
                           echo=lambda _: None, trigger="controller")
        failed = ctx.results["_failed"]
        span.set_attribute("tcg.rerun.run_id", ctx.run_id)
        if self.settings.pushgateway and ctx.metrics:
            try:
                ctx.metrics.push(self.settings.pushgateway, self.settings.instance)
            except OSError:
                pass
        return f"rerun {ctx.run_id} " + ("ok" if not failed else f"failed ({', '.join(failed)})")

    def _open(self, state: State, now: float) -> str:
        backoff = self.settings.breaker_backoff_s * 2 ** state.opens
        state.breaker, state.open_until, state.opens = "open", now + backoff, state.opens + 1
        return f"breaker open for {backoff} s (opening {state.opens})"

    def _escalate(self, con, state: State, reason: str, now: float) -> str:
        """Hand the loop to a person: once, until the SLIs are back within the SLOs."""
        state.escalated = reason[:200]
        url = self.settings.escalation_webhook
        if url:
            body = json.dumps({"service": "tcg-dataapp", "reason": reason, "at": int(now), "trace_id": ids()[0]}).encode()
            try:
                urllib.request.urlopen(urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"}),
                                       timeout=5).read()
            except OSError:
                return "escalated (webhook unreachable; the metric tcg_controller_escalated still pages)"
        return "escalated to a person"

    def _push(self, con, sli: Sli, err: dict, state: State, now: float) -> None:
        if not self.settings.pushgateway:
            return
        m = ControllerMetrics(con)
        st = self.settings
        for name, value, slo in (("freshness_s", sli.freshness_s, st.slo_freshness_s),
                                 ("run_duration_s", sli.run_duration_s, st.slo_run_duration_s),
                                 ("source_error_rate", sli.source_error_rate, st.slo_source_error_rate)):
            if value is not None:
                m.sli.labels(sli=name).set(value)
                m.slo.labels(sli=name).set(slo)
                m.error.labels(sli=name).set(err[name])
        m.sli.labels(sli="grain_ok").set(1 if sli.grain_ok else 0)
        m.breaker.set(1 if state.breaker == "open" else 0)
        m.escalated.set(1 if state.escalated else 0)
        m.tick.set(now)
        try:
            pushadd_to_gateway(st.pushgateway, job="tcg_controller", registry=m.registry,
                               grouping_key={"instance": st.instance}, timeout=10)
        except OSError:
            pass

    def loop(self, interval: float, ticks: int | None = None, sleep: Callable[[float], None] = time.sleep) -> None:
        n = 0
        while ticks is None or n < ticks:
            self.tick()
            n += 1
            if ticks is None or n < ticks:
                sleep(interval)

Faults are injected by configuration and never by code. TCG_FAULT=source_down makes every request raise, and duplicate_prices sends the prices of today twice, which breaks the grain of the fact; the same fault applies to the probe of the breaker, so a rehearsal cannot pass by accident.

21. The loop in the rehearsal

The rehearsal of 08/11/2026 ran the real DataApp against tcgcsv.com with short guardrails, so that a whole loop fits in a few minutes: a backoff of 20 seconds, ticks every 10 seconds and escalation at the third opening of the breaker.

source down Β· TCG_FAULT=source_down Β· control --interval 10 --ticks 9
tick 4a1b2d5ed253  open_breaker the source failed: error rate 100% against an SLO of 50%
      β†’ breaker open for 20 s (opening 1)
tick 66dc1db567fa  hold         circuit breaker open for 9 s more
tick f4a9fedb3630  probe        backoff elapsed; probing the source
      β†’ probe failed (ConnectionError); breaker open for 40 s (opening 2)
tick af1efebbe1e4  hold         circuit breaker open for 29 s more
tick eea2eca30d83  hold         circuit breaker open for 19 s more
tick f6984ac12f9c  hold         circuit breaker open for 9 s more
tick df512f4b8f19  probe        backoff elapsed; probing the source
      β†’ probe failed (ConnectionError); breaker open for 80 s (opening 3) Β· escalated to a person
tick a7a10be7a194  hold         escalated (source down after 3 openings of the breaker); waiting for a person
tick b1eb5322b207  hold         escalated (source down after 3 openings of the breaker); waiting for a person

No rerun was attempted against the source while it was down. TcgControllerEscalated fired in Prometheus. After a person ran the DataApp again without the fault, the next tick was resolve, which closed the breaker and the escalation, and the following one was none.

A run with TCG_FAULT=duplicate_prices loaded the prices of today twice and failed at check_quality: 9,613 rows for 7,782 keys of the grain. The first tick quarantined three batches, 5,159 rows: the catalogue captured by the failing run and the batch of today. Gold went back to 5,951 rows = 5,951 keys, and the frozen report of September kept its 1,226 rows. With the fault removed, as a transient failure would be, the second tick reran the DataApp, the run succeeded with 7,782 rows, and the third tick found every SLI within its SLO. With the fault kept, within the same six hours, the second quarantine also escalated and the following ticks held without rerunning, with gold at 5,951 = 5,951.

The loop is observable as well. A tick that reruns is one trace of 41 spans: control.tick, control.sense, control.act rerun and, under it, the whole run, with tcg.trigger = controller.

22. The same idea at scale

The controller of the DataApp is small, but its structure is that of the control loops that run most production systems. Each Kubernetes controller runs a reconciliation loop: it compares the desired state declared in a resource with the observed state and acts until they match, so a Deployment of three replicas recreates a pod that died. The Horizontal Pod Autoscaler has a setpoint in CPU or in a custom metric, a sensor in the metrics API, an actuator on the number of replicas, and a stabilisation window against oscillation. Alertmanager can deliver an alert to a webhook that runs a remediation for a known failure, with routing, grouping and silences as guardrails. The error budget of site reliability engineering closes a loop on the work of a team: while the SLO leaves budget, changes go out, and when the budget is spent, releases stop until reliability recovers.

Part VILab

23. The lab in four steps

The professor starts from a copy of the package of Lesson 7 and builds the reference with the four prompts below, comparing each step with lab/lesson-10/. Each prompt states the facts measured in the rehearsal, so that both the agent and the class can check the result. Prompt 05 is for the groups.

Step 01 Β· Metrics

Prompt 01 Β· CREATE
[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.

Review before moving on:

  • out/metrics.prom shows the rows 7, 1490, 657, 896, 1153, 1414 and 1831
  • tcg_run_info has one series, with the run and the trace
  • the etls do not import prometheus_client

Step 02 Β· Traces and logs

Prompt 02 Β· CREATE
[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.

Review before moving on:

  • a run is one trace, with the tasks as children of the root
  • a failing task has status ERROR, its attempts as events and the exception
  • the log line of a failure has the span_id of its task

Step 03 Β· Stack and correlation

Prompt 03 Β· CREATE
[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.

Review before moving on:

  • promtool test rules prints SUCCESS, with the trace in TcgRunFailed
  • a run with TCG_FAULT=source_down fires the alert with its run and trace
  • "Logs for this span" opens the lines of the failing span

Step 04 Β· Closed loop

Prompt 04 Β· CREATE
[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.

Review before moving on:

  • a source down opens the breaker, backs off and escalates once, with no rerun
  • a duplicated batch is quarantined, gold has rows = keys and the frozen report is kept
  • the 25 tests pass

Second hour Β· Your DataApp

Prompt 05 Β· CREATE
[C] Character
You are a data engineer of the group, responsible for operating the
DataApp of the partner: the package of Lesson 7, or the flow of Lesson 8.
Today it gains the three signals of observability and one closed loop
for one service level objective.

[R] Request
Apply the method of Lesson 10 to the DataApp of the group:
1. Metrics: the run pushes its outcome, duration, rows per task, errors of
   the source and an info metric with its run_id and trace_id; an exporter
   or a query publishes the freshness and the volume of the data.
2. Traces: one root span per run, one per task, and child spans for each
   call to the source and each SQL file or transformation.
3. Logs: JSON lines with run_id, trace_id and span_id, written inside the
   span they describe.
4. The stack of lab/lesson-10/stack, with the dashboard adapted to the
   names of the group, and three alerting rules with promtool tests.
5. Choose ONE SLO of the DataApp (for example: the data of yesterday is
   available by 08:00 UTC) and write its closed loop:
   - the setpoint and the dead band;
   - the sensor (which SLI, read from where);
   - the actuator and what it changes in the process;
   - the guardrails: cooldown, budget per window and when it escalates;
   - one test that breaks the plant and proves that the loop either
     recovers or escalates once.
6. Rehearse a failure on purpose and record the path alert β†’ metric β†’
   trace β†’ log line, with the identifiers that were followed.

[E] Example
SLO: prices of the day loaded by 08:00 UTC Β· sensor: max(timestamp) of
db_ingestion Β· actuator: rerun of the extraction Β· guardrails: 3 reruns in
6 h, 10 min of cooldown Β· escalation: webhook to the channel of the group.

[A] Adjustments
- Do not put credentials of the partner in the repository, in the logs or
  in span attributes.
- If an SLO has no safe actuator, state it: that SLO stays as an alert to a
  person, and the reason belongs in the README.

[T] Type of output
The changes in the repository of the group, the output of pytest and of
promtool, and docs/observability.md with the SLO, the diagram of its loop
and the path of the rehearsed failure.

[E] Extras
Show the plan before editing. Stop at the end of each item for review.

24. Tests of the package

The package has 25 tests that run in about ten seconds without the network, with the fake client of two sets of Lesson 7, which can now be switched off to simulate a source down. The tests of the signals use an in-memory span exporter; the tests of the loop use a fake clock, so that hours of backoff pass in milliseconds.

FileTestsWhat they prove
test_cli.py, test_landing.py, test_pipeline.py9the package of Lesson 7 still works
test_telemetry.py5the metrics of a good and of a failed run, the push and the exporter
test_signals.py4one trace per run with its tree, the marks of a failure, the identifiers in every log line, tcg_run_info
test_control.py7a healthy DataApp gets no action; stale data is rerun and the loop settles; a source down escalates once with no rerun; a source that returns closes the breaker alone; a bad batch is quarantined and a repeated one escalates; a failure without an actuator is rerun within the budget; a tick is a trace with the rerun as its child

25. Reference numbers

MeasureValue
good run with --with-today13 tasks ok in 30.6 s; 7,782 prices in 6 captures; 697 cells; September frozen with 1,226 rows
its trace and its logs38 spans in Tempo (1 run, 13 tasks, 20 requests, 4 SQL files); 15 lines in Loki, each with its trace_id
run with source_downfailed in 3.0 s; 17 spans; TcgRunFailed with the run and the trace; 3 lines of the failing span
loop, source downopen, hold, probe (40 s), 3 Γ— hold, probe (80 s) and escalation, 2 Γ— hold; then resolve after a person reran
loop, duplicated batch9,613 rows for 7,782 keys; quarantine of 3 batches, 5,159 rows; gold 5,951 = 5,951; frozen report 1,226 rows kept
tick with a rerunone trace of 41 spans, 34.6 s
promtoolcheck config: 11 rules; test rules: SUCCESS
tests25 passed in about 10 s, without network

26. What the rehearsal revealed

Five problems appeared only when the reference ran against real data and a real stack, and the prompts and the reference already carry their corrections.

A batch replaced by the same key

The prices of today are loaded as the batch of noon UTC, so a run with duplicated prices replaced the good batch of the same day instead of adding a new one. A good state recorded only by key would not detect it, which is why ops.good_batches keeps the rows and an md5 digest of each batch. The consequence is that the quarantine cannot restore the replaced content: gold falls back to the previous captures, 5,951 rows, until a good run brings today back.

The window of the escalation

In the rehearsal, the persistent bad batch escalated at its first quarantine, because the quarantine of the transient case had happened less than six hours before. The rule counts quarantines in the window, not per fault, which is the intended behaviour: two bad batches in six hours are a pattern that a person should see.

Two runs in the same second

The tests ran a good run and a failed run within the same second, and the sensor, which looked for the last run by its start time, sometimes read the good one. The last run is now chosen by start time and then by insertion order.

A reserved word

The first version of ops.controller_actions had a column named at, which DuckDB rejects as a reserved word; it is acted_at.

Explore closed to viewers

With anonymous access as Viewer, Grafana redirected every link to Explore back to the dashboard, so the links from the metric to the trace did nothing. The stack sets GF_USERS_VIEWERS_CAN_EDIT, acceptable on a local stack and not on a shared one.

27. The second hour

In the second hour each group applies the method to its own DataApp, the package of Lesson 7 or the flow of Lesson 8, with prompt 05. The result expected at the end of the session has two parts. The first is the three signals with the identifiers that link them, three alerting rules tested with promtool, and a failure rehearsed on purpose and followed from the alert to the log line. The second is one SLO of the DataApp with its closed loop: the setpoint and the dead band, the sensor, the actuator and what it changes, the cooldown, the budget and the condition to escalate, and a test that breaks the DataApp and proves that the loop recovers or escalates once. When an SLO has no safe actuator, the group states it, and that SLO stays as an alert to a person.

28. Glossary

TermMeaning in this lesson
observabilitythe property of a system whose internal state can be inferred from what it emits
metric, trace, logthe three signals: an aggregated number, the path of one execution, a discrete event
spanan operation of a trace, with start, end, parent, attributes, events and status
run_id, trace_id, span_idthe identifiers that link the signals: a run, its trace, one operation
OTLPthe protocol of OpenTelemetry that carries the three signals
collectorthe service that receives telemetry and routes each signal to its store
cardinalitythe number of series of a metric, the product of the values of its labels
SLI, SLOthe indicator measured and the objective it must meet
setpoint, sensor, comparator, controller, actuator, plantthe elements of a closed loop
open loopa control that acts without measuring the result
hysteresisa dead band between the threshold that triggers an action and the one that ends it
circuit breakera guard that stops calling a failing dependency and probes it after a backoff
quarantinethe isolation of data that failed a check, restoring the last good state
escalationhanding the loop to a person, once

29. Checklist

  • Every metric has the prefix of the application and its unit in the name, and no label takes an identifier.
  • The run and its trace are named by one info metric.
  • A run is one trace, with one span per task, per call to the source and per transformation.
  • A failure sets the status of its span, records the exception and its attempts.
  • Every log line is JSON and carries run_id, trace_id and span_id.
  • The application sends traces and logs to one collector.
  • From an alert, a person reaches the log line of the failing span in four hops.
  • Every alert describes a symptom, has a reason for its threshold and a promtool test.
  • Each SLO declares whether it has an actuator; if not, it is an alert to a person.
  • The loop has hysteresis, a cooldown, a budget per window and one escalation.
  • A test breaks the DataApp and proves that the loop recovers or escalates once.
  • Every action of the controller is a span, a log line and a metric.

30. References and self-study