iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / docs / telemetry.mdmain at 949894f

# Telemetry

A mind reads its own telemetry with one call: `await itx.telemetry.query(sql, { hours })`. It
answers `{ rows, sql, dataset?, truncated?, notice? }`: at most 1,000 rows, and the SQL
that ran. `truncated: true` says that 1,000 rows came back and more may match: aggregate, or page
with `LIMIT` and `OFFSET`.

The query reads one of two stores. The FROM decides which (`isTelemetryDatasetQuery`,
`core/lib/src/api.ts`).

## Cloudflare's own datasets: no token

Cloudflare keeps every Worker's logs, spans, invocations and errors, and the stack's metrics. The
Telemetry Worker reads them through its Analytics SQL binding (`ANALYTICS`), which needs no API
token, in every telemetry mode. Write Cloudflare's own SQL with Cloudflare's own names, as
[Cloudflare's docs](https://developers.cloudflare.com/analytics/sql-api/) write it:

| Dataset                     | What it holds                         | Worker column | Time column | `hours` at most |
| --------------------------- | ------------------------------------- | ------------- | ----------- | --------------- |
| `logs.workersLogs`          | every log line and invocation log     | `scriptName`  | `timestamp` | 168             |
| `logs.traces`               | every span (OpenTelemetry)            | `serviceName` | `startTime` | 168             |
| `logs.issues`               | every error, unsampled                | `scriptName`  | `timestamp` | 168             |
| `events.workersInvocations` | every invocation, with CPU and status | `scriptName`  | `timestamp` | 768             |
| `metrics`                   | the stack's own Analytics Engine data | —             | `timestamp` | 768             |

`hours` is 24 by default. Cloudflare keeps the logs 7 days and the other two 90 days, but one query
reads at most 32 days (2,764,800 seconds). The columns of each dataset:
`https://api.cloudflare.com/client/v4/analytics/sql/introspection?dataset_name=<dataset>&include_columns=true`.

**Whose rows.** The account holds other Workers too. A query reads the rows of the Workers of
the mind's own stack, and of no other Worker. Of the logs, issues and invocations it reads every
Worker of the stack (`workerNamesWhoseLogsQueriesRead`: mind, boundary, auth, secrets and
telemetry). So a mind's agent reads every log line of its auth and secrets Workers: those Workers
log paths, verbs, outcomes and ids, and must never log a secret's value or a token. Of the spans
(`logs.traces`) it reads the mind Worker's and the boundary Worker's alone
(`workerNamesThatQueriesReadWhole`): a span of the vault's outbound fetch can hold a secret's
value, in a URL or a header.
`metrics` is the stack's own dataset, all of it. The Telemetry Worker puts the cut into the
caller's text (`core/telemetry-worker/src/store-query.ts`):

```sql
WHERE (scriptName IN ($itx_worker_0, $itx_worker_1, …) AND timestamp >= $itx_since) AND (<your WHERE>)
```

With no WHERE of yours, the right side is `(TRUE)`, so the shape is always one. An `OR` in your
WHERE, a `GROUP BY` or a `HAVING` cannot undo it. The text that is sent, the physical name of
`metrics` in it, is parsed again to prove that the WHERE is one AND, its left side exactly the cut,
its right side exactly your WHERE as parsed from your SQL, over the one dataset, with a LIMIT of at
most 1,000. Anything else is refused. A row cap of `LIMIT 1000` goes on the end. An answer over
8 MiB of JSON is refused: select fewer columns or rows.

**The dialect.** One SELECT over one dataset. No JOIN, UNION, subquery, derived table, CTE or
window function, no comment, `;`, backslash, backtick or `$`. No alias may take the name of the
cut's columns. Column names are case-sensitive (`scriptName`); never alias a column `message`.
**Sampling.** Each row carries `sampleInterval`: the rows it stands for. How to count depends on
where the dataset samples. Measured on 22 Nov 2026, each an exact read against a sampled read of
the same hours:

- `logs.workersLogs` and `logs.traces` sample when they are read (a 24-hour read of the logs took
  1 row in 10, `sampleInterval` 10). `count()` is already weighted: 5,700 against the exact
  5,538 log lines, 34,790 against the exact 35,581 spans. `sum(sampleInterval)` counts each row
  again (57,000; 347,900): never use it there. Count with `count()`.
- `metrics` (Analytics Engine) and `events.workersInvocations` sample when they are written.
  `count()` counts the rows that were kept, not weighted: 2,253 points of `metrics`, where
  `sum(sampleInterval)` is 9,131; 1,328 rows of invocations, where `sum(sampleInterval)` is 6,702.
  Count with `sum(sampleInterval)`, total with `sum(x * sampleInterval)`. For invocations, whether
  `sum(sampleInterval)` is the exact count is not settled: the log read of the same hour counted
  5,232 invocations of the same Workers, which are not the same invocations.
- `logs.issues`: not measured. Cloudflare's docs say it is not sampled.

`quantileWeighted(0.95, x, sampleInterval)` takes a percentile; its weighting was not measured
against an exact read. A sampled dataset refuses `max()` and `min()` (use
`APPROX_MAX` and `APPROX_MIN`) and `COUNT(DISTINCT)`. There is no regex, no `path()` and no
`splitByChar()`. A time is compared as an ISO text (`timestamp >= '2026-11-22T13:00:00Z'`) or
as `NOW() - INTERVAL '10' MINUTE`; `toDateTime('…')` is refused (measured 22 Nov 2026). Booleans come back as 0 and 1. `attributes['k'] <> ''` keeps the rows that have
the key; `IS NULL` on one is refused. Every row of the logs carries the full URL with its query
string, in `url`, `message` and `error`.

**Errors.** Cloudflare's own words never come back and are never logged: they could name what the
cut keeps out. A refused query throws `INVALID_INPUT` with a fixed sentence: `MAX` or `MIN` on a
sampled dataset (use `APPROX_MAX` or `APPROX_MIN`), a column that the dataset does not have, a
function that Analytics SQL does not support, a time range over what one query reads, or a
subquery. Any other refusal says "refused the query", with Cloudflare's numeric code when it has
one. A failure that may pass when asked again keeps workerd's `retryable` stamp.

**Approval.** `itx.telemetry.query` is the platform's alone, under that one name: no rule of the
template points it away, so an approval rule that names it holds every call of that name.

### Eight examples

Each ran on 22 Nov 2026 through the Telemetry Worker's own rewrite.

What went wrong, by kind (`level` is `error`, `warn` or `info`; `error` is often empty):

```ts
await itx.telemetry.query(
  "SELECT level, substring(message, 1, 80) AS kind, count() AS times FROM logs.workersLogs WHERE level IN ('error', 'warn') OR error <> '' GROUP BY level, kind ORDER BY times DESC LIMIT 20",
  { hours: 1 },
);
```

The slowest spans, with a p95:

```ts
await itx.telemetry.query(
  "SELECT serviceName, spanName, count() AS spans, quantileWeighted(0.95, durationMs, sampleInterval) AS p95_ms FROM logs.traces GROUP BY serviceName, spanName HAVING count() >= 10 ORDER BY p95_ms DESC LIMIT 10",
  { hours: 1 },
);
```

Requests by path and status (a request's log has `logType = 'cf-worker-event'`):

```ts
await itx.telemetry.query(
  "SELECT CASE WHEN position(url, '?') > 0 THEN substring(url, 1, position(url, '?') - 1) ELSE url END AS route, httpStatus, count() AS requests FROM logs.workersLogs WHERE invocationType = 'fetch' AND logType = 'cf-worker-event' GROUP BY route, httpStatus ORDER BY requests DESC LIMIT 20",
  { hours: 1 },
);
```

What one trace did:

```ts
await itx.telemetry.query(
  "SELECT startTime, serviceName, spanName, spanId, parentSpanId, durationMs, spanStatus FROM logs.traces WHERE traceId = '<traceId>' ORDER BY startTime",
);
```

Invocations by Worker and status:

```ts
await itx.telemetry.query(
  "SELECT scriptName, status, sum(sampleInterval) AS invocations, quantileWeighted(0.95, cpuTimeUs, sampleInterval) AS p95_cpu_us FROM events.workersInvocations GROUP BY scriptName, status ORDER BY invocations DESC",
  { hours: 1 },
);
```

The mind's own metrics (`core/itx/src/metrics.ts` writes them):

```ts
await itx.telemetry.query(
  "SELECT blob1 AS name, sum(sampleInterval) AS points, sum(double1 * sampleInterval) AS total FROM metrics GROUP BY name ORDER BY points DESC",
);
```

**The mind's events.** For each batch of events that a context commits, the Telemetry Worker
writes one `event.committed` point to `metrics` for each context path and event type
(`core/telemetry-worker/src/event-points.ts`): `blob2` is the path, `blob3` the type, `double1` the
number of events and `double2` the bytes of their payloads as JSON. A call writes at most 200
points. Past that, the quietest types of a path fold into one point with the type `(other)`. Add
events with `sum(double1 * sampleInterval)`: Analytics Engine keeps a sample of the points, each
kept point stands for `sampleInterval` of them, and `count()` counts the points that were kept. The
two examples ran on 22 Nov 2026 on the kernel's `subscription.delivered` points, whose blobs and
doubles have the same positions.

Events an hour, by type:

```ts
await itx.telemetry.query(
  "SELECT toStartOfHour(timestamp) AS hour, blob3 AS type, sum(double1 * sampleInterval) AS events, sum(double2 * sampleInterval) AS bytes FROM metrics WHERE blob1 = 'event.committed' GROUP BY hour, type ORDER BY hour DESC, events DESC",
  { hours: 24 },
);
```

The busiest context paths of the day:

```ts
await itx.telemetry.query(
  "SELECT blob2 AS path, sum(double1 * sampleInterval) AS events FROM metrics WHERE blob1 = 'event.committed' GROUP BY path ORDER BY events DESC LIMIT 20",
  { hours: 24 },
);
```

## The telemetry tables: with a token

`events`, `logs` and `spans` are R2 SQL tables that the stack's streams fill: the mind's own events,
and the logs and spans that Cloudflare's OpenTelemetry export posts to the Telemetry Worker
(`core/telemetry-worker/src/query.ts`, at most 720 hours). Only a stack whose deploy made them
with a telemetry token has them (telemetry mode `minted` or `given`, `core/alchemy/README.md`). A
stack in mode `off`, which is every stack that a deploy makes now, has no tables, no stream and
no export: a query over the tables answers `{ rows: [], sql, notice }`, and the notice names
Cloudflare's own datasets, which every mind reads with no token. Its events are still counted in
`metrics`.

Until 25 Nov 2026 a mind could turn its tables on with a member's token. Such a mind can no longer
read its tables: `itx.config.telemetryQuery` and `itx.telemetry.cut` are gone, and
`itx.telemetry.query` answers the notice. The template's publish hook still removes the rewrite
rule `itx.telemetry.query ⇒ itx.config.telemetryQuery` that such a mind may hold
(`core/configs/default/telemetry-query-rule.ts`), and the stack's next deploy removes the tables
it made, with their streams and bucket (`core/alchemy/src/mind-made-telemetry-tables.ts`).

Neither removes the token. A member does two things:

1. Delete the vault entry: `await itx.secrets.delete("/secrets/cloudflare-telemetry")`. The mind's
   code can then no longer send the token. The token itself stays valid.
2. Delete the token in Cloudflare, on the account's API tokens page (it was named
   "iterate telemetry", unless the member renamed it). This revokes it. The sinks keep their own
   copy of the token, so their writes into the tables stop then.