iterate.com / kernel

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

docs: the two guides that the kernel's code names are in this repo

Moved from iterate/private (archived, tip 0070b51df). They may need
small changes for their new home.

Tests: none
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Jonas Templestein, 2026-11-27 22:42 UTC · c670a98e76440e265834ca79e61002c54e1db153 · parent 088d957

3 files changed

M README.md
@@ -17,6 +17,11 @@
 | `core/home-lab`         | Runs the mind Worker on your own machine, behind a deployed boundary.                                                                                                   |
 | `core/configs`          | The templates a new mind's config repo starts from. `default/` has its apps (agents, onboarding, and a guestbook as an example of an app for end users).                |
 
+## Guides
+
+- [docs/engineering-invariants.md](docs/engineering-invariants.md): expected outcomes are modeled, and recovery is bounded and observable.
+- [docs/telemetry.md](docs/telemetry.md): how a mind reads its own telemetry.
+
 ## Deploy a mind
 
 - With the wizard at [cloud.iterate.com](https://cloud.iterate.com), which runs the same deploy in your Cloudflare account.
A docs/engineering-invariants.md
@@ -0,0 +1,102 @@
+# Engineering invariant: no deviant system behaviour
+
+We do not accept unexplained, unbounded, or silently tolerated system
+behaviour. An error is either an explicitly modelled and correctly classified
+expected outcome, or it is a product defect. The same rule applies to retry
+storms, stuck work, silent data loss, unexplained latency, state drift, and
+resource leaks.
+
+- Never normalize an error counter merely because it is noisy or longstanding.
+  Classify every contributing outcome, remove expected outcomes from error
+  telemetry, and fix the rest.
+- Never swallow, endlessly retry, or hide failures behind fallbacks or
+  compatibility shims. Recovery must be bounded, observable, and preserve a
+  durable explanation of what happened. A workaround that heals a platform
+  fault logs a warn whose `event` is `<area>.platform-failure-<action>`: the
+  prd fault alarm (`apps/prd-fault-alarm` of the iterate mind's `/repos/config`) pages on bursts of those,
+  on any 5xx a first-party prd Worker answered a visitor, and on errors.
+  Retries follow one policy:
+  [Failures and retries](#failures-and-retries).
+- A workaround for an upstream defect (a library, Cloudflare, a vendor) stays
+  only while a `createFailing` test
+  (`failing-test.ts`, in `packages/shared/src/test-support` of the archived iterate/private) pins the defect, so the pin goes red once upstream fixes it. The
+  exception is a defect too rare to reproduce in a test, such as the held
+  Durable Object alarm ([alarm-coordinator.ts](../core/itx/src/alarm-coordinator.ts)).
+  Its heal's absence from prd is the pin: `PINNED_WORKAROUNDS` in the prd fault
+  alarm posts once after 28 days without it. An upstream defect that only logs
+  an error line, where no call failed, gets no workaround: a `createFailing`
+  test pins it (its upstream issue, where only a deployed runtime shows it), and
+  its entry in the alarm's `PINNED_LINES` says where the line still pages.
+- A healthy request is not enough if it leaves corrupt, stalled, or divergent
+  state behind. Verify the resulting state and the relevant production-shaped
+  telemetry.
+- Green tests are necessary but not sufficient. For operational changes, the
+  acceptance proof includes a deployed stack and evidence that its traces,
+  logs, metrics, and state transitions are coherent, correctly classified, and
+  free of new unexplained errors.
+
+Treat any unexplained error volume as a release blocker until evidence proves
+that each outcome is expected and correctly represented outside the error
+signal. "Unavoidable error spam" is not a category.
+
+## Failures and retries
+
+Every failure is one of five kinds. The hop that first sees it decides the
+kind (`failureKind` in
+[platform-retry.ts](../core/lib/src/platform-retry.ts)), and the kind
+rides on as own properties. capnweb keeps them. Workers RPC can drop them when
+the two sides run different Cloudflare runtime versions, as two contexts can
+during a rollout, so contexts call each other with `invokeSafe`, which returns
+a refusal instead of throwing it
+([iterate-context-durable-object.ts](../core/itx/src/iterate-context-durable-object.ts)).
+
+| Kind           | Recognized by                                                                                                                                                                                                                                                                                                                                     | Repeated                                                                                                                                          | Answered as            |
+| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
+| `refused`      | a `code` from iterate/lib's `ErrorCode`                                                                                                                                                                                                                                                                                                           | never                                                                                                                                             | 4xx or a typed answer  |
+| `deploy-reset` | "reset because its code was updated" (a Durable Object's or D1's)                                                                                                                                                                                                                                                                                 | once, at once, on a fresh stub, if idempotent                                                                                                     | 503, `Retry-After: 1`  |
+| `disconnected` | workerd's `retryable: true`; a storage reset; D1's documented transient errors; an HTTP 5xx or dropped connection; Artifacts 10400, or an Artifacts call left unanswered 20 s (`ARTIFACTS_ANSWER_MS`) while it answers the calls around it; Browser Run 6002 on inline HTML; Cloudflare's own not-found for a workers.dev hostname not routed yet | once at once on a fresh stub (RPC), once a second later (an upstream API), or on a script's schedule (`CI_HTTP`, `CLOUDFLARE_API`), if idempotent | 503, `Retry-After: 1`  |
+| `overloaded`   | workerd's `overloaded: true` (a storage timeout, a memory limit); D1's overload, or workerd's opaque "internal error; reference = …" on a D1 call; HTTP 429 or 408; our own deadline                                                                                                                                                              | never at once: only a durable ladder, or the caller after `Retry-After`                                                                           | 503, `Retry-After: 10` |
+| `failed`       | anything else, our own defects and workerd's opaque internal error on any other call included                                                                                                                                                                                                                                                     | never, except a named workaround with a pin                                                                                                       | 500, and `reportIssue` |
+
+- **Idempotency decides whether a call is repeated; the kind decides when.**
+  Idempotent means a read, an append whose every event is durable and keyed, a
+  `processors.enable`, a GET or HEAD with no body, or a script's call on a
+  method that names its whole end state. A request answered 429 was refused
+  unrun, so a script sends it again whatever its method. `contextStub`
+  ([context-stub.ts](../core/itx/src/context-stub.ts)) applies this to every
+  call the platform makes on a context Durable Object, whichever hop makes it.
+- **Schedules come from one short list**: `ONCE_NOW`, `UPSTREAM_ONCE`,
+  `RELAY_BURST`, `CI_HTTP`, `CLOUDFLARE_API`, the durable ladder (1 s·2ⁿ,
+  capped at 30 minutes), and the socket re-dial
+  ([redial.ts](../core/itx/src/context/redial.ts): at once, then 250 ms doubling
+  to 8 s, within the caller's deadline of the drop: 60 s for a lent stub's pager,
+  30 s for a resumable upgrade). Each schedule is bounded, each wait but the
+  re-dial's is jittered, and giving up on an idempotent call is logged once. A
+  platform failure that ends a call that is not idempotent is logged once too
+  (`<area>.platform-failure-not-repeated`): the call is made once, the caller
+  alone can send it again, and a queued call may still run after its caller is
+  gone. A
+  `Retry-After` longer than a wait replaces it, up to the schedule's longest
+  wait. A script's HTTP call goes through `fetchRetryingPlatformFailures`, whose
+  attempt that gets no answer in time is our own deadline, an overload.
+- **A platform failure that stands crosses a hop as `UNAVAILABLE`**, its
+  `data` `{ kind, retryAfterMs }`, and the edge answers it 503 with that
+  `Retry-After` ([unavailable.ts](../core/itx/src/unavailable.ts)). "Never retry
+  this" is a code (`PERMANENT_FAILURE`, or the refusal's own), never
+  `retryable: false`: workerd never sets it.
+- **One event naming rule, `<module>.<outcome>`.** A deploy's reset is
+  expected: `<area>.deploy-reset-<action>` at info. Any other platform failure
+  is `<area>.platform-failure-<action>` at warn, carrying the `name` the prd
+  fault alarm groups by.
+
+Sources:
+[Cloudflare's Durable Objects error handling](https://developers.cloudflare.com/durable-objects/best-practices/error-handling/)
+(`.retryable` may be retried when idempotent, `.overloaded` "should not be
+retried", a new stub after an exception);
+[capnp's `Exception.Type`](https://github.com/capnproto/capnproto/blob/v2/c%2B%2B/src/capnp/rpc.capnp)
+(OVERLOADED: "should NOT retry again immediately"; DISCONNECTED: rebuild and
+retry);
+[workerd](https://github.com/cloudflare/workerd/blob/main/src/workerd/jsg/util.c%2B%2B)
+(DISCONNECTED is stamped `retryable`, OVERLOADED `overloaded`; a storage
+timeout is thrown OVERLOADED in `io/worker.c++`);
+[D1's error list](https://developers.cloudflare.com/d1/observability/debug-d1/#error-list).
A docs/telemetry.md
@@ -0,0 +1,197 @@
+# 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.