---
title: "Tracing and metrics"
description: "Spans, events and metrics with typed fields, followed across tasks and exported to OpenTelemetry."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Tracing and metrics

> **Built**
>
> Everything on this page is built, and the book's gate holds every example on
> it to compiling. The programs that hold the compiler to this page are in
> `corpus/stdlib/`; [Holding it](#holding-it) lists them. What the first version
> leaves out is [listed at the end](#not-in-the-first-version).

A program says what it is doing with **spans** and **events**, and keeps count
with **metrics**. A span is a stretch of work with a name and fields — a call
to `load_user` with `id=7` — and spans nest. An event is one moment inside
them, with a level, a message and fields. A metric is a number kept as the
program runs — requests answered, how long each took — by the attributes it is
counted by. Who sees them is decided when the program runs, not when it is
written: a line on standard error, a JSON line, an OpenTelemetry collector, a
Prometheus scrape, or a test asserting on them.

It is Rust's `tracing` crate and OpenTelemetry's metrics, built into the
language rather than written on top of it, and four things follow from that:

- **A span follows what it makes.** The span a function is in is the span of
  its calls, of the tasks it spawns and of the closures it makes: a callback
  logs in the span it was made in, wherever it is called from. The runtime
  owns the scheduler, so a task's span is put back each time it resumes.
  There is no `.instrument(…)` to forget and no guard that can be held across
  a suspension.
- **A field is named once.** A template part that names a value is a field of
  that name, so the message and the fields are written once, together.
- **An instrument is a function.** Its parameters are its attributes, typed and
  named; its return type is its kind; its doc comment is its description.
- **Off costs nothing, and on costs little.** A callsite that is off is one
  load and one branch, and its arguments are never evaluated; a measurement is
  an add into memory the runtime keeps, with no host call; and none of it adds
  an effect to anything.

## Events

An event is a call to one of five functions, one per level, from the most
severe: `trace.error`, `trace.warn`, `trace.info`, `trace.debug`,
`trace.trace`. Each takes a message, written as a string literal or a
template, and optionally a record of more fields:

```atoll
import trace

struct User {
    id   int
    name string
}

fn main() void {
    user := User { id: 7, name: "ada" }
    tries := 2
    trace.info("loaded ${user.name} after ${tries + 1} tries")
    trace.warn("cache is cold", { hits: 0, ratio: 0.25 })
}
```

**A template part that names a value is a field** with that name: `${user.name}`
is the field `user.name`, `${tries}` would be `tries`. A part that computes —
`${tries + 1}`, `${f(x)}` — is in the message and is not a field; to name it,
put it in the record. A record's fields come after the template's, in the order
written, and a name may not be both.

**The message is part of the callsite**, so it is a literal: `trace.info(msg)`
with `msg` a variable is refused, and `trace.info("${msg}")` is what it means.

**Arguments are evaluated only when the event is on.** `trace.debug("${expensive()}")`
does not call `expensive` when `debug` is off. To prepare something for an
event and only then, ask first:

```atoll
import trace

fn summary(xs []int) string {
    return "${xs.len()} values"
}

fn main() void {
    xs := [3, 1, 2]
    if trace.enabled(trace.Level.Debug) {
        s := summary(xs)
        trace.debug("prepared ${s}")
    }
}
```

A field's value is anything a template part can be: what `"${x}"` accepts, an
event's record and `@trace` accept, and what it refuses, they refuse. Numbers,
`bool` and `string` are kept as what they are, so JSON and OpenTelemetry get a
number as a number; anything else is written as its template text when, and
only when, a subscriber reads it.

## Spans: `@trace`

`@trace` on a function makes each call to it a span, named after the function
and holding its parameters as fields:

```atoll
import trace

@trace
fn fetch(url string, attempt int) int {
    trace.info("asking")
    return url.len() + attempt
}

@trace
fn load(id int) int {
    trace.info("loading ${id}")
    return fetch("https://a.dev/${id}", 1)
}

fn main() void {
    println("${load(7)}")
}
```

With `ATOLL_LOG=info`, that writes:

```text
 INFO load{id=7}: loading 7
 INFO load{id=7}:fetch{url="https://a.dev/7" attempt=1}: asking
```

A parameter is recorded by borrowing it — nothing is copied — and every
parameter is recorded except `self` and those `skip` names. A parameter whose
type has no text, a function value or a task, is refused with the `skip` that
leaves it out. The span **closes on every way out** of the call: a `return`, a
`?` or an `error`, a trap, and the cancellation of its task. A call that leaves
through its error channel closes its span *failed* with the error's text; one
whose task is cancelled closes it *cancelled*.

The decorator takes these, in any order:

| Argument | Meaning |
| --- | --- |
| `debug` (any level) | the span's level; `info` when not said |
| `skip(a, b)` | parameters left out |
| `name("load user")` | the span's name, instead of the function's |
| `ret` | the returned value is recorded when the span closes |
| `parent(ctx)` | the span continues `ctx`, a parameter of type `trace.Context` or `trace.Context?`, which is then not a field; see [Context](#context-and-propagation) |
| `kind(server)` | the OpenTelemetry span kind: `internal`, `server`, `client`, `producer` or `consumer` |

A span whose level is off is not a span at all: what happens inside it is in
the spans around it, as if the function had no decorator.

**More fields as the call goes.** `trace.record({ … })` adds fields to the
current span, from where it is written on — the place for what a parameter
does not say, `self`'s identity among them:

```atoll
import trace

struct Order {
    id    int
    lines []int
}

impl Order {
    @trace
    fn total(&self) int {
        trace.record({ order: self.id, lines: self.lines.len() })
        mut sum := 0
        for n in self.lines {
            sum += n
        }
        return sum
    }
}

fn main() void {
    o := Order { id: 12, lines: [3, 4] }
    println("${o.total()}")
}
```

A method's span is named `Type.method`: `Order.total`.

## Tasks

A task's spans are its own. The span a task is in goes with it across every
suspension — a `yield_now`, an `await`, a host call that suspends — and is put
back when the task resumes. While a task is parked its spans stay open, so a
span knows how long it was **busy** (its task running) and how long **idle**
(parked inside it), exactly: the runtime decides both.

A task `spawn` starts is a child of the span the `spawn` is written in:

```atoll
import trace
import task.{yield_now}

@trace
fn child(n int) int {
    trace.info("before")
    yield_now()
    trace.info("after")
    return n + 1
}

@trace
fn parent(n int) int {
    t := spawn { child(n) }
    return t.await() ?? -1
}

fn main() void {
    println("${parent(4)}")
}
```

Both events are in `parent{n=4}:child{n=4}`, the one after the suspension as
much as the one before. A task cancelled by a `race` it lost closes its open
spans *cancelled*.

Work placed on another reactor of a group (`r.spawn { … }`) is in the span it
was placed from there too. Its events, and the spans it opens, are in that
span's trace and children of it, so an exporter joins the two halves; a text
line names only the spans open on its own reactor. A capture does not reach
across: what placed work emits there is written, not captured.

## Closures

A closure logs in the span it was made in, not the one it is called from:

```atoll
import trace

@trace(skip(f))
fn each(f fn() -> void) void {
    f()
}

@trace
fn load() void {
    each(() => {
        trace.info("loaded")
    })
}

fn main() void {
    load()
}
```

The event is in `load`, not `load:each`: a callback is part of the code that
made it, not of the function that calls it. `each` is in its own span again
once the callback returns, however it returns, and a task the callback spawns
is a child of `load`. A closure called after its span has closed logs in that
span still, so an exporter puts the event in its trace; the text line, with no
open span to name, writes it with no chain.

A closure carries its span only where its body logs, opens a span, makes a
request a host opens one for, or spawns a task, itself or through what it
calls. It captures the span where it is made, once a span has been open in
the run, and binds it while it runs. Any other closure is made and called as
if there were no tracing, and a function type says nothing of it.

## Metrics

An **instrument** is a function with no body: `@metric` says the runtime
supplies it, as `@host` says the host does. Its return type is the kind of
instrument, its parameters are the attributes a measurement is kept by, and
its doc comment is the description an exporter sends:

```atoll
import metric

/// Requests answered, by route and status.
@metric("{request}")
fn requests(route &string, status int) metric.Counter[int]

/// How long a request took.
@metric("ms")
fn latency(route &string) metric.Histogram[float]

fn handle(route string) int {
    requests(route, 200).add(1)
    latency(route).record(12.5)
    return 200
}
```

**Calling an instrument names a series**: `requests("/users", 200)` is the
count kept for that route and that status, and a measurement is a method of
it. The four kinds are OpenTelemetry's synchronous instruments:

| Kind | Keeps | Measured by | Read by |
| --- | --- | --- | --- |
| `metric.Counter[T]` | a sum that only goes up | `add(n)` | `value()` |
| `metric.UpDown[T]` | a sum that goes up and down | `add(n)` | `value()` |
| `metric.Gauge[T]` | the last value set | `set(v)` | `value()`, a `T?` that is `None` until set |
| `metric.Histogram[T]` | a distribution | `record(v)` | `count()`, `sum()`, `min()`, `max()` |

`T` is `int` or `float`, and for a histogram or a gauge `time.Duration` too,
which is recorded in the instrument's unit — `s`, `ms`, `us` or `ns`.

**A series is a value of one word**, its place in the instrument's table, so
it can be kept. A loop that adds to one series names it once:

```atoll
import metric

/// Rows read, by table.
@metric("{row}")
fn rows_read(table &string) metric.Counter[int]

fn scan(table string, rows []int) int {
    read := rows_read(table)
    mut total := 0
    for r in rows {
        total += r
        read.add(1)
    }
    return total
}
```

**An attribute is a key**, so a parameter is a `bool`, an integer, a
`string`, or an enum whose variants carry nothing (its variant's name). A
`float` is refused: two floats that print alike can differ, and `NaN` is not
equal to itself, so a float attribute makes series nobody can name. A `string`
is borrowed, `route &string`: the instrument reads it to name the series and
keeps nothing, so naming a series moves nothing out of the caller, and one
taken by value is refused.

**A counter only goes up.** `add` with a negative literal is refused before the
program runs, and a negative amount computed while it runs traps where it is
added, naming the instrument.

**An instrument keeps at most 2000 series.** A measurement for an attribute set
past that goes to one overflow series with the attribute
`otel.metric.overflow = true`, and the exporter says so once. `limit(n)` raises
or lowers it.

The decorator takes the unit first, when the number has one — a UCUM string,
`"ms"`, `"By"`, `"{request}"` — and then, in any order:

| Argument | Meaning |
| --- | --- |
| `name("http.server.request.duration")` | the name the instrument is exported under; the function's name when not said |
| `limit(n)` | the most series it keeps |
| `buckets([1, 5, 10, 50])` | a histogram's bucket bounds, ascending |
| `exponential` | a base-2 exponential histogram, which needs no bounds and takes none |

A histogram with neither has OpenTelemetry's default bounds, `0, 5, 10, 25, 50,
75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000`, unless the run asks for
exponential ones ([OpenTelemetry](#metrics-export)).

**Aggregation always runs**, exported or not, so `value()` answers the same in
a test as in production. Under `atoll test` each test starts with every series
at zero, and a series never measured reads zero and is not exported:

```atoll
import metric

/// Retries made.
@metric("{retry}")
fn retries(op &string) metric.Counter[int]

fn fetch(attempt int) void {
    if attempt > 1 {
        retries("fetch").add(1)
    }
}

test "a second attempt is counted" {
    fetch(1)
    fetch(2)
    assert_eq(retries("fetch").value(), 1)
}
```

**An exponential histogram** has buckets that are powers of two and their
roots: at scale `s`, bucket `i` holds the values in `(2^(i/2^s), 2^((i+1)/2^s)]`.
It starts at scale 8, 256 buckets an octave, and as what it records spreads
further than 160 buckets on either side of zero can hold, its scale falls,
each step merging pairs of buckets, until they do: 1 ms to 10 s fits at scale
3. Zero is counted apart, a value below zero goes to buckets of its own, and
one that is no number or is infinite is not recorded. A measurement costs a
search of 255 steps' mantissas, eight compares, and an add; one past the
buckets kept is the runtime's to place. OpenTelemetry's own scale starts at
20, finer than one bucket in 400 tells apart; Atoll's at 8 keeps the steps in
2 KB.

**A histogram links to a trace.** A measurement made in a sampled span keeps
that span's trace and span IDs as an exemplar, so the bucket a slow request
fell in leads to the trace of a slow request: an explicit histogram's last in
each bucket, an exponential one's twenty sampled from all, as OpenTelemetry's
reservoirs keep them. They are kept while a metrics exporter that writes
them — `otlp` or `console` — is on, as `OTEL_METRICS_EXEMPLAR_FILTER` says:
`trace_based` (the default) those in a sampled span, `always_on` every
measurement, `always_off` none. A histogram's `record` reads one word the
runtime writes at each turn and a span's opening sets; while it is clear, the
cost is that load and a branch.

**The runtime keeps its own**, exported under the scope `atoll` whenever
metrics are: `atoll.memory.used` (`By`), the program's memory handed out,
`atoll.task.count` (`{task}`), its tasks alive, both up-down counters, and the
counter `atoll.task.switches` (`{switch}`), the turns its tasks have run. They
are not among what `atoll run --metrics` prints, which is the program's own.

`atoll run --metrics` prints every series at exit, on standard error:

```text
requests{route="/users" status=200} 3
latency{route="/users"} count=2 sum=34 min=4 max=30
```

## Seeing it

What is written, and where, is the run's to say. The **filter**, `ATOLL_LOG`,
turns callsites on by level and by module, and the **subscribers** — the host's
text and JSON writers and its OpenTelemetry exporter — receive what it turns
on. With no `ATOLL_LOG`, `warn` and `error` are written as text to standard
error, and nothing is exported. Metrics are not filtered: every instrument
aggregates, and the metrics exporter sends what it holds.

| `ATOLL_LOG` | Turns on |
| --- | --- |
| `info` | `info` and more severe, everywhere |
| `warn,acme.dev/kit/db=debug` | `warn` everywhere, `debug` in that module and the modules under it |
| `off` | nothing |

`atoll run --log <filter>` is the same as setting it. A module is named by its
path, a file compiled alone is the module `main`, and a directive for a module
holds for the modules under it.

| Variable | Meaning |
| --- | --- |
| `ATOLL_LOG_FORMAT` | `text` (the default), `json`, or `off`, which writes nothing and leaves export to OpenTelemetry |
| `ATOLL_LOG_SPANS` | `close` adds a line each time a span closes, with its busy and idle times |
| `ATOLL_LOG_STABLE` | `1`: no times, and span and trace IDs counted from 1, so a run writes what its program says and nothing about the clock; on under `atoll test` |
| `ATOLL_FLIGHT` | a level, and how many after a `:` (1000 when not said): the [flight recorder](#the-flight-recorder) |

### The flight recorder

`ATOLL_FLIGHT=debug` keeps the run's last 1000 events at `debug` and under in
memory, whatever `ATOLL_LOG` writes, and writes them nowhere while the run goes
on. A run that fails — a trap, a `main` that returned an error — writes them
to standard error before its report, the oldest first, each with the spans it
was in, as the text writer would have:

```text
atoll: the last 3 events before the run failed:
  DEBUG ratio{a=12 b=1}: dividing 12 by 1
   INFO turn 0
  DEBUG ratio{a=12 b=0}: dividing 12 by 0
atoll run: trap: division by zero
```

`ATOLL_FLIGHT=trace:5000` keeps 5000 at every level. What it costs is what an
event at its level costs when it is on: the level is on for every module, so
each such event is rendered, into the recorder's ring rather than the output.

### Writing never waits

The text and JSON writers write through the queue `println` and `eprintln`
write through ([Console](https://docs.atoll.workreef.dev/language/standard-library/console/#println-does-not-suspend)):
an event that is on is rendered into it, behind what the program printed before
it, and a host thread writes it out, so events and printed lines keep the order
they happened in and the program does not wait for standard error. Unlike a
printed line, an event never waits for the queue either: one that finds it
holding a megabyte the writer has not taken is dropped and counted, and the
writer says so on standard error —
`atoll: 258337 trace records were dropped: the output queue was full`.

### Text

One line per event, on standard error:

```text
<time> <LEVEL> <spans>: <module>: <message> <fields>
```

- `<time>` is RFC 3339 in UTC, to the microsecond; under `ATOLL_LOG_STABLE` it
  is left out.
- `<LEVEL>` is five wide: `ERROR`, ` WARN`, ` INFO`, `DEBUG`, `TRACE`.
- `<spans>` is the event's spans, outermost first, each its name and fields in
  braces, joined by `:` — `load{id=7}:fetch{url="https://a.dev/7" attempt=1}`.
  With no span, it and its `: ` are left out.
- `<module>` is the event's module, left out when it is the program's own root
  module, so a library's lines say whose they are and the program's do not.
- `<message>` is the rendered message; `<fields>` are the record's fields as
  `name=value`, separated by spaces. Template fields are in the message and are
  not written again.

A field's value is written as its template text, except that a `string` is
quoted, so `name="ada lovelace"` is one field.

### JSON

One object per line, its keys in this order:

```text
{"time":"…","level":"INFO","target":"main","spans":[{"name":"load","fields":{"id":7}}],"message":"loading 7","fields":{"id":7}}
```

`fields` holds every field of the event, the template's and then the record's;
numbers and `bool` are JSON numbers and booleans, anything else a string.
`spans` is outermost first, and `[]` when there is none. Under
`ATOLL_LOG_STABLE`, `time` is left out.

### A trap says where it was

A trap prints the stack it stopped on, as it always has, and then the spans it
stopped in, with their fields — which call, of the thousand, it was:

```text
atoll run: trap: division by zero
  at ratio (main.at:5:12)
  5 |     return a / b
    |            ^^^^^
  at work (main.at:10:12)
  at main (main.at:14:16)
  in work{n=4}:ratio{a=4 b=0}
```

The spans are those the filter turned on; with none on, the line is left out.

## Tests

`atoll test` captures what each test emits, at every level whatever
`ATOLL_LOG` says, and prints it with the test's failure. `trace.captured()` is
what the test has emitted so far, for a test that asserts on its own tracing:

```atoll
import trace

fn fetch(attempt int) void {
    if attempt > 1 {
        trace.warn("retrying", { attempt: attempt })
    }
}

test "a second attempt is warned" {
    fetch(1)
    fetch(2)
    seen := trace.captured()
    assert_eq(seen.len(), 1)
    assert_eq(seen[0].level, trace.Level.Warn)
    assert_eq(seen[0].field("attempt"), Some("2"))
}
```

`trace.capture(f)` does the same for any program: it runs `f` with what it
and the tasks it spawns emit captured instead of written, at every level, and
returns the records in the order they happened. `f` may suspend — await a task,
call a host function that waits — as the code worth capturing often does. A
closure written in `capture(…)`'s place is run there, as part of the function it
is written in, so it suspends as that function does. Any other callback is a
function value, and `capture` takes it with a row variable —
`capture[E](f fn() using [E] -> void) []Record using [E]` — so one that suspends
makes the call suspend ([Effects in function types](https://docs.atoll.workreef.dev/language/concurrency/effects/#effects-in-function-types)):
a `fn() using [Suspend] -> void` held in a local or a field, a named function
that waits, and a closure written in place that leaves itself with `return`.

```atoll
import trace

@trace
fn double(n int) int {
    return n * 2
}

fn main() void {
    records := trace.capture(() => {
        println("${double(21)}")
    })
    for r in records {
        println("${r}")
    }
}
```

A `trace.Record` prints as the text line its event would be under
`ATOLL_LOG_STABLE`, and a span's opening and closing are records of their own.
A closing says how the span closed: nothing when it returned, `-> value` under
`ret`, `failed: <error>` or `cancelled`:

```text
 INFO open both{a=1 b=0}
 INFO open both{a=1 b=0}:find{id=0}
 INFO close both{a=1 b=0}:find{id=0} failed: NotFound
 INFO close both{a=1 b=0} failed: NotFound
```

Span IDs in a capture are counted from 1, whatever the run's mode.

| `trace.Record` | |
| --- | --- |
| `kind` | `Kind.Event`, `Kind.Open` or `Kind.Close` |
| `level` | the event's or the span's level |
| `name` | the span's name; `""` for an event |
| `message` | the event's rendered message; `""` for a span |
| `fields` | `[]trace.Field`, each a `name` and its `value` as text, in the order written |
| `span`, `parent` | the span this is in (an event) or is (a span), and the one around it; `0` for none |
| `status` | for `Close`: `Ok`, `Failed(text)` or `Cancelled` |
| `returned` | for `Close` under `ret`: the returned value's text, `string?` |
| `field(name)` | the value of the field of that name, `string?` |

## OpenTelemetry

The host exports spans, events and metrics over OTLP to any OpenTelemetry
collector, and metrics to Prometheus too. Export is configured as every
OpenTelemetry SDK is, by the standard variables, with one difference: **a run
sends nothing it was not asked to.** A signal is exported when its own
`OTEL_*_EXPORTER` says how, or, for all three, when `OTEL_EXPORTER_OTLP_ENDPOINT`
names a collector; a run that set neither sends nothing, and one that asked for
Prometheus metrics sends no traces.

| Variable | Meaning | Default |
| --- | --- | --- |
| `OTEL_TRACES_EXPORTER` | `otlp`, `console`, `file` or `none` | `otlp` when an endpoint is set, `none` otherwise |
| `OTEL_LOGS_EXPORTER` | the same, for events | the same |
| `OTEL_METRICS_EXPORTER` | `otlp`, `prometheus`, `console`, `file` or `none` | the same |
| `ATOLL_OTEL_FILE`, `ATOLL_OTEL_FILE_MAX_BYTES`, `ATOLL_OTEL_FILE_BACKUPS` | where `file` writes, how large a file grows, and how many older ones are kept | `atoll-telemetry.jsonl`, 100 MiB, 3 |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | the collector | `http://localhost:4318` for an exporter set to `otlp` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf`, `http/json` or `grpc` | `http/protobuf` |
| `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_TIMEOUT` | as the specification says | |
| `OTEL_SERVICE_NAME` | the resource's `service.name` | the package's module path; `main` for a file alone |
| `OTEL_RESOURCE_ATTRIBUTES` | more resource attributes | |
| `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG` | which traces are exported | `parentbased_always_on` |
| `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BSP_MAX_EXPORT_BATCH_SIZE`, `OTEL_BSP_EXPORT_TIMEOUT` | the batch exporter | 2048, 5000 ms, 512, 30000 ms |
| `OTEL_BLRP_MAX_QUEUE_SIZE`, `OTEL_BLRP_SCHEDULE_DELAY`, `OTEL_BLRP_MAX_EXPORT_BATCH_SIZE` | the batch exporter, for events | 2048, 1000 ms, 512 |
| `OTEL_SDK_DISABLED` | `true` turns export off | |

`ATOLL_LOG` decides what exists, for every subscriber at once; the sampler
decides which of the traces it let through are exported, and an unsampled span
is still written as text.

A request the collector cannot take for now — it answers `429`, `502`, `503` or
`504`, or does not answer — is sent again, up to three times, after a quarter
of a second and twice as long each time, or after what its `Retry-After` says.
Any other answer is final, and the exporter says why on standard error. The
exporter's thread waits, never the program.

### Metrics export

A run's series are collected when the interval is up and the runtime next has
control, between one task's turn and the next or while it waits for the world,
and handed to the exporter's thread; a run never waits for a send. One that
neither yields nor waits sends them when it ends, as every run does.

| Variable | Meaning | Default |
| --- | --- | --- |
| `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_METRIC_EXPORT_TIMEOUT` | how often metrics are collected and sent | 60000 ms, 30000 ms |
| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | `cumulative`, `delta` or `lowmemory` | `cumulative` |
| `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION` | `explicit_bucket_histogram` or `base2_exponential_bucket_histogram` | `explicit_bucket_histogram` |
| `OTEL_METRICS_EXEMPLAR_FILTER` | `trace_based`, `always_on` or `always_off` | `trace_based` |
| `OTEL_EXPORTER_PROMETHEUS_HOST`, `OTEL_EXPORTER_PROMETHEUS_PORT` | where `prometheus` serves `/metrics` | `localhost`, 9464 |

At each interval the runtime copies every series at the scheduler's next poll.
Only one task runs at a time, so the copy is one consistent snapshot with no
lock, and no measurement waits for it; the host encodes and sends it off the
guest's path. At exit a last collection is exported. `prometheus` serves the
latest snapshot in the Prometheus text format, its names converted as the
specification says (`requests_total`, `latency_milliseconds`), each attribute a
label and the module `otel_scope_name`; its collection runs every second unless
`OTEL_METRIC_EXPORT_INTERVAL` says otherwise, since a scrape reads the last.

| Atoll | OTLP |
| --- | --- |
| `Counter` | a monotonic `Sum` |
| `UpDown` | a non-monotonic `Sum` |
| `Gauge` | a `Gauge` |
| `Histogram` | a `Histogram`, or an `ExponentialHistogram` |
| `int`, `float`, `time.Duration` | `asInt`, `asDouble`, `asDouble` in the instrument's unit |
| the doc comment, the unit | `description`, `unit` |
| the module | the instrumentation scope; instruments in the order the module declares them, series in the order they were first measured |

### What a span and an event become

| Atoll | OTLP |
| --- | --- |
| a span | a `Span`: its name, start and end, parent, kind, and its fields as attributes, with `code.function.name` (`main.load`), `code.file.path` and `code.line.number` |
| busy and idle time | the attributes `atoll.busy_ns` and `atoll.idle_ns` |
| closed *failed* | status `ERROR` with the error's text, and an `exception` event: `exception.type` is the error's type, `exception.message` its text |
| closed by a trap | status `ERROR`, and an `exception` event with the trap's message and the stack as `exception.stacktrace` |
| closed *cancelled* | status unset, and the attribute `atoll.cancelled = true`: a cancelled task did what it was asked |
| closed under `ret` | the attribute `atoll.returned`, the returned value's text |
| an event | a `LogRecord`: its message is the body, its fields and `code.*` are attributes, and it carries the trace and span IDs of the span it is in |
| a level | severity `ERROR` 17, `WARN` 13, `INFO` 9, `DEBUG` 5, `TRACE` 1 |
| a module | the instrumentation scope, with the package's version |
| the program | the resource: `service.name`, `service.version` from the manifest, `telemetry.sdk.name` and `telemetry.sdk.language` `atoll`, `telemetry.sdk.version`, `process.pid`, `host.name` |

Trace IDs are 128 random bits and span IDs 64, as the specification asks.
Under `ATOLL_LOG_STABLE` both are counted from 1, every time is `0` — and so,
at its protobuf default, left out — busy and idle are left out, the runtime's
own metrics are not exported, and the resource is `service.name`,
`telemetry.sdk.name` and `telemetry.sdk.language` alone, so an export is a
program's own answer.

### Export never waits

The guest hands a closed span or an event to the host and goes on: batching,
encoding and sending happen on a host thread, off the guest's path, and a
collector that is slow or down costs the program nothing. A full queue drops
the newest, counts them, and says so once at exit —
`atoll: 12 spans were dropped: the export queue was full`. At exit the queue is
flushed, waiting at most `OTEL_BSP_EXPORT_TIMEOUT`.

`file` writes what `console` would, one request a line, to
`ATOLL_OTEL_FILE` — the JSON Lines OpenTelemetry's file exporter writes,
which a collector's `otlpjsonfile` receiver reads back. Every signal set to
`file` shares the file, each line saying which it is by its first key. A file
that would grow past `ATOLL_OTEL_FILE_MAX_BYTES` is renamed `<file>.1`, the
older ones moved on to `<file>.2` and so on, at most
`ATOLL_OTEL_FILE_BACKUPS` of them kept, and a new one begun; a run appends to
the file it finds.

`console` writes each batch as one line of OTLP/JSON — an
`ExportTraceServiceRequest`, `ExportLogsServiceRequest` or
`ExportMetricsServiceRequest`, its fields in the
order the protocol declares them, a field at its protobuf default left out — to
standard error. It is for seeing what would be sent, and under
`ATOLL_LOG_STABLE` everything is one batch per signal, written at exit, spans
in the order they closed.

### Context and propagation

`trace.Context` is a span's place in a trace, as W3C Trace Context writes it:

```atoll
import trace

@trace(parent(ctx))
fn handle(ctx trace.Context, path string) string {
    here := trace.current() ?? ctx
    return here.header()
}

fn main() void {
    incoming := "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
    match trace.Context.parse(incoming) {
        Some(ctx) => println(handle(ctx, "/users"))
        None => println("not a traceparent")
    }
}
```

`trace.Context.parse(header)` reads a `traceparent`, `ctx.header()` writes one,
`ctx.trace_id` and `ctx.span_id` are its hex, `ctx.sampled` its flag, and
`trace.current()` is the current span's context, `None` outside every span. A
span continued from a context is in that context's trace, a child of its span.

`ctx.with_state(header)` is the context with the `tracestate` header sent
beside its `traceparent`, and `ctx.state` is that header: the entries vendors
keep in a trace, `rojo=00f067aa0ba902b7,congo=t61rcWkgMzE`. A span continued
from it carries the state on, and so does every span inside it and every
request they send, when the W3C's grammar takes it — at most 32 `key=value`
members, each key once, the spaces and empty members between them dropped. A
state it refuses is dropped whole, as the specification says.

The `http` module does this itself. Its server runs each request in a span of
kind `server`, named `<METHOD> <route>` — `GET /users/{id}`, or `GET` for a
request no route matched — continued from the request's `traceparent` and
`tracestate`, with the HTTP semantic conventions' attributes
`http.request.method`, `url.path`, `http.route` and
`http.response.status_code`. The span opens when the request is taken, so the
handler is in it, and closes when its answer is whole; a `5xx`, an answer
abandoned, and a request never answered are errors, a `4xx` is the client's.
Its client makes each request a `client` span named by its method, with
`url.full` (credentials and signing query values written `REDACTED`),
`server.address`, `server.port` and the status, failed for a `4xx`, a `5xx` or
no answer; the request carries that span's context as `traceparent` and
`tracestate`, or the calling task's span's when `http`'s own spans are off,
unless the program set a `traceparent` itself. The client span lasts until the
response's head arrives, or an upload's until it is answered. `http`'s spans
are at `info` under the module `http`, so `ATOLL_LOG=info` or `http=info`
turns them on, and the context is sent only while an exporter gives spans
their ids. A message over another transport carries `trace.current()`'s
header and `state`, and is continued with `@trace(parent(ctx))`.

## What it costs

The bar is the one every other part of Atoll is held to at `-O2`.

- **A callsite that is off** is a static record in the module's data — level,
  module, name, file, line, field names — and an interest byte the host sets.
  The check is a load and a branch; the arguments are behind it. The host
  changes interest only at the scheduler's polls, so between polls the byte is
  invariant: a loop with no poll in it reads it once and is unswitched on it,
  and costs what the loop without the event costs. Built: the check is two
  loads, two `and`s and a compare written in place, with no call, and a loop
  that does not suspend is copied once and the word asked before it, so the
  copy that runs while the level is off has no check and no call in it. The
  `benchmarks/trace` row holds it: a hot loop with a disabled `debug` in it
  is within 6% of the loop without, the rest a register the copy that calls
  keeps on the stack for both.
- **A ceiling the build sets** removes callsites entirely: `[trace] max =
  "info"` in `atoll.toml`, or `atoll build --trace-max info`, compiles every
  `debug` and `trace` callsite to nothing. They are still type-checked.
- **Tracing adds no effect.** Emitting is a host call that does not suspend,
  cannot fail, and allocates nothing in the program's memory — the event is
  written into a buffer the runtime gives each task once — so a function's
  inferred effects are the same with an event in it as without, and so is how
  it compiles. `println` is the precedent: a call that carries no effect.
  The one difference is a closure whose body logs: it holds the span it was
  made in, one word. Until a span has been open in the run it is made with a
  load, a mask and a branch more and called with a compare, and asks the
  host nothing.
- **An event that is on** is one host call carrying its callsite and its
  values. A number, a float and a `bool` go as themselves; any other value is
  written as its text in the guest first, borrowed from where it is, so the
  event moves nothing. The host renders the line into the output queue and
  returns; the system call is the writer thread's. **A span that is on** is a host call when it opens and
  one when it closes.
- **A capture** has every callsite ask the host until it ends, and the host
  answers tasks outside it as before.
- **A measurement is no host call.** `add` on a series is a load, an add and a
  store into a table the runtime owns, not the program, so it adds no effect.
  Calling an instrument hashes its attributes and probes its table, inserting
  a series the first time; a call whose attributes are all literals, of an
  instrument any module declares, does that once and finds the series again
  with two loads (`requests("/users", 200).add(1)` is 35 instructions), and a
  series kept in a local is an add each time.
  A histogram's `record` finds its bucket in at most four compares over the
  default bounds. Collection is a copy at a poll; encoding and sending are the
  host's, on its own thread. Built: a series is the address of its cells,
  which the runtime reserves outside the program's heap, so no leak gate
  counts them, and the `benchmarks/metric` row holds a counter kept in a local
  and added to in a hot loop to the same loop adding into a local — the same
  cycles a turn, and 1.09x the instructions, the load and store a turn the
  local does not make. Calling an instrument finds a series named before
  with no call and no allocation: the runtime keeps a table of series, the
  program hashes the attributes, probes the table and compares the key a
  slot holds, and only a series named the first time, or one past its
  instrument's limit, asks the runtime. `benchmarks/metric` `named` names one
  of eight series by a route and a status each turn: 218 instructions a
  turn, and 87 for one integer. An instrument with no attributes is found in
  an entry of the table's header its address picks, two loads: 21
  instructions a turn, against 15 for a series kept in a local. A naming whose
  attributes are all constants still probes.

## Refusals

Each lands with its code and a corpus program.

- A parameter `@trace` cannot record — one with no text, a function value, a
  task — and that `skip` does not leave out. The help is the `skip`.
- `skip(x)` or `parent(x)` naming no parameter; `parent(x)` naming one that is
  not a `trace.Context` or `trace.Context?`.
- `@trace` on a function with no body, a `@host` declaration.
- A message that is not a literal or a template.
- A record field with the name of a template field.
- `@metric` on a function with a body, or returning something that is not an
  instrument; an attribute parameter of another type than `bool`, an integer,
  `string` or an enum whose variants carry nothing; a `string` attribute taken
  by value.
- A counter's `add` with a negative literal; a `time.Duration` instrument whose
  unit is not one of time; bucket bounds that do not ascend; two instruments of
  one module exported under one name.

## Names

The modules are `trace` and `metric`, and the decorators `@trace` and
`@metric`. The compiler's own record of how it decided what it did is
**explain** — `atoll explain`, the `atoll-explain` crate, `.explainbin` files
and the explain app — and a trap's whole stack, the standard library's frames
too, is `ATOLL_BACKTRACE=full`, so that "trace" means one thing.

## Not in the first version

- **A span over a block.** `@trace` covers a function, and a function is where
  a span's name comes from. A closure passed to a function would change what
  `return` and `?` mean inside it, so a block span, if real code asks for one,
  is a form of the language rather than a library call.
- **A subscriber written in Atoll.** The host's subscribers and `capture` cover
  writing, exporting and testing; a user subscriber is dynamic dispatch on
  every event, and waits for a use that needs it.
- **Observed instruments**, whose value a function computes at each
  collection. One needs state that outlives the calls that change it, and a
  `Gauge` set where that state changes says the same; the runtime's own
  metrics are observed, by the runtime.
- **Baggage**, and per-subscriber filters.

## Holding it

Each program held its part in the quarantine (`corpus/ledger/quarantine.txt`)
until the part landed; none is there now:

| Program in `corpus/stdlib/` | Holds |
| --- | --- |
| `an_event_is_written_at_its_level` | levels, the filter, the text line |
| `a_template_part_that_names_a_value_is_a_field` | template fields, record fields, the JSON line |
| `an_event_turned_off_does_not_evaluate_its_arguments` | lazy arguments |
| `a_traced_function_is_a_span_with_its_arguments` | `@trace`, nested spans in the text line |
| `a_skipped_parameter_is_not_recorded` | `skip` |
| `a_span_turned_off_is_left_out_of_the_stack` | a span's level |
| `a_span_closes_on_every_way_out` | `capture`, closing on `?` and `error`, *failed* |
| `a_returned_value_is_recorded_with_ret` | `ret` |
| `a_span_follows_its_task_across_a_suspension` | spans across `yield_now` and `spawn` |
| `a_callback_logs_in_the_span_it_was_made_in` | a closure's span, through calls, a `return`, a spawn and after the span closed |
| `a_trap_says_the_spans_it_stopped_in` | the trap's span line |
| `a_traceparent_is_read_and_continued` | `trace.Context`, `parent`, `current` |
| `otlp_console_export_is_each_span_as_otlp_json` | the OTLP mapping, the console exporter |
| `otlp_export_says_a_span_failed_or_was_cancelled` | a failed and a cancelled span in OTLP |
| `otlp_export_keeps_a_continued_trace_and_its_kind` | `parent` and `kind` in OTLP, a context not sampled |
| `otlp_export_says_what_http_served` | `http`'s server spans, continued from `traceparent` and `tracestate` |
| `a_run_that_traps_exports_what_it_left` | a trap's spans and series, exported |
| `a_counter_counts_by_its_attributes` | `@metric`, series, a kept series |
| `a_histogram_keeps_count_sum_min_and_max` | `Histogram` |
| `a_gauge_keeps_its_last_value_and_an_updown_its_sum` | `Gauge`, `UpDown` |
| `a_counter_added_a_negative_amount_traps` | a counter only goes up |
| `otlp_console_export_writes_each_metric` | the OTLP metrics mapping, the default buckets |
| `otlp_export_writes_an_exponential_histogram_and_its_exemplars` | `exponential`, exemplars, `trace_based` |
| `a_span_writes_a_line_as_it_closes_under_log_spans` | `ATOLL_LOG_SPANS=close` |
| `a_run_that_fails_writes_what_its_flight_recorder_kept` | the flight recorder |

Source: https://docs.atoll.workreef.dev/language/standard-library/tracing/index.mdx
