<!-- https://tinyactors.dev/guides/telemetry/ -->
# Telemetry

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Export each step an actor takes as an OpenTelemetry span, with its logs and metrics, as OTLP bytes your code sends to a collector.

Each step an actor takes becomes a span with its event and the states it left and entered, in the caller's trace when it passes one. Your code sends the OTLP bytes to the collector it chooses.

<a id="overview"></a>

## Decide where the OTLP bytes go

The host writes OTLP requests, the protobuf bytes a collector takes at `/v1/traces`, `/v1/logs` and `/v1/metrics`. Your code posts them where it chooses, and retries when it must ([operating a host](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#operating-a-host)).

A step's span holds the event, the transitions, and the states left and entered. Each `<log>` and failed action becomes a log record, and the host's counters become metrics.

Turning telemetry on changes nothing an actor does. [Telemetry: every step is a span](https://tinyactors.dev/telemetry/index.md) runs a traced payment in your browser and shows its spans.

<a id="turning-it-on"></a>

## Export spans to your collector

A `telemetry` map in the config makes the host write OTLP. A `telemetry` handler in the options gets each request it writes as a `Buffer`, with its signal, `'traces'` or `'logs'`.

This order continues a caller's trace, and its spans come back with the caller's span as their parent:

```javascript title="export.mjs"
import { compileCharts, decodeTraces, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'order.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="open">
  <state id="open">
    <transition event="pay" target="paid"><log label="order" expr="'paid'"/></transition>
  </state>
  <final id="paid"/>
</scxml>` }]);

const requests = [];
const clock = new SimulatedClock();
const host = new Host(compiled, {
  system: 'shop',
  config: {
    system: { ticksPerSecond: 1000 },                                        // the host's clock in milliseconds
    telemetry: { flushInterval: 1000, resource: { 'service.name': 'shop' } }, // a request at most a second after its first record
  },
  clock,
  telemetry: (signal, data) => {
    // A real exporter posts the bytes, from a promise so the host goes on:
    // fetch(`${collector}/v1/${signal}`, { method: 'POST', headers: { 'content-type': 'application/x-protobuf' }, body: data })
    requests.push([signal, data]);
  },
});
compiled.close();

const caller = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'; // a W3C traceparent, from an HTTP header
host.spawn('order').send('pay', undefined, { traceparent: caller });
await host.idle();
console.log('requests before the flush interval:', requests.length);
clock.increment(1000);
await host.idle();
console.log('signals:', requests.map(([signal]) => signal).sort().join(', '));

// Read the spans back (for a test; a collector does this for you).
for (const [signal, data] of requests) {
  if (signal !== 'traces') continue;
  const spans = decodeTraces(data);
  const ours = spans.filter((span) => span.trace === '0af7651916cd43dd8448eb211c80319c');
  console.log('spans in the caller\'s trace:', ours.map((span) => span.name).sort().join(', '));
  const step = ours.find((span) => span.name === 'scxml.macrostep pay');
  console.log('the step\'s parent is the caller\'s span:', step.parent === 'b7ad6b7169203331');
}
host.close();
```

```text title="output"
requests before the flush interval: 0
signals: logs, traces
spans in the caller's trace: scxml.destroyed, scxml.finished, scxml.macrostep pay, scxml.microstep pay
the step's parent is the caller's span: true
```

The handler runs in the host's turn, so start the post there and return without waiting for the collector. `decodeTraces` reads an export without a host ([Wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format)).

A handler's error is the turn's ([Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)). The request it failed to send is not offered again, so retrying is the exporter's job.

<a id="the-encoders-options"></a>

## Choose how soon records are sent

Every key of the config's `telemetry` map is optional, and `flushInterval` decides how soon a request is ready:

| Key | Default | What it does |
|---|---|---|
| `flushInterval` | 0 | a request is ready this long after its first record, in the host's clock ticks (`system.ticksPerSecond`); 0 means only when the staging is full, or at close |
| `resource` | none | attributes on every request, such as `service.name` (at most 32, text to text) |
| `logs` | `true` | `<log>` lines and failed actions as log records |
| `values` | `false` | event data and assigned values in the spans; they may hold personal data, so turn this on knowingly |
| `linkParents` | `false` | an actor's step is a root span linked to its cause, instead of its child |
| `stagingBytes` | 1048576 | the encoder's staging memory |

The host's clock runs at `system.ticksPerSecond`, a billion by default, so a `flushInterval` of 5000 is five microseconds. Most programs that export set `ticksPerSecond: 1000` and give the interval in milliseconds.

<a id="flush-in-tests"></a>

## Step a test's clock past the flush

Once records wait to be sent, the flush is one of the host's deadlines. `host.nextDeadline` reads it even when no actor has a delayed send left.

The host arms its timer for it, which keeps the process alive until then. A test that asserts no timer is left steps its clock past the flush first:

```javascript title="flush.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'job.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" name="job">
  <final id="done"/>
</scxml>` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, {
  system: 'shop',
  config: { system: { ticksPerSecond: 1000 }, telemetry: { flushInterval: 1000 } },
  clock,
  telemetry: (signal) => console.log(signal, 'at', clock.now),
});
compiled.close();
host.spawn('job');
await host.idle();
console.log('the job ended; nextDeadline', host.nextDeadline);
clock.increment(host.nextDeadline ?? 0);
await host.idle();
console.log('flushed; nextDeadline', host.nextDeadline);
host.close();
```

```text title="output"
the job ended; nextDeadline 1000
traces at 1000
logs at 1000
flushed; nextDeadline undefined
```

<a id="metrics-and-close"></a>

## Read metrics on your own schedule

`host.metrics()` returns the metrics request for the host's counters now, a `Buffer` for `/v1/metrics`. On a host without `telemetry` in its config it throws `TA_ERROR_STATE`.

<a id="close-to-flush"></a>

## Close the host to send the last spans

At `host.close()` every open span ends, marked incomplete, and the handler gets the last requests before the host is freed.

`await host[Symbol.asyncDispose]()` also awaits a promise the handler returns there. A host the garbage collector frees without `close()` sends none of it: close the hosts whose telemetry you want.

<a id="trace-context"></a>

## Continue a trace across requests

An input continues the trace a W3C `traceparent` header's text names, and text that does not parse starts a new trace. Pass it as an option:

- `actor.send(event, data, { traceparent })`
- `host.send(actor, event, data, { traceparent })`
- `host.spawn(chart, { traceparent })`

A send's `traceparent` is the sending step's context: put it in the header of your request for that send. This handler reads the trace its request would carry:

```javascript title="propagate.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="c" initial="s">
  <state id="s">
    <transition event="go"><send type="urn:example:api" event="call"/></transition>
  </state>
</scxml>` }]);
const host = new Host(compiled, {
  system: 'demo',
  ioProcessors: {
    'urn:example:api': {
      receive(send) {
        const [, trace] = send.traceparent.split('-');
        console.log('the outgoing request continues trace', trace);
        // fetch(url, { headers: { traceparent: send.traceparent } })
      },
    },
  },
});
compiled.close();
host.spawn('c').send('go', undefined, {
  traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
});
await host.idle();
host.close();
```

```text title="output"
the outgoing request continues trace 4bf92f3577b34da6a3ce929d0e0e4736
```

`send.answer()` continues the send's trace unless given another, and `null` starts a new one.

Tracing is on by default (`system.tracing`), with or without `telemetry` in the config, so trace context flows when nothing is exported.

<a id="trace-ids"></a>

## Seed trace IDs to repeat a test's traces

A trace the host starts takes its ID from a generator seeded by `system.traceSeed`. With none in the config, the package draws a random seed for each new host (`crypto.getRandomValues`).

So two processes, or one process and its restart, do not collide at the collector. The same seed gives the same IDs, which reproduces a test's traces:

```javascript title="seed.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="c" initial="s">
  <state id="s"><onentry><send type="urn:example:api" event="call"/></onentry></state>
</scxml>` }]);
const image = compiled.image;
compiled.close();

const firstTrace = async (system) => {
  let trace;
  const host = new Host(image, {
    system: 'demo',
    config: { system },
    ioProcessors: { 'urn:example:api': { receive: (send) => { trace = send.traceparent.split('-')[1]; } } },
  });
  host.spawn('c');
  await host.idle();
  host.close();
  return trace;
};

console.log('no seed, twice:', (await firstTrace({})) === (await firstTrace({})));
console.log('seed 7, twice:', (await firstTrace({ traceSeed: 7 })) === (await firstTrace({ traceSeed: 7 })));
```

```text title="output"
no seed, twice: false
seed 7, twice: true
```

A host made with `Host.restore` keeps the snapshot's generators, so its IDs go on from where the snapshot left them.

<a id="choosing-what-is-traced"></a>

## Change what is traced while the host runs

Call these methods on the host to change what it records while it runs ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)):

- **`traceConfigure(params)`**: sets what every actor traces: `detail` (`'summary'`, `'decisions'`, `'full'` or `'off'`), `values`, `sample` (the share of new traces sampled, 0 to 1) and `rules`. It replaces the previous configuration.
- **`traceWatch({ rules, seconds })`**: adds rules in front of the configured ones for a while (900 seconds by default) and answers `{ id }`. A watch is how an operator looks closely at one chart or one actor without tracing everything.
- **`traceUnwatch({ id })`**: ends a watch early.
- **`traceEnd()`**: ends every open span now, as `close()` does.
- **`traceSpansDecode({ traces })`**: reads the spans of a traces request back through the host. `decodeTraces(bytes)` needs no host, and also gives each span's `flags`, `links`, `resource` and `scope`.

A rule picks the steps it applies to, then says how to trace them:

- **What it matches**: `chart`, `actor` (a trailing `*` makes it a prefix), `event` (SCXML's prefix rule), `session` or `from`, which is `'host'`, `'actor'`, `'timer'`, `'spawn'` and so on.
- **What it decides**: `sample` (`'keep'`, `'sample'`, `'drop'` or a share) and `detail`, at most `perSecond` with a `burst`.

This host samples 1 trace in 100 in summary, then traces every checkout in full for a minute:

```javascript title="watch.mjs"
import { Host } from '@tinyactors/node';

const host = new Host([], { system: 'shop', config: { telemetry: {} } });
await host.traceConfigure({ detail: 'summary', sample: 0.01 });
console.log('1 trace in 100, summarized');
const watch = await host.traceWatch({ rules: [{ chart: 'checkout', sample: 'keep', detail: 'full' }], seconds: 60 });
console.log(`watch ${watch.id}: every checkout in full for a minute`);
host.close();
```

```text title="output"
1 trace in 100, summarized
watch 1: every checkout in full for a minute
```
