返回 CodeWhale
README.md
根目录 / telemetry-ingest / README.md
1 # `telemetry-ingest` — Codewhale's first-party telemetry endpoint
2
3 A Cloudflare Worker that accepts the batches described in
4 [`docs/TELEMETRY.md`](../docs/TELEMETRY.md) and writes them to Workers Analytics
5 Engine. One POST route. No response body on any path. The handler never reads
6 client-IP metadata and the closed payload schema accepts no address field.
7
8 It lives here and not in `web/` because the site is a separate deploy with its
9 own build (Next.js via OpenNext); this is a single 13 KiB script with no assets,
10 and coupling the two would mean a telemetry change rebuilding the marketing site.
11
12 **Deployed and live** at `https://telemetry.codewhale.net/v1/telemetry`, which
13 is the shipped default for `telemetry_endpoint`. workers.dev is disabled; that
14 hostname is the only way in.
15
16 The current Engine source defaults usage analytics on under notice version 6, with a
17 clear opt-out. Prior explicit declines remain off; a missing acceptance record
18 is not treated as consent. Schema 6 carries `notice_version: 8` and schema 4 carries `notice_version: 6`; schema 3
19 uses notice 5, and legacy schema 2 retains its original explicit
20 `consent_version: 4` contract. Schema 1, 4 and 6 batches are first-party
21 only in this source. Local validation is not proof this updated Worker has been deployed. A user who wants
22 to contact nobody sets `telemetry_endpoint = ""`, which writes batches to
23 `$CODEWHALE_HOME/telemetry/dryrun.jsonl` instead.
24
25 ---
26
27 ## Cross-repository CWC contract
28
29 The cross-repository CWC contract is generated, not independently authored:
30 `node scripts/export-product-schema.mjs` (Node 22.18+) exports
31 `schema/cwc-product-v3.schema.json` from this validator's constants. The v2
32 artifact remains available for existing clients. It accepts
33 only `web-app` / `desktop`, one closed `product_usage` event, and the fixed
34 no-fingerprint browser envelope. Copies must be compared with this generated
35 artifact when changing the schema. `test/golden/browser-v3.json` is a complete
36 website wire example; CWC changes only its surface to `web-app` or `desktop`.
37 `operations_summary` is separate operator-consented service health: six `u32`
38 aggregates on `control-plane` with a new random install ID per batch, never
39 individual request records or end-user identifiers.
40
41 The website/app same-origin proxy, when configured, must validate and forward
42 only the closed batch body and reconstruct a content-type header. Do not pass
43 through the incoming request, cookies, user agent, authentication, or metadata.
44 The ingest's two-header invariant remains unchanged.
45
46 ## The one property that matters
47
48 `docs/TELEMETRY.md` publishes:
49
50 > Batches are **IP-stripped at ingest**. No IP is stored, logged, or joined to
51 > `install_id`.
52
53 This Worker is the whole of what makes that sentence true. There is no other
54 component. So:
55
56 - `src/index.ts` reads exactly two request headers — `content-type` and
57 `content-length` — and nothing else, ever.
58 - It never touches the `cf` property of the request, so country, colo, city,
59 region, ASN and coordinates are never in scope.
60 - `src/datapoint.ts` builds every stored row, and it cannot see the request at
61 all: its input type is the validated batch body.
62 - Nothing logs. `invocation_logs` is off in `wrangler.jsonc`, because Cloudflare
63 describes those as "enriched with information available to Cloudflare in the
64 context of the invocation" — exactly the class of automatic per-request record
65 this service promises not to keep.
66 - `test/no-ip.test.ts` reads the shipped source as text and fails the build if
67 any of those names appears, if the set of headers read grows past two, if a
68 `console.*` call is added, or if a `Response` is ever constructed with a body.
69 That file is the only place in this directory where the forbidden header names
70 are written down. A later edit cannot add one quietly.
71
72 Debugging without an IP is a solved problem: the schema carries `os`, `arch`,
73 `libc`, `surface`, `app_version` and `git_sha`, which is what crash triage
74 actually needs.
75
76 ## What it stores
77
78 Everything in [`docs/TELEMETRY.md`](../docs/TELEMETRY.md) and nothing else. The
79 validator in `src/schema.ts` is a **closed** field set: an unexpected key
80 anywhere in the batch — envelope, event, `counters`, `errors`, `turn_wall` —
81 rejects the whole batch with `400`. That is the point of the design. A future
82 client bug that starts attaching a path, a prompt, or a customer's provider
83 table name gets refused by the server rather than quietly stored.
84
85 `test/schema-doc.test.ts` parses the field names and enum spellings back out of
86 `docs/TELEMETRY.md` and asserts set equality against the validator, and
87 `test/ingest.test.ts` posts `crates/telemetry/tests/golden/v1.json` — the
88 client's own pinned v1 wire form — and asserts it is accepted byte for byte and
89 that deleting *any* key from it is rejected. The doc, the Rust client, and this
90 endpoint cannot drift apart without a red test.
91
92 ### Column layout
93
94 One Analytics Engine data point per event. A batch carries at most 200 events
95 (`BATCH_MAX_EVENTS`) and Analytics Engine allows 250 data points per invocation,
96 so a conforming batch never needs a second pass.
97
98 The layout is **positional and append-only** — Analytics Engine columns are
99 `blob1..blob20` / `double1..double20`, and the names below exist only in the SQL
100 you write. Renumbering silently rewrites every historical query. To add a field,
101 take the next free slot.
102
103 | column | contents |
104 |---|---|
105 | `index1` | `install_id` — random v4 UUID, client-rotated every 90 days. The only identifier in the schema. |
106 | `blob1` | `event` — `install_or_upgrade` \| `session_start` \| `session_end` \| `panic` \| `product_usage` \| `operations_summary` |
107 | `blob2` | `surface` |
108 | `blob3` | `os` |
109 | `blob4` | `arch` |
110 | `blob5` | `libc` |
111 | `blob6` | `app_version` |
112 | `blob7` | `git_sha`, `''` for every locally built binary |
113 | `blob8` | `tty` — `'true'` \| `'false'` |
114 | `blob9` | `install_kind` (`install_or_upgrade` only) |
115 | `blob10` | `previous_version` (`install_or_upgrade` only) |
116 | `blob11` | `session_source` (`session_start` only; schema 6 adds `fleet_worker`, `agent`, `scripted`) |
117 | `blob12` | `duration_bucket` (`session_end`); `install_age` (`session_start`, schema 6 only: `new_today`, `under_week`, `older`, `''` for null or older schemas) |
118 | `blob13` | `exit_class` (`session_end` only; schema 6 adds `unclean`) |
119 | `blob14` | `cold_start_bucket` (`session_end` only; `''` on surfaces that do not measure it) |
120 | `blob15` | `providers`, comma-joined, already sorted and deduplicated; the one `provider` on `model_usage` |
121 | `blob16` | `panic_site` (`panic`) — a `crates/…` path or the literal `<dep>`; `model` (`model_usage`); `tool` (`tool_usage`) |
122 | `blob17` | `sent_at` — the *batch* timestamp. Events carry none. |
123 | `blob18` | `aggregate_counters` — closed JSON counts, for `product_usage` or `operations_summary` |
124 | `blob19` | `schema_version` |
125 | `blob20` | `privacy_version`: notice8 for v6, notice7 for the v5 website funnel, notice6 for v4, notice5 for v3, consent4 for v2, empty for v1; `blob19` keeps their meanings distinct |
126 | `double1..10` | `counters`: `turns`, `tool_calls`, `fleet_dispatch`, `workflow_run`, `subagent_spawn`, `mcp_server_connected`, `memory_search`, `approval_modal_shown`, `approval_auto_allowed`, `command_palette_open` |
127 | `double11..16` | `errors`: `auth_preflight_failed`, `provider_http_4xx`, `provider_http_5xx`, `tool_denied_by_policy`, `tool_timeout`, `network_error` |
128 | `double17..20` | `turn_wall`: `lt_5s`, `5_30s`, `30_120s`, `gte_120s` |
129 | `double1..11` on `model_usage` | `turns_ok`, `turns_failed`, `turns_interrupted`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, then `turn_wall` `lt_5s`, `5_30s`, `30_120s`, `gte_120s` |
130 | `double12..18` on `model_usage` | schema 6 only, `0` on v4 rows (`blob19` tells them apart): `requests`, `reasoning_tokens`, `generation_secs` (whole seconds, session sum, u32), then input-size request counts `lt_32k`, `32k_128k`, `128k_256k`, `gte_256k` |
131 | `double1..2` on `tool_usage` | `calls`, `errors` |
132
133 Columns not relevant to an event are `''` / `0`. `tty` is a blob because the 20
134 doubles are exactly used by the three numeric structs — Analytics Engine's
135 ceiling is 20.
136
137 ### What it structurally cannot store
138
139 Not "does not"; **cannot**, given the code as written:
140
141 - **The client IP, and anything derived from it** — never read. See above.
142 - **Any geo** — country, colo, city, region, ASN, coordinates, timezone.
143 - **Any key the schema does not name.** Unknown key ⇒ `400` for the entire
144 batch, so there is no path from an unexpected field to storage.
145 - **Any free-form string.** The published schema has no free-form string type and
146 no open-keyed map. Every field is an integer, a boolean, or a closed enum,
147 except `app_version`, `git_sha` and `panic_site` — each of which has a regex
148 here, so a path, a prompt, a URL, or a branch name fails the shape check.
149 - **A provider table name.** `providers` entries must be lowercase hyphenated ids
150 and the array must be sorted and deduplicated; `acme_internal_gateway` is
151 rejected. (See "known gap" below.)
152 - **A panic message.** Only `panic_site`, and only inside the `crates/`
153 allowlist or the literal `<dep>`.
154 - **Per-event timestamps.** There are none in the schema; only `sent_at`,
155 per batch.
156 - **Response content.** Every response is a bare status with a `null` body, so
157 the endpoint cannot echo back what it received or what it holds.
158
159 **Known gap, stated plainly.** `providers` is the one field whose *value* space
160 this endpoint cannot close. The authoritative list is
161 `codewhale_config::provider::all_providers()`, a Rust registry with no generated
162 artifact to read, and hard-coding a copy here would drift into silently dropping
163 a real user's route. The client closes it (`Event::is_bounded` →
164 `is_known_provider_id`) before the POST is made; the server enforces the shape a
165 closed `&'static str` enum can produce, plus the doc's sorted-and-deduplicated
166 rule. If a generated provider-id list ever lands in the repo, wire it in here.
167
168 ### Retention
169
170 Cloudflare stores Analytics Engine data for **three months**, and that is not
171 configurable — a ceiling rather than a policy, since no setting could make it
172 longer. `docs/TELEMETRY.md` states it. The separate [`telemetry-stats/`](../telemetry-stats/) Worker is the private page (behind Cloudflare Access, aggregates only) that reads this dataset in place, and its daily rollup keeps per-day totals with no install ids beyond three months; this Worker stays write-only and is not changed by it.
173
174 ---
175
176 ## Deploy
177
178 Live. The commands below are the ones that produced the current deployment and
179 the ones that will produce the next one.
180
181 ```sh
182 cd telemetry-ingest
183 npm install
184 npm test # 109 tests, including the doc weld and the IP guard
185 npx wrangler deploy --dry-run --outdir=.wrangler/dry-run # no account touched
186 npx wrangler deploy # <- the only command that publishes anything
187 ```
188
189 The `routes` block in `wrangler.jsonc` binds it to `telemetry.codewhale.net` as
190 a custom domain, so the endpoint URL is
191 `https://telemetry.codewhale.net/v1/telemetry`. The workers.dev subdomain is
192 disabled: that hostname is the only way in.
193
194 Verified against the live endpoint before the client default was changed: the
195 client's golden batch returns `204` with a zero-byte body; an unknown key
196 returns `400`; `GET` returns `405`; a wrong content type returns `415`; a `POST`
197 to `/` returns `404`. Reading back from Analytics Engine returned exactly two
198 rows — `session_start` and `session_end`, carrying `install_id`, `surface=tui`,
199 `os=macos` — the documented shape and nothing else.
200
201 **Re-run the verification below after any deploy.** The client default now
202 points here, so a regression in this Worker is a regression in a promise
203 `docs/TELEMETRY.md` makes to users.
204
205 ### Analytics Engine dataset setup
206
207 There is none. The dataset named in `wrangler.jsonc`
208 (`codewhale_telemetry`) is created implicitly on the first successful
209 `writeDataPoint`, so there is nothing to provision ahead of the deploy. Confirm
210 it exists after the first batch:
211
212 ```sh
213 curl "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/analytics_engine/sql" \
214 --header "Authorization: Bearer $CF_API_TOKEN" \
215 --data "SHOW TABLES"
216 ```
217
218 The token needs **Account → Account Analytics → Read**. Querying is out of band
219 through this API, or through the separate `telemetry-stats/` Worker, which reads
220 the dataset in place through an account binding with no token; this Worker
221 itself has no read path at all.
222
223 ### Rate limiting
224
225 `ratelimits` binding, 20 POSTs per 60s, **keyed on `install_id`** from the
226 validated batch body. Never on a network address — an IP-keyed limiter would
227 mean this Worker handles IPs, which is the whole thing it must not do. That is a
228 weaker limiter (an `install_id.json` can be rewritten between POSTs) and it is
229 the right trade: Cloudflare's edge already absorbs volumetric abuse, and the
230 client only flushes once per session anyway (one three-second attempt at
231 shutdown).
232
233 ### Size cap
234
235 `MAX_BODY_BYTES` is 72 KiB, computed rather than guessed. A conforming client
236 sends at most 200 events totalling at most 65536 bytes (`BATCH_MAX_EVENTS` and
237 `BATCH_MAX_BYTES` in `crates/telemetry/src/actor.rs`, both hard ceilings because
238 `parse_events` breaks *before* crossing them), plus 199 commas and ~375 bytes of
239 envelope keys and values — 66110 bytes worst case. 72 KiB is ~11% headroom.
240
241 The 512-record / 256 KiB rings in `crates/telemetry/src/buffer.rs` are the *disk*
242 cap, not the wire cap: a full ring drains as three batches, never as one POST.
243
244 `content-length` is checked first as a cheap reject, but it is client-supplied,
245 so the real bound is enforced while reading the body and the stream is cancelled
246 the moment it goes over.
247
248 ---
249
250 ## Owner reports and queries
251
252 The routine activity report is a checked-in command rather than SQL copied
253 from a chat:
254
255 ```sh
256 CF_ACCOUNT_ID=... CF_API_TOKEN=... npm run report:active-installs
257 CF_ACCOUNT_ID=... CF_API_TOKEN=... npm run report:active-installs -- --days 30 --json
258 ```
259
260 The metric is **observed active installs by UTC day**: distinct rotating
261 anonymous `install_id` values that produced a `session_start` event that day,
262 plus the weighted number of sessions started. It is never a count of people,
263 accounts, or total installs, and the report says so next to the numbers.
264 `npm run report:dau` still works — `scripts/report-dau.mjs` is a pure
265 re-export of the canonical `scripts/report-active-installs.mjs`, kept only so
266 the old name keeps working — but the canonical name matches what the number
267 actually is.
268
269 One command produces all four things the ledger asks for:
270
271 - the **daily series** (default `--days 15` — 14 complete UTC days plus the
272 partial current day, marked `*`);
273 - a **7-day trend** over complete UTC days only: the last 7 days' sum of
274 daily observed active installs against the previous 7, with the percentage
275 change. When the window cannot cover both sides it says so instead of
276 printing zeros;
277 - **event freshness**: the timestamp of the newest ingested event of any kind
278 and how stale it is, or a plain statement that nothing has been ingested;
279 - the **coverage caveats, printed with the numbers** in both text and
280 `--json` modes: clients older than the telemetry feature, opted-out
281 installs, and non-emitting environments (kill switches, fleet workers,
282 offline shutdowns, dropped flushes) are invisible, so every count is a
283 lower bound; and the 90-day id rotation means week-over-week comparisons
284 are not a retention metric.
285
286 The token needs **Account → Account Analytics → Read**. The report performs
287 two read-only SQL requests (the series and the freshness probe), does not
288 print credentials, and rejects windows beyond Analytics Engine's fixed 90-day
289 retention. Its read path is pinned by `test/report-active-installs.test.ts`:
290 the install id appears only inside `count(DISTINCT …)`, no payload column
291 (`blob2`+, `double*`) is ever selected, and the output wording can never label
292 the result as users, people, or accounts.
293
294 The underlying ad-hoc queries are one query each, which is what the column
295 layout was chosen for. Run them against the SQL API:
296
297 ```sh
298 query() {
299 curl -sS "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/analytics_engine/sql" \
300 --header "Authorization: Bearer $CF_API_TOKEN" --data "$1"
301 }
302 ```
303
304 `_sample_interval` says how many original rows a stored row represents;
305 Analytics Engine downsamples high-volume indexes, so every count is weighted by
306 it rather than using bare `count()`.
307
308 ### (a) How many installs and sessions
309
310 ```sql
311 SELECT
312 count(DISTINCT index1) AS installs,
313 sumIf(_sample_interval, blob1 = 'session_start') AS sessions_started,
314 sumIf(_sample_interval, blob1 = 'session_end') AS sessions_ended,
315 sumIf(_sample_interval, blob9 = 'install') AS first_installs,
316 sumIf(_sample_interval, blob9 = 'upgrade') AS upgrades,
317 sumIf(_sample_interval, blob13 = 'clean') AS clean_exits
318 FROM codewhale_telemetry
319 WHERE timestamp > NOW() - INTERVAL '7' DAY
320 ```
321
322 Read `installs` as what the published doc says it is and nothing more: the id
323 rotates every 90 days and is regenerated whenever the telemetry directory is
324 cleared, so **no count derived from `install_id` is a user count**. It is a lower
325 bound on distinct machine-installs seen in the window, and it undercounts a
326 returning user across a rotation.
327
328 Add `, blob6` to `SELECT` and `GROUP BY blob6` to cut by `app_version`; `blob3`
329 for OS, `blob2` for surface.
330
331 ### (b) Which error classes and panic sites dominate
332
333 ```sql
334 SELECT
335 blob16 AS panic_site,
336 sum(_sample_interval) AS rows,
337 sum(double11 * _sample_interval) AS auth_preflight_failed,
338 sum(double12 * _sample_interval) AS provider_http_4xx,
339 sum(double13 * _sample_interval) AS provider_http_5xx,
340 sum(double14 * _sample_interval) AS tool_denied_by_policy,
341 sum(double15 * _sample_interval) AS tool_timeout,
342 sum(double16 * _sample_interval) AS network_error
343 FROM codewhale_telemetry
344 WHERE timestamp > NOW() - INTERVAL '7' DAY
345 AND blob1 IN ('session_end', 'panic')
346 GROUP BY panic_site
347 ORDER BY rows DESC
348 ```
349
350 One query, two answers, because `panic_site` is `''` on every non-panic row:
351
352 - the **`panic_site = ''` row** carries the six error-class totals across all
353 `session_end` events in the window — that is the error ranking;
354 - every **other row** is one panic site, ranked by how often it fired.
355
356 Sessions that ended in a panic are visible either way: `blob13 = 'panic'` on the
357 `session_end` row, and the `panic` event carries the site.
358
359 ---
360
361 ## Verifying no IP is stored
362
363 Three checks, in increasing order of how convincing they are.
364
365 **1. The source cannot ask for it.** `npm test` runs `test/no-ip.test.ts`, which
366 greps the shipped source. Prove the guard is live by adding a
367 `request.headers.get("CF-Connecting-IP")` line to `src/index.ts` and re-running —
368 three tests go red — then revert.
369
370 **2. Every stored column is accounted for.** The schema is closed and the layout
371 above is exhaustive; there is no free slot an address could occupy. Confirm the
372 deployed dataset has exactly the columns you expect:
373
374 ```sh
375 query "SELECT * FROM codewhale_telemetry LIMIT 1 FORMAT JSON"
376 ```
377
378 The result carries `dataset`, `timestamp`, `_sample_interval`, `index1`, and the
379 `blob*`/`double*` columns. There is no address column, because Analytics Engine
380 has no implicit one — every column is written by `writeDataPoint`.
381
382 **3. Search the stored data for an address shape.** After the first real
383 batches, this returns zero rows:
384
385 ```sql
386 SELECT count() AS suspicious
387 FROM codewhale_telemetry
388 WHERE timestamp > NOW() - INTERVAL '7' DAY
389 AND (
390 match(index1, '\\d+\\.\\d+\\.\\d+\\.\\d+')
391 OR match(concat(blob1, blob2, blob3, blob4, blob5, blob6, blob7, blob8,
392 blob9, blob10, blob11, blob12, blob13, blob14, blob15,
393 blob16, blob17), '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|:[0-9a-f]{1,4}:')
394 )
395 ```
396
397 Also confirm nothing is being logged: with `invocation_logs` off and no
398 `console.*` call in the source, **Workers Logs → this Worker** should show no
399 per-request entries at all.
400
401 ---
402
403 ## Local development
404
405 ```sh
406 npm install
407 npm test # vitest, 109 tests
408 npm run typecheck # tsc --noEmit
409 npm run check # wrangler deploy --dry-run — touches no account
410 npm run dev # wrangler dev --local
411 ```
412
413 `wrangler dev --local` runs the real `workerd` with local Analytics Engine and
414 rate-limit bindings. Post the client's own golden batch at it:
415
416 ```sh
417 curl -i -X POST http://127.0.0.1:8787/v1/telemetry \
418 -H 'content-type: application/json' \
419 --data-binary @../crates/telemetry/tests/golden/v1.json
420 # HTTP/1.1 204 No Content, zero-byte body
421
422 curl -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8787/v1/telemetry
423 # 405, Allow: POST
424 ```
425
426 ### Responses
427
428 | status | when |
429 |---|---|
430 | `204` | accepted, zero-byte body, no headers |
431 | `400` | not JSON, or fails the published schema — including any unknown key |
432 | `404` | POST to a path other than `/v1/telemetry` |
433 | `405` | any method other than POST, on any path (`Allow: POST`) |
434 | `413` | body over `MAX_BODY_BYTES` |
435 | `415` | content type is not `application/json` |
436 | `429` | this `install_id` is over the rate limit |
437 | `500` | internal error; nothing was written |
438
439 Every one of them has an empty body. The client
440 (`crates/telemetry/src/client.rs`) reads only the status class and drops the
441 batch on anything that is not 2xx — no retry, no backoff, no re-queue — so a
442 rejection is invisible to the user by construction, and a 5xx here can never
443 become a client-visible error. That is what lets this endpoint fail closed:
444 when in doubt, refuse the batch.
445
445 lines MARKDOWN