* feat(telemetry): D1 schema + migrations for raw events and daily rollups First step of replacing PostHog with self-hosted telemetry on Cloudflare D1. Creates the codegraph-telemetry database binding and the initial migration; no worker code paths change yet (the ingest write path and the nightly rollup cron land next). Schema is raw events plus daily rollups: `events` holds one row per sanitized event with the envelope broken out into columns and event-specific props as JSON; `daily_machines`, `daily_event_counts` and `daily_dim_counts` are the nightly rollups the dashboard reads; `machine_first_seen` and `machine_days` carry the retention cohorts and are never purged. One generic dimension table covers every bar and pie, so a new breakdown is a cron change rather than a migration. The migration is commented as an audit surface, like the rest of this worker — every column, and which dashboard chart each rollup table serves. Three judgment calls worth flagging, all documented in the file: - `events` gets `(day, event)` instead of the separate `(day)` and `(event, day)` indexes. D1 bills a row write per index touched, so a third index on the hot table costs ~97k writes/day, and `(day, event)` is a covering index for plain day-range scans anyway (verified with EXPLAIN QUERY PLAN). - `daily_event_counts` and `daily_dim_counts` carry a `machines` column, and `machine_days` a `prod` flag. The "users by ..." panels and the production-user count are distinct-machine numbers, not event counts, and they are unrecoverable once raw events are purged. - No CHECK constraint on `event`: the worker's allowlist is the source of truth and the write path is fail-silent, so a rejected INSERT would lose data quietly instead of erroring loudly. Volume note in the migration footer: ~30M row writes/month against the 50M included on Workers Paid. Storage is the tighter constraint — raw events grow ~74 MB/day, so retention should start at 90 days (~6.7 GB) rather than 180, which would exceed D1's 10 GB per-database cap. * feat(telemetry): admin dashboard worker — scaffold + shared-password auth New Cloudflare Worker at telemetry-dashboard/, sibling of telemetry-worker/ and bound read-only to the same D1 database. Serves a static frontend plus a JSON API behind a shared password, on stats.getcodegraph.com. Auth is the simplest thing that is actually safe for exactly two users: one password in a secret, compared in constant time over SHA-256 digests, and an HMAC-signed cookie (HttpOnly; Secure; SameSite=Lax; Path=/) with a one-year expiry so you sign in once per browser. The cookie is a signed assertion, not a lookup key — no session store. Its payload carries a fingerprint of the password it was minted against, so rotating ADMIN_PASSWORD signs everyone out. Login attempts are capped at 5/min per IP via a ratelimit binding. Everything is deny-by-default: assets.run_worker_first routes every request through the worker before the static-asset server sees it, so the dashboard HTML, its JS, its CSS and the chart library are all behind the session check. The login page is rendered inline by the worker rather than served from public/, which leaves no "is this file public?" judgement calls in the asset directory. Unauthenticated pages 302 to /login, unauthenticated /api/* gets 401. A missing secret fails closed rather than opening the dashboard. scripts/smoke-auth.sh is the regression net — 54 assertions against a throwaway `wrangler dev` covering the gate, cookie flags and persistence, forged/flipped/ truncated cookies, open-redirect refusal, brute-force capping, and password rotation invalidating live sessions. Refs CG-11. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(telemetry-dashboard): simplify the chart-library probe in the shell Refs CG-11. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(telemetry): nightly rollup cron + raw-event retention purge (CG-10) Adds a scheduled() handler to the ingest worker that recomputes daily_event_counts / daily_dim_counts / daily_machines for the just-completed UTC day plus a 2-day overlap (late-arriving offline buffers), then purges raw events past the retention window. Rollup writes are idempotent upserts, so a re-run never double-counts. Also adds an ADMIN_TOKEN-guarded POST /admin/rollup?day=YYYY-MM-DD for backfill/repair, and drops the PostHog forwarding path. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(telemetry): dashboard charts — SQL API over D1 + the Chart.js views (CG-12, CG-13) Replaces the scaffold page with the dashboard proper: 19 panels covering every view of the PostHog dashboard this retires, driven by one filter row. src/api.ts is the read API CG-12 specified: /api/{meta,summary,timeseries, breakdown,activation,retention}, all range-scoped, all parameterized against a closed set of dims and metrics, all shaped labels[] + datasets[] so the frontend does no arithmetic. Rollups answer everything except the activation funnel, which needs raw events and says where they start. The frontend splits into a DOM-free panel registry (public/panels.js) and the page that mounts it (public/app.js), so the render check can drive the same registry the browser rendered from. Panels fail alone, refetch dims rather than flashing, and every chart carries a table twin. Two numbers are labelled rather than rounded off: range-wide "users" per dimension is machine-days (the rollups cannot give distinct machines, and per-day counts are taken as the largest single-event count so one machine's install + index + usage is not counted three times), and recent activation and retention cohorts are marked as still-converting instead of drawn as a cliff. Both colour scales were run through the data-viz validator against the panel surface, not picked by eye; the results are recorded in public/theme.js. Verification, all against the committed fixture (12 machines over 10 days, every expected number worked out by hand from the events, not recorded from a run): scripts/smoke-api.sh 98 assertions scripts/render-check.mjs 79 assertions — real Chromium over CDP, no new deps scripts/smoke-auth.sh 54 assertions (unchanged, still green) Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(telemetry): cutover runbook + the end-to-end gate that de-risks it (CG-14) The account-level steps of the PostHog cutover are the maintainer's to run, so this lands the runbook they follow and the check that has to pass first. The runbook (telemetry-worker/README.md) walks the six steps in the order that keeps them reversible: Workers Paid → migrate → deploy → watch 24h → verify the first rollup and the dashboard → only then delete POSTHOG_KEY and cancel the subscription. Step 3 records the outgoing version id because `wrangler rollback` is the escape hatch for the whole verification window, and that window is precisely why the PostHog key is deleted last rather than first. The new gate (scripts/smoke-cutover.sh, `npm run smoke:cutover`) covers the one seam nothing else did. Both workers declare the same D1 database_id, so pointing them at a single --persist-to directory runs the real chain: a client batch → the ingest worker → D1 → the nightly rollup → the dashboard API reading the numbers back. Every other suite stops at one link — smoke-ingest at the events table, smoke-rollup at hand-checked SQL, smoke-api at a hand-written fixture that the cron never touched. That left the dimension names the rollup WRITES versus the ones the dashboard READS agreeing by convention across two branches, where a mismatch is silent: no error, no failed request, just a panel reading zero forever. 61 assertions, all 13 dimensions, and three deliberate traps — a ci machine that is active but not a production user, usage_rollup counts that must be summed rather than tallied, and an uninstall's `targets` that must not leak into the install-scoped breakdown. Writing it caught that the activation funnel's denominator is first-seen machines, not install events (deliberate — a reinstall must not re-enter the funnel), so the suite now pins that distinction rather than assuming it. Also rewords the last PostHog reference in dashboard code: a comment justifying the 14-day retention curve by pointing at a dashboard step 6 deletes. The reasoning now stands on its own. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(telemetry): tell the truth about where events are stored (CG-15) The telemetry docs are a privacy contract, and they still described a managed analytics store that no longer receives anything. Replace that with what actually happens now — events land in our own D1 database on Cloudflare, the endpoint makes no outbound requests, raw events are purged after 90 days and only anonymous daily rollups outlive them. This strengthens the guarantee rather than restating it: there is no second party to share with. - TELEMETRY.md: new "Where it is stored" section; the never-collected IP bullet no longer leans on a vendor-side setting to hold. - docs/design/telemetry.md: ingest section rewritten around D1 + the nightly rollup/retention cron; volume math redone on Workers Paid and the D1 quota (storage, not writes, is what sets the 90-day window); new section documenting the dashboard worker and cross-linking it. - Fixed three drifts from the worker allowlist the sweep surfaced: schema_version was still 1, client_name/client_version was still marked "plumbing to add" though session.ts passes it today, and the legacy sqlite_backend field the worker still accepts was undocumented. - telemetry-worker/README.md: step 6 claimed a repo-wide grep came back clean, which this runbook itself falsifies. Added step 7 — deleting the runbook is what makes that grep true, and is the completion check. - smoke-cutover.sh: the vendor guarantee is now asserted by class (no analytics-ingest endpoint referenced) rather than by one vendor's name, so it keeps working once the name is gone. Verified it still catches a planted forwarding URL. 61/61 pass. Retention is documented as 90 days, not the 180 in the task notes: 180 days of raw events exceeds D1's 10 GB per-database cap, and the code purges at 90. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore: untrack local Kommandr issue DB and ignore its sqlite artifacts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
206 lines
12 KiB
SQL
206 lines
12 KiB
SQL
-- codegraph telemetry — initial schema (Cloudflare D1)
|
||
--
|
||
-- This file is public on purpose, like the rest of telemetry-worker/: it is the
|
||
-- complete list of everything codegraph's anonymous telemetry stores. If a column
|
||
-- is not here, it is not kept. The field-by-field contract it implements lives in
|
||
-- docs/design/telemetry.md (and, user-facing, in TELEMETRY.md).
|
||
--
|
||
-- Nothing in this database identifies a person or a codebase. No IP addresses (the
|
||
-- ingest worker never reads them), no file paths, no repo, file, or symbol names, no
|
||
-- query strings. `machine_id` is a random UUIDv4 the client mints locally and the user
|
||
-- can delete at any time (`codegraph telemetry off`, or remove ~/.codegraph/telemetry.json).
|
||
--
|
||
-- Shape: raw events + daily rollups.
|
||
-- * The ingest worker (`src/index.ts`) writes ONLY to `events`, `machine_days` and
|
||
-- `machine_first_seen`, off the response path.
|
||
-- * The nightly cron recomputes the `daily_*` rollups from `events` with idempotent
|
||
-- upserts, then purges raw `events` past the retention window.
|
||
-- * The admin dashboard reads rollups first and falls back to `events` only for the
|
||
-- activation funnel and ad-hoc drill-down (both bounded by the retention window).
|
||
--
|
||
-- Apply: npm run db:migrate:local (local .wrangler state)
|
||
-- npm run db:migrate (remote codegraph-telemetry)
|
||
|
||
-- ---------------------------------------------------------------------------
|
||
-- Raw events
|
||
-- ---------------------------------------------------------------------------
|
||
-- One row per sanitized event accepted by POST /v1/events. Everything here has
|
||
-- already passed the worker's allowlist: unknown events dropped, unknown props
|
||
-- stripped, strings length- and charset-checked, timestamps clamped.
|
||
--
|
||
-- Deliberately NO `CHECK (event IN (...))` constraint: the worker's EVENTS allowlist
|
||
-- is the single source of truth, and the write path is fail-silent by design (a
|
||
-- rejected INSERT would lose data quietly rather than error visibly). Same reasoning
|
||
-- for `json_valid(props)` — the worker constructs that JSON itself.
|
||
CREATE TABLE events (
|
||
-- rowid alias, no AUTOINCREMENT: ids are never referenced anywhere, and the
|
||
-- retention purge only ever deletes the OLDEST rows, so max(id) never drops and
|
||
-- ids stay monotonic in practice. Gives the purge a cheap keyset batch:
|
||
-- DELETE FROM events WHERE id IN (SELECT id FROM events WHERE day < ? LIMIT 5000)
|
||
id INTEGER PRIMARY KEY,
|
||
received_at TEXT NOT NULL, -- ISO 8601 UTC, worker clock, always present
|
||
ts TEXT, -- ISO 8601 UTC client timestamp, already clamped
|
||
-- by the worker (>10min future / >30d past rejected);
|
||
-- NULL when the client sent none. For usage_rollup
|
||
-- the client sets it to <rollup day>T12:00:00Z, so it
|
||
-- attributes counters to the day they happened on.
|
||
day TEXT NOT NULL, -- UTC YYYY-MM-DD from substr(ts, 1, 10), else received_at.
|
||
-- Every rollup and every chart is keyed on this.
|
||
event TEXT NOT NULL, -- install | index | usage_rollup | uninstall
|
||
machine_id TEXT NOT NULL, -- random UUIDv4, client-minted (never fingerprinted)
|
||
-- Envelope, identical for every event in a batch. All nullable: the worker's
|
||
-- sanitizer strips anything malformed rather than rejecting the batch, so an old
|
||
-- or odd client shows up as NULLs instead of vanishing.
|
||
codegraph_version TEXT,
|
||
os TEXT, -- process.platform: darwin | linux | win32 | …
|
||
arch TEXT, -- process.arch: arm64 | x64 | …
|
||
node_major INTEGER,
|
||
ci INTEGER, -- 0/1 from the client's `ci` boolean; NULL if absent.
|
||
-- "Production users" = everything except ci = 1
|
||
-- (NULL counts as production — see machine_days.prod).
|
||
schema_version INTEGER,
|
||
props TEXT NOT NULL DEFAULT '{}' -- JSON object of the sanitized event-specific props
|
||
);
|
||
|
||
-- (day, event) subsumes a plain (day) index — SQLite uses the leading-column prefix —
|
||
-- so this pair covers day-range scans, per-event day-range scans AND the retention
|
||
-- purge with one fewer index than listing them separately. That matters: D1 bills an
|
||
-- extra row write per index touched, so every index on this table costs ~97k
|
||
-- writes/day. Do not add a third without re-checking the volume note below.
|
||
CREATE INDEX events_day_event ON events (day, event);
|
||
-- Ad-hoc per-machine drill-down and the activation funnel (install → first index).
|
||
CREATE INDEX events_machine_day ON events (machine_id, day);
|
||
|
||
-- ---------------------------------------------------------------------------
|
||
-- Rollups — written by the nightly cron, read by the dashboard
|
||
-- ---------------------------------------------------------------------------
|
||
-- Rollups are kept FOREVER (they are tiny); raw `events` are purged. So any number a
|
||
-- chart needs long-term has to be recoverable from these tables alone — that is why
|
||
-- the distinct-machine columns exist alongside the event counts.
|
||
|
||
-- Daily unique machines.
|
||
-- Serves: "Daily Production Users" line; the machine denominator on daily panels.
|
||
-- `prod_machines` excludes ci = 1 (CI runners), matching the dashboard's
|
||
-- "Production Users" framing. NOTE: these are per-day distinct counts and CANNOT be
|
||
-- summed across a range — a range-wide distinct count comes from `machine_days`.
|
||
CREATE TABLE daily_machines (
|
||
day TEXT PRIMARY KEY,
|
||
machines INTEGER NOT NULL DEFAULT 0,
|
||
prod_machines INTEGER NOT NULL DEFAULT 0
|
||
);
|
||
|
||
-- Daily event volume per event type.
|
||
-- Serves: "Install" / "Uninstall" big numbers; "Installs vs uninstalls over time";
|
||
-- "New installs (daily)"; the runs series of "Daily indexing activity".
|
||
-- `count` is a row count for install/index/uninstall, but for usage_rollup it is the
|
||
-- SUM of the events' `count` prop (the client pre-aggregates locally, so one row can
|
||
-- represent hundreds of tool calls). `machines` is the distinct machines that emitted
|
||
-- that event that day — the "active users" series of "Daily indexing activity", which
|
||
-- is unrecoverable once the raw rows are purged.
|
||
CREATE TABLE daily_event_counts (
|
||
day TEXT NOT NULL,
|
||
event TEXT NOT NULL,
|
||
count INTEGER NOT NULL DEFAULT 0,
|
||
machines INTEGER NOT NULL DEFAULT 0,
|
||
PRIMARY KEY (day, event)
|
||
) WITHOUT ROWID;
|
||
|
||
-- One generic (dimension, value) table behind every bar and pie on the dashboard,
|
||
-- so a new breakdown is a cron change, never a migration.
|
||
-- Serves, by `dim`:
|
||
-- os → "Users by operating system" (pie)
|
||
-- arch → arch mix
|
||
-- codegraph_version → "Users by app version" (bar)
|
||
-- node_major → Node version mix
|
||
-- language → "Most-indexed programming languages" (bar; unnested from index.languages)
|
||
-- file_count_bucket → "Codebase size (files per project)" (bar)
|
||
-- duration_bucket → "Session run length" (pie) and "Indexing speed" (bar),
|
||
-- plus "indexing duration buckets over time" (stacked line)
|
||
-- target → "AI Agent Targets" (bar; unnested from install.targets / uninstall.targets)
|
||
-- scope → install local vs global
|
||
-- kind → install fresh / upgrade / reinstall
|
||
-- name → usage by MCP tool / CLI command (incl. prompt-hook-gate-* outcomes)
|
||
-- client_name → usage by agent (Claude Code, Cursor, …), from MCP clientInfo
|
||
-- `event` is kept in the key so the same dim can be sliced per event type (e.g. os for
|
||
-- install vs os for index). `count` is event volume (SUM of the usage_rollup `count`
|
||
-- prop where applicable); `machines` is distinct machines — the honest number for the
|
||
-- "users by …" panels, which are machine counts, not event counts.
|
||
CREATE TABLE daily_dim_counts (
|
||
day TEXT NOT NULL,
|
||
event TEXT NOT NULL,
|
||
dim TEXT NOT NULL,
|
||
value TEXT NOT NULL,
|
||
count INTEGER NOT NULL DEFAULT 0,
|
||
machines INTEGER NOT NULL DEFAULT 0,
|
||
PRIMARY KEY (day, event, dim, value)
|
||
) WITHOUT ROWID;
|
||
|
||
-- Cross-event slices of one dimension over a date range ("languages, all events, last 30d").
|
||
CREATE INDEX daily_dim_counts_dim_day ON daily_dim_counts (dim, day);
|
||
|
||
-- First day a machine was ever seen.
|
||
-- Serves: "New installs over time"; the denominator of the install → first-use
|
||
-- activation funnel; the cohort key for retention.
|
||
-- Written by the ingest worker on every batch (upsert keeps the MINIMUM day, so a
|
||
-- late-arriving offline buffer can move a machine's first day earlier but never later).
|
||
CREATE TABLE machine_first_seen (
|
||
machine_id TEXT PRIMARY KEY,
|
||
first_day TEXT NOT NULL
|
||
);
|
||
|
||
-- Cohort scans: "machines first seen between X and Y".
|
||
CREATE INDEX machine_first_seen_day ON machine_first_seen (first_day);
|
||
|
||
-- Machine × day activity matrix — the only table that can answer "distinct machines
|
||
-- over a RANGE" (daily rollups can't: summing them double-counts returning machines).
|
||
-- Serves: "Daily retention cohorts" (day 0–14 curve, joined to machine_first_seen);
|
||
-- the "Production Users" big number over the picker's range;
|
||
-- active-machine lines beyond the raw-event retention window.
|
||
-- `prod` is 0 only if EVERY event that machine sent that day carried ci = 1; a missing
|
||
-- `ci` counts as production. Kept per (machine, day) rather than as a per-machine flag
|
||
-- because the same install can run inside and outside CI on different days.
|
||
-- ~10k rows/day at current volume — WITHOUT ROWID keeps it compact (the PK is the table).
|
||
-- NOT purged by the retention job: retention cohorts need the full history.
|
||
CREATE TABLE machine_days (
|
||
machine_id TEXT NOT NULL,
|
||
day TEXT NOT NULL,
|
||
prod INTEGER NOT NULL DEFAULT 1,
|
||
PRIMARY KEY (machine_id, day)
|
||
) WITHOUT ROWID;
|
||
|
||
-- Day-keyed scans ("distinct machines active in this range").
|
||
CREATE INDEX machine_days_day ON machine_days (day);
|
||
|
||
-- ---------------------------------------------------------------------------
|
||
-- Volume & storage sanity check (Workers Paid, limits as of 2026-07)
|
||
-- ---------------------------------------------------------------------------
|
||
-- Included per month: 50M rows written, 25B rows read, 5 GB storage
|
||
-- (then $0.75/GB-mo). Hard cap: 10 GB per database.
|
||
--
|
||
-- Current ingest is ~97k accepted POSTs/day. D1 counts one row write PER INDEX
|
||
-- touched in addition to the table row, so with ~2 events per request:
|
||
--
|
||
-- events 97k × 2 × (1 table + 2 indexes) ≈ 0.6M writes/day
|
||
-- machine_days 97k × (1 table + 1 index) ≈ 0.2M writes/day
|
||
-- first_seen 97k × (1 table + 1 index) ≈ 0.2M writes/day
|
||
-- rollup cron ~1k rows/day negligible
|
||
-- ─────────────────
|
||
-- ≈ 1.0M writes/day ≈ 30M/month
|
||
--
|
||
-- Comfortably inside the 50M included, with ~1.6× headroom. (The epic's "~10M/month"
|
||
-- estimate predates counting index writes; the arithmetic above is the one to trust.)
|
||
-- Reads are trivial: the dashboard hits rollups, ~thousands of rows per page load.
|
||
--
|
||
-- STORAGE is the tighter constraint, and it decides the retention window. A raw event
|
||
-- row is ~250 B plus ~130 B of index entries, so ~74 MB/day:
|
||
--
|
||
-- 90-day retention ≈ 6.7 GB under the 10 GB cap, ~$1.30/mo over the 5 GB included
|
||
-- 180-day retention ≈ 13 GB EXCEEDS the 10 GB per-database cap
|
||
--
|
||
-- So the retention job should start at 90 days, not 180 — and the real row size must be
|
||
-- measured after cutover (`SELECT count(*), sum(length(props)) FROM events`) before
|
||
-- widening it. Rollups are kept forever regardless, so shortening the raw window costs
|
||
-- ad-hoc drill-back, never a chart. If writes or storage ever get tight, the levers, in
|
||
-- order: drop events_machine_day (drill-down only), move the machine_first_seen upsert
|
||
-- off the hot path into the nightly cron, then store timestamps as INTEGER epoch ms.
|