# Analytics

Every event a program sees, kept one by one and asked of later: how many and by what, who came
back, how far people got through a funnel, what they did next, who is new and who has gone quiet.
Two declarations do it, each written like a model, and the usage extension builds a product
analytics tool on them (PostHog's ground: people, funnels, retention, flags, experiments,
dashboards). Back to the [map](README.md); [usage.md](usage.md) is what the runtime gathers.

- **`log Events`**: an append-only, ordered, durable log on the back end, the program's own
  Kafka. Rows go in by the thousand, each gets an offset (0, 1, 2 … with no gaps), and consumers
  (`server on Events(batch)`) each read it in order from their own place, at least once. A door
  (`capture`) takes events from other sites and programs, PostHog's shape included.
- **`fact Event`**: an analytics table, wide and append-mostly, asked by time and grouped. SQLite
  by default, in a file of its own; Postgres where the program's models are
  ([`MOTE_SQL=postgres://…`](back-end.md#models-in-postgres)), the log with it; ClickHouse
  where `MOTE_ANALYTICS` names one. The same
  questions (trends, uniques, percentiles, breakdowns, funnels, retention, paths, stickiness,
  lifecycle, frequency) are written for either.
- **`use "pkg:usage/analytics.mote"`**: the two of them already declared, fed by `usage=on` and
  the door, with people, cohorts, feature flags, experiments, saved insights, dashboards, export,
  webhooks and a panel ([below](#product-analytics)).

```mote
// docs: whole
app "Shop"

// Everything that happened, as it came, for a week. `capture`: POST /capture takes it from outside.
log Events
  plan: string = ""
  keep 7 days
  capture

// The same events, for 400 days, asked by time; and a count of each name each day, kept as they come.
fact Event
  plan: string = ""
  total: number = 0
  rollup daily by name, day count, uniq(who)

// The consumer that moves the log into the store, in batches.
server on Events(batch) as store
  Event.addAll(batch)?

server fn bought(plan: string, total: number) requires signedIn
  let me = auth.me()?
  Events.append({name: "checkout", who: me?.id ?? "", plan, props: {total}})?

server fn report(): json requires signedIn
  let daily = Event.trend({last: "30 days", every: "day", by: "plan"})?
  let funnel = Event.funnel({steps: ["/", "/cart", "checkout"], within: 24})?
  let back = Event.retention({every: "week", periods: 8})?
  return {daily, funnel, back}

text "A shop"
```

## Mental model

A log is for **moving** events: it is written fast, in order, and read in order by whoever needs
them (the store, a webhook, a copy elsewhere), each at its own pace and each again from any point
for as long as the log keeps it. A fact is for **asking**: rows kept by time, in the shape a
question wants, for as long as the questions need them. A program may have either without the
other, several of each, and its own consumers; the extension's is one such program.

Nothing is reached from a page: a log and a fact are the back end's, asked in a `server fn`, a
consumer, a job (`H206`). What a page may know of them is what a `server fn` answers.

## log

```mote
log Clicks
  route: string = ""          // fields beyond the ones every log has
  keep 3 days                 // how long (unsaid: 7 days); `keep 2 GB` for how much; both may be said
  capture                     // the door: POST /capture, keys in MOTE_CAPTURE_KEYS
```

**Fields every log and fact has**, unless it says one itself with the same type (`H213`):
`id: string` (made for each row, 32 hex digits: what a consumer and the store tell rows apart
by), `at: time = now`, `name: string`, `who: string = ""`, `session: string = ""`,
`app: string = ""`, `props: json = {}`. A row read from a log also has its `offset`. A field
holds a text, a number, a yes-or-no, a time or json: a reference to a model is its key
(`order: string`) and a file is kept by a model (`H211`). Nothing else of a model belongs in a
log: rules, `unique`, `check`, `index` (`H201`).

| Operation | |
|---|---|
| `Clicks.append(row)` | One row in. Answers its offset, once it is on the disk. |
| `Clicks.appendAll(rows)` | Rows in, in order, as one write. Answers the last one's offset (`-1` for none). |
| `Clicks.read(offset, max?)` | Rows from that offset on (1000 unsaid, 100 000 at most), each with its `offset`. |
| `Clicks.since(time, max?)` | Rows from the first at or after a moment. |
| `Clicks.last()` | The newest offset, `-1` for an empty log. |
| `Clicks.rewind("store", offset)` | That consumer reads from there next: a replay. |
| `Clicks.stats()` | `{first, last, rows, segments, bytes, waiting, consumers: [{name, offset, lag}]}`. |

### Consumers

```mote
server on Clicks(batch) as copy       // `as` names it; unsaid, it is `main`
  for c in batch
    log(`${c.offset} ${c.name} ${c.who}`)
```

Each consumer keeps its own place, in the log's file. It is handed what is after its place, up to
`MOTE_LOG_BATCH` rows (1000), and its place moves past them when the block returns: **at least
once**. A block that fails is handed the same rows again after 1 second, then 2, 4 … up to 30, and
the failure is a line of the log. So a consumer goes by `id` where a row handed twice matters: a
fact's `addAll` does (a row whose id it has is let go). Consumers are woken by an append in their
own process and look every fifth of a second otherwise. With several processes on one machine,
one at a time reads for each consumer (a lease of 15 seconds, taken again each round); a new
consumer starts at the oldest row the log still has. In a test, each consumer is handed what it
has not seen whenever the test's clock moves ([testing.md](testing.md)).

### How it is kept

Unless its models are in Postgres ([below](#in-postgres)), a log is a SQLite file of its own (`log.sqlite` in the data folder, or `MOTE_LOG_FILE`), not the
program's database: a table for each segment of 100 000 rows (`MOTE_LOG_SEGMENT`), a table of the
segments (first and last offset, first and last time, size), the consumers' places and leases.

- **In order, with no gaps, across processes.** An append takes SQLite's write lock
  (`BEGIN IMMEDIATE`) and gives each row the last offset plus one inside that turn.
- **Durable.** The file is in write-ahead mode with `synchronous = FULL`: an append is answered
  after its turn is on the disk. `MOTE_LOG_SYNC=full` adds `F_FULLFSYNC` on macOS (through the
  drive's own cache); `MOTE_LOG_SYNC=normal` answers sooner and leaves the last moment's appends
  to a power cut (a crash of the process loses nothing either way).
- **Batched.** Appends made in one turn of the event loop are one write: many callers each
  appending one row share the cost of the disk.
- **Bounded.** At most `MOTE_LOG_BUFFER` rows (100 000) wait in memory; an append past that waits
  for room, five seconds at most, then fails with the kind `busy`. The door answers 503.
- **Kept.** Whole segments go once their newest row is older than `keep … days`, or while the log
  is larger than `keep … GB`; never the one being written. Looked at every minute.

### In Postgres

With the program's models in Postgres ([`MOTE_SQL=postgres://…`](back-end.md#models-in-postgres))
and no `MOTE_LOG_FILE`, every log is kept there, and every back end of the program appends to it
and reads it as one log. Nothing in the program changes; everything above holds, across machines.

| Table | Columns |
|---|---|
| `mote_log_rows` | `log`, `"offset"`, `at` (ms), `row` (the row as JSON text): one row a row, the key `(log, "offset")` |
| `mote_log_segments` | `log`, `seg`, `first`, `last`, `"firstAt"`, `"lastAt"`, `rows`, `bytes`: as in the file, a segment being a range of offsets here, not a table |
| `mote_log_readers` | `log`, `name`, `next`, `holder`, `until`: each consumer's place and lease |
| `mote_log_head` | `log`, `last`, `seg`, `segrows`: the last offset given, the segment being written and how many rows it has |

A log's head row is made by its first append, from its segments where it has none (the last
segment's `last`, `seg` and `rows`), so rows and segments copied in from a `log.sqlite` (each
segment table's rows, with their offsets, and the segments' and consumers' rows as they are)
before that are taken up where they end. `mote migrate --to postgres` copies them so, with the
facts ([moving an app](back-end.md#moving-an-app-from-sqlite-to-postgres)): before the first
back end starts on the database, which the move makes sure of.

- **In order, with no gaps, across back ends.** An append is one statement, a function the back
  end makes in the database (`mote_log_append`, PL/pgSQL): it locks the log's row of
  `mote_log_head` (`SELECT … FOR UPDATE`), gives the rows the offsets after its `last`, writes
  them and their segments, and moves `last` on, in the statement's own transaction. The lock is
  held to the commit, and Postgres lets a row's lock go only once its transaction is seen as
  committed, so an append that takes offsets 20–29 waits until the one that took 10–19 is
  committed and visible. A reader that sees 20 therefore sees 10–19: offsets are given in the
  order appends commit, and **no reader ever skips a row that would be committed later** (as it
  would with a sequence, whose numbers are taken in one order and committed in another).
- **Durable** as Postgres's commit is (`synchronous_commit`, on unless the server says
  otherwise): an append is answered once it is committed. `MOTE_LOG_SYNC=normal` makes the
  appends' own commits asynchronous (`SET LOCAL synchronous_commit = off`, a power cut of the
  database's machine may lose its last moment); a back end that crashes loses nothing either way.
- **Batched**: what is appended while a write of the log is under way is the next write, one
  statement of up to 10 000 rows (an `appendAll` is never cut in two). One round trip a batch,
  the lock held only inside the database.
- **Consumers** keep their place and lease in `mote_log_readers`, as in the file: one back end at
  a time reads for a consumer, whichever holds the lease. A consumer is woken by its own back
  end's appends and finds the others' within a fifth of a second.
- **Retention** as in the file: whole segments go (a segment's rows and its row, in one
  statement), never the one being written; each back end looks every minute.
- **Behind a transaction pooler**: each statement stands alone; nothing is kept on a connection.
- **Made** on first use, under the lock the models' schema is made under
  (`pg_advisory_xact_lock`), only where the catalog lacks them.
- An append whose connection breaks before it is answered fails, and may have been kept: a
  consumer that goes by `id` keeps it once.

Why SQLite and not a format of its own: a log in files of its own was measured too (records
framed with a length, a CRC and the offset, synced each batch) and was faster only one row at a
time; at a hundred rows a call and above SQLite was as fast, and it already is the lock between
processes, the recovery after a torn write and the index by time that such files would need.

### The capture door

A log that says `capture` takes events at `POST /capture` (and `/capture/batch`), and at
PostHog's paths `/batch/`, `/e/`, `/i/v0/e/`, so that posthog-js, or any PostHog SDK, may be
pointed at the program (`api_host`). Two shapes:

```text
{"key": "pk_…", "events": [{"name": "signup", "who": "v1", "session": "s1", "at": 1764240000000, "id": "…", "props": {"plan": "pro"}}]}
{"api_key": "pk_…", "batch": [{"event": "$pageview", "distinct_id": "v1", "properties": {"$session_id": "s1", "$set": {"plan": "pro"}}, "timestamp": "2026-11-27T10:00:00Z", "uuid": "…"}]}
```

- **Keys.** `MOTE_CAPTURE_KEYS="site:pk_abc123,planner:pk_def456"`: each key is a project, kept as
  the event's `app` (a key alone is the program's own, `""`). A key is write-only, like PostHog's
  project key: it may sit in a page. A key nobody has: 401.
- **Bodies.** JSON; gzipped (`?compression=gzip-js` or `Content-Encoding: gzip`, as posthog-js
  sends it); `text/plain` (what `sendBeacon` sends, which needs no preflight); a form's
  `data=` of base64. Any origin may post (`Access-Control-Allow-Origin: *`).
- **Limits.** 1 MB a request (`MOTE_CAPTURE_BYTES`), 1000 events, 6000 events a minute a key
  (`MOTE_CAPTURE_RATE`) and 1200 an address (`MOTE_CAPTURE_ADDRESS`); past them 413 or 429. A
  time more than a week old is taken as a week ago, one in the future as now. Properties: 60 at most,
  texts cut at 500 letters, anything else kept as its JSON text, cut; `$set` stays a record.
- **What does not fit is dropped and counted**: `{"status": 1, "ok": 2, "dropped": 1}`.
- **Never an address.** The sender's address bounds how much it may send, in memory, for the
  minute; it is in no row, and a property called `ip` or `$ip` is not kept.
- **A browser that asks not to be tracked** (`Sec-GPC: 1`, `DNT: 1`) is counted for nobody: what
  it did is kept with no `who`, no `session`, and nothing it said of itself (`$set`).

## fact

```mote
fact Sale
  total: number = 0
  country: string = ""
  order country, at           // the order rows are kept in (unsaid: app, name, at)
  partition day               // month (unsaid), day, none
  keep 2 years                // how long (unsaid: 400 days)
  index who                   // another index (SQLite); ClickHouse's order is its index
  rollup monthly by month, country sum(total), max(total) as top, count
```

The same fields every log has, and the program's own. A **rollup** is a table kept as rows come in:
`rollup NAME by DIMENSIONS MEASURES`, where a dimension is a field or a bucket of `at` (`hour`,
`day`, `week`, `month`) and a measure is `count`, `uniq(f)`, `sum(f)`, `min(f)`, `max(f)` or
`avg(f)`, named `count`, `uniqWho`, `sumTotal` … or `… as name`. `Sale.rollup("monthly", {last:
"6 months", where: {country: "DE"}})` reads it, by its own dimensions only.

| Operation | |
|---|---|
| `Sale.add(row)`, `Sale.addAll(rows)` | Rows in (a log's rows as they are: their other fields are let go). A row whose `id` is kept already is let go. Answers how many were new. |
| `Sale.trend(q)` `funnel` `retention` `paths` `stickiness` `lifecycle` `frequency` `people` `rows` | The questions, [below](#questions). |
| `Sale.rollup("name", q?)` | A rollup's rows. |
| `Sale.alias(visitor, person)` | A visitor's id is that person's from now on, and back to its first row. |
| `Sale.forget(who)` | A person's rows go, and their visitors' with them. Answers how many. |
| `Sale.sql("… where who = ?", [who])` | The program's own SQL, in the store's dialect, each value given apart (`H214` for a value written into the text). |
| `Sale.dialect()` | `"sqlite"`, `"postgres"` or `"clickhouse"`. |

### SQLite, unless said

Unless the models are in Postgres ([below](#postgres-where-the-models-are)): `analytics.sqlite` in the data folder (`MOTE_ANALYTICS=sqlite:/some/file` for another): a table a
fact, its `id` the key, an index on its order and on `who, at`; a field added since is a column
more. A rollup is a table kept in the same write as the rows; `uniq` by a table of the values it
has seen. What is older than `keep` goes every hour.

### Postgres, where the models are

With the program's models in Postgres ([`MOTE_SQL=postgres://…`](back-end.md#models-in-postgres))
and `MOTE_ANALYTICS` unset, each fact is a table there, beside the models', in the schema
`MOTE_SQL` reaches: `"Sale"` (as declared, so quoted), its fields as columns (a text `TEXT COLLATE
"C"`, a number `DOUBLE PRECISION`, a whole number and `at` (ms) `BIGINT`, a yes-or-no `BOOLEAN`,
json `JSONB`), `id` the key, an index on its order (`"Sale__order"`), on `who, at` and on `at`;
`"Sale__alias"` (`anon`, `who`); each rollup `"Sale__r_monthly"` (`k`, its dimensions, its
measures, `"…__n"` beside an `avg`) and `"Sale__r_monthly__u"` (`k`, `b`, the values `uniq` has
seen). Made on first use, under the lock the models' schema is made under; a field added since is
a column more. Several back ends add to and ask of the same tables.

- **Rows in** are one transaction: the rows (`ON CONFLICT ("id") DO NOTHING`, so a batch handed
  twice is kept once), then each rollup's counts of the ones that were new, each a statement
  of the whole batch. Two back ends adding to one rollup at once each count their own.
- **The questions** are the same, written in Postgres's SQL: buckets in the zone's own hours
  (summer time and all, as ClickHouse's; SQLite's are shifted by the zone's offset now), a
  percentile `percentile_disc` (SQLite's first value whose share reaches it), a property
  `props -> 'plan'` (`props.a.b` a path). The same rows give the same answers as in SQLite
  (`tests/all.sh real_pg_log` asks 32 questions of both), but: an object of `props` comes back
  with its keys in jsonb's order (shorter first), and a yes-or-no dimension of a rollup as
  `true`/`false` where SQLite has `1`/`0`.
- **`sql`** is Postgres's SQL, `?` for each value (said as `$1`, `$2` …; a `?` inside quotes is
  left), the tables by their names, quoted: `Sale.sql("SELECT count(*) AS n FROM \"Sale\" WHERE
  who = ?", [who])`.
- Text holds no U+0000 there: one is kept as U+FFFF.
- `MOTE_ANALYTICS=sqlite:/some/file` keeps the facts in SQLite all the same, and a ClickHouse
  named there is used whatever `MOTE_SQL` says.

### ClickHouse, where said

```sh
MOTE_ANALYTICS=clickhouse://user:password@host:8123/database      # http
MOTE_ANALYTICS=clickhouses://user:password@host:8443/database     # https
MOTE_ANALYTICS_TIMEOUT=30000                                       # ms a request may take
```

Over ClickHouse's HTTP interface, with nothing but `fetch`: SQL posted, rows sent as
`JSONEachRow`, answers read as `FORMAT JSON`, every value apart as a query parameter
(`{p0:String}`), the user and password as `X-ClickHouse-User` and `X-ClickHouse-Key`. On the
first question each fact is made: `MergeTree`, `ORDER BY` its order, `PARTITION BY toYYYYMM(at)`
(or by day), `TTL toDateTime(at) + INTERVAL 400 DAY`, a column added for each field it lacks; a
rollup is an `AggregatingMergeTree` table and a materialized view that fills it (`countState`,
`uniqState`, `sumState` …); aliases a `ReplacingMergeTree`. A batch is sent with an
`insert_deduplication_token` (a hash of its ids), so a batch a consumer sends twice is kept once.
`at` is `DateTime64(3, 'UTC')`, `name` and `app` `LowCardinality(String)`, `props` its JSON text.

**It has not met a real ClickHouse.** What is tested (`tests/all.sh real_e2d_analytics`) is the
SQL the builder writes and what the runtime makes of answers of the right shape, against a
stand-in for the HTTP interface (`tests/e2d_clickhouse.mjs`); no ClickHouse was installed or
reached. To verify against one:

1. Start one: `docker run -d -p 8123:8123 -e CLICKHOUSE_PASSWORD=pw clickhouse/clickhouse-server`
   (or a ClickHouse Cloud service, with `clickhouses://…:8443`).
2. `CREATE DATABASE shop` in it (`curl 'http://localhost:8123/?user=default&password=pw' -d 'CREATE DATABASE shop'`).
3. Build `tests/e2d_analytics/shop.mote` and run it with
   `MOTE_ANALYTICS=clickhouse://default:pw@localhost:8123/shop MOTE_CAPTURE_KEYS=site:pk_test_site1`.
4. Post events to its door (the curl lines of the door, above), wait a second, and ask through
   its `ask` call each of: a trend by day and by a property, a percentile, a funnel, a retention by
   week, paths, stickiness, lifecycle and frequency; compare each with the same events in a
   SQLite build (`MOTE_ANALYTICS` unset). The demo (`usageDemoSeed`) is a good load: the same
   rows both ways.
5. Look for: the tables and the view made once (`SHOW TABLES`), a batch sent twice kept once
   (`SELECT count() FROM UsageEvents`), the rollup's numbers (`SELECT name, day, countMerge(count)
   FROM UsageEvents__r_daily GROUP BY name, day`), and every question answered without an error.

## Questions

A question is a record. Every one takes a span and a filter:

| Word | |
|---|---|
| `last` | `"today"`, `"24 hours"`, `"30 days"` (unsaid), `"12 weeks"`, `"6 months"`, `"1 year"`, or a number of days; from the start of the first day, in `ANALYTICS_ZONE` (else `USAGE_ZONE`, else UTC). |
| `from`, `to` | Moments instead. |
| `name` | One event's name, or a list of them. |
| `where` | A model's filter of the fields (`{country: "DE", at: after(t), any: [{…}, {…}]}`), and `props: {plan: "pro"}` for properties (a value, or a list of them). |

| Question | Its own words | Each row it answers |
|---|---|---|
| `trend` | `every` (`hour`, `day`, `week`, `month`, `all`), `by` (a field or `"props.plan"`: the 10 most, then `(other)`, `limit` for more), `measure` (`count`, `uniq` people, `sum`, `avg`, `min`, `max`, `p50` `p75` `p90` `p95` `p99`), `of` (the number measured) | `{bucket, by, value}`, every bucket of the span, empty ones as 0 |
| `funnel` | `steps` (2 to 12 names), `within` (hours, 24 unsaid), `by` | `{step, index, by, people, rate, dropped, ms}`: `rate` of those who began, `dropped` since the step before, `ms` the median time from the first step |
| `retention` | `every`, `periods` (8), `start` (the event that puts a person in a cohort: any unsaid), `again` (what counts as coming back) | `{cohort, people, kept, after}`: each cohort's size and how many, and what share, were seen in each period since; periods not yet come are left off |
| `paths` | `start`, `steps` (5), `limit` (20 a step) | `{step, from, to, people}`: in each visit (`session`), what came next |
| `stickiness` | `every` | `{periods, people}`: how many buckets of the span each person came |
| `lifecycle` | `every` | `{bucket, fresh, returning, resurrecting, dormant}` |
| `frequency` | `count`: `days`, `sessions`, `events`, or `recency` | `{times, people}`: 1, 2, 3–5, 6 or more; or today, 1 day, 2–7 days, 8–30 days, 31 or more since last seen |
| `people` | `limit`, `order` (`last`, `first`, `events`) | `{who, first, last, events}` |
| `rows` | `limit`, `order` (`at`, `at desc`) | the rows themselves |

**People.** Every question goes by the person: a visitor's id joined to an account (`alias`) is
that account's, back to its first row. A row counted for nobody (`who` empty: a browser that asked
not to be tracked) is in counts of events, and in no question of people.

What a query may say is checked as it is written: a word the question does not take, a bucket or
a measure that is not one, a field the fact does not have, a percentile with nothing to measure,
a funnel of one step (`H209`, `H210`).

## Product analytics

The usage extension's `analytics.mote` is all of the above, already written:

```mote
app "Shop" usage=on autocapture=on
use "pkg:usage/analytics.mote"

fn usageMay(): bool = (auth.me() else none)?.email == "owner@shop.example"

route "/admin/analytics"
  AnalyticsPanel
```

It declares `log UsageLog` (a week, with the door) and `fact UsageEvents` (400 days, with a daily
rollup of each name's count and people), with the fields of the usage seam (kind, route, path,
title, ms, ok, referrer, country, browser, os, device). Its `server on usage` puts what the
runtime gathered (`usage=on`: screens, actions, `track`, sign-ins, autocapture, as it rides the
open line or the door, [usage.md](usage.md#the-open-line)) into the log, and its consumer moves the
log into the store. `usage.mote`, the counters, is taken with it and keeps working beside it. A
program that keeps other programs' batches ([several apps](usage.md#several-apps-one-panel)) hands
each to `usageTakeEvents(batch, app)` as well as to `usageTake`, and asks with `app=`.

- **People.** A sign-in or sign-up that says the browser's id until then, PostHog's `$identify`
  (`$anon_distinct_id`) and `$create_alias` join a visitor to a person. What is known of a person
  (`UsagePersonProps`): what a client says with `$set`, and the program's
  `usagePersonSet(me.id, {plan: "pro", company: "Acme"})`. `usagePeopleList`, `usagePerson`
  (properties, and what they did, newest first), `usageForget(who)` (their events, what is known
  of them, and usage.mote's rows of them).
- **Cohorts.** `usageCohortSave(name, rule)`: by what people did (`{did: "checkout", within: 30,
  times: 2}`), by what is known of them (`{prop: "plan", is: "pro"}`), or by name (`{people: […]}`).
- **Feature flags** (`features.mote`). `usageFeatureSave(flag, on, rollout, variants, rules)`: on
  or off, or one of several variants by weight, for a share of people, for people who fit its
  rules (a property is, is not, is one of; a cohort). A person's answer is the same every time:
  PostHog's hash (the first 15 hex digits of SHA-1 of `"flag.who"`, over `0xfffffffffffffff`), so
  a person keeps their variant as the rollout grows. The page asks `usageFeatures(seed)`; the back
  end `usageFeature("flag")`, `usageVariant("flag")`. Each answer is an exposure, the event
  `$feature_flag_called` `{flag, variant}`.
- **Experiments.** `usageExperimentSave(name, flag, goal)`, and `usageExperimentReadout(id)`: of
  the people shown each variant (the first each saw), how many then reached the goal; each
  variant's rate, lift on the control (the flag's first variant), the two-sided p-value of a
  two-proportion z-test, and the chance its rate is the higher (Beta posteriors); significant at
  p < 0.05 with 30 people or more in each.
- **Insights and dashboards.** `usageAsk(kind, query, compare)` answers any question for the
  reader, with the span before where `compare`; `usageInsightSave`, `usageInsightPin` (saved and
  put on the first dashboard), `usageBoards`, `usageBoardRun(id, last, compare)`.
- **Export and webhooks.** `usageExport(kind, query, "csv" | "json")`; `usageHookSave(url, names,
  secret)`: each event, as it comes, posted to the address (`{events: […]}`, signed
  `x-mote-signature: sha256=<HMAC of the body>`), by a consumer of its own, so at least once.
- **The demo.** `usageDemo("larder")`: eight weeks of a made-up shop (600 people, about 10 000
  events, a flag and its experiment, cohorts, a dashboard), once, under that app, to see the panel
  with. The playground's Analytics page shows it.

### The panel

`AnalyticsPanel` (or each part alone, with `app=` and `last=`): a span (7, 30, 90 days) and the
span before beside it, then a tab each:

| Part | |
|---|---|
| `AnalyticsTrends` | any event (or all) over time: events, people, or a property summed, averaged, its median or 90th percentile; by country, device, browser, source or plan; against the span before |
| `AnalyticsRetention` | cohorts by the day, week or month people were first seen (or first did an event) against the periods since, as shares, shaded; the average of all cohorts on top, and as a curve |
| `AnalyticsLoyalty` | new, returning and back-after-a-gap people each day or week; how many days and how many visits each came; how long since each last came |
| `AnalyticsEngagement` | stickiness (how many days of the span each came) and lifecycle (new, returning, back, gone quiet below the line) |
| `AnalyticsFunnel` | steps to add and take away, a window, the drop-off and the median time to each step, the rate against the span before, a breakdown |
| `AnalyticsPaths` | step by step, what people did next, from any event |
| `AnalyticsPeople` | the people seen, found by id or property; one person's properties and timeline, day by day; forgetting them |
| `AnalyticsBoards` | the saved insights of a dashboard, each drawn small |
| `AnalyticsFlags` | the flags, and each experiment's readout and verdict |
| `AnalyticsLive` | who is here now (as the pages' open lines say), events each minute of the last half hour, the newest events |

Each part filters by one field or property (`AnalyticsFilter`: country, device, browser, system,
source, plan, to one of the values seen) and saves what it shows as an insight. Each folds to a
phone's width (a grid scrolls inside itself), and follows the app's colours, light and dark.

### Left out on purpose

**Session recording and replay are not here, and will not be**: a recording of a screen holds
whatever was on it (what was typed, what was read), which is more than a program's owner should
keep, and the legal questions of keeping it are not ones the owner of this project wants a
program to inherit. Heatmaps go as far as how often each control was pressed (autocapture's
`click`): no positions are kept.

## What it costs

Measured 2026-11-27 on an Apple M3 Ultra, Bun 1.2.20, the log synced to the disk on each write
(`bench/analytics/run.sh`; the numbers in [bench/README.md](../bench/README.md#analytics)):

| | rows a second |
|---|---|
| `appendAll`, 1 row a call (each waits for its own sync) | 740 |
| `appendAll`, 100 a call | 60 000 |
| `appendAll`, 1000 a call | 245 000 |
| `appendAll`, 10 000 a call | 375 000 |
| `addAll` into the store (SQLite), 1000 a call, no rollup | 62 000 |
| the same with a rollup by name and day of its count and `uniq(who)` | 26 000 |
| the log and its consumer into the store at once, 1000 a call | 18 000 to 28 000 |
| the capture door, 100 events a request, 1 to 32 clients | 8 000 to 24 000 events |

**In Postgres** ([above](#in-postgres)), measured 2026-12-01 on the same machine, Bun 1.4.5,
PostgreSQL 17 on the same machine with `fsync` on (each append's commit waits for the disk), the
back end and the database talking over the loopback (`PG=1 bench/analytics/run.sh`), beside
SQLite measured the same day:

| | Postgres | SQLite |
|---|---|---|
| `appendAll`, 1 row a call | 735 | 787 |
| `appendAll`, 100 a call | 47 000 | 63 000 |
| `appendAll`, 1000 a call | 118 000 | 253 000 |
| `appendAll`, 10 000 a call | 140 000 | 422 000 |
| `addAll` into the store, 1000 a call, no rollup / with the rollup | 73 000 / 48 000 | 54 000 / 24 000 |
| the log and its consumer into the store at once, 1000 a call | 101 000 | 24 000 |
| the capture door, 100 events a request, 1 to 32 clients | 40 000 to 137 000 events | 14 000 to 23 000 events |

A question of 600 000 rows takes 0.2 to 0.8 s in Postgres (a funnel the slowest), as in SQLite.
A database across a network adds its round trip to each append: many callers appending at once
share one, as above. The rows take about twice the room they take in SQLite (675 MB for the
log's million rows, against 320 MB).

A question of 600 000 rows on SQLite takes 0.3 to 0.5 s (a trend by hour and name, people, a
funnel, a retention). Many callers appending a row each share one write a turn, so the first row
is the dearest. Past those rates, or past a few million rows a question, is ClickHouse's ground.

## Refused

| Code | |
|---|---|
| `H200` | `keep` that is not a number of days, weeks, months or years, or for a log of KB, MB, GB, TB; less than a day, or a megabyte; a size for a fact. |
| `H201` | A model's line in a log or fact (a rule, `unique`, `check`, a full-text index, `confirmed`, a log's `index`), or a word after a field's type. |
| `H202` | `order` or `partition` in a log; `order` of a field it does not have; `partition` that is not month, day or none. |
| `H203` | A rollup in a log, with no `by`, counting nothing, by a field it does not have, a sum of what is not a number, two of one name; `rollup("name")` it does not have. |
| `H204` | `capture` in a fact. |
| `H205` | A consumer of no log, of a fact, handed more than the batch, two of one name; `rewind` of a consumer it does not have. |
| `H206` | A log or fact asked in the page. |
| `H207` | An operation it does not have. |
| `H208` | An operation given the wrong arguments; `appendAll` of what is not a list of rows. |
| `H209` | A query's word that question does not take, or of the wrong kind; a span, bucket or measure that is not one; a funnel without 2 to 12 steps; a percentile of nothing. |
| `H210` | `by` or `of` a field it does not have; `of` what is not a number. |
| `H211` | A field that is a reference to a model, a file or bytes. |
| `H212` | A log or fact named as another model, log or fact. |
| `H213` | A field every log has, with another type; `id` or `offset` declared. |
| `H214` | Values written into the text of `sql`. |
