* 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>
188 lines
9.4 KiB
Bash
Executable File
188 lines
9.4 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# End-to-end check of the ingest contract against a real `wrangler dev` + local D1.
|
|
#
|
|
# Boots the worker, POSTs a spread of good and bad batches, then shuts the worker
|
|
# down and inspects the rows that actually landed. Every request uses a fresh
|
|
# machine_id, so the script is re-runnable against a dirty local database and never
|
|
# trips the per-machine rate limit.
|
|
#
|
|
# npm run db:migrate:local # once
|
|
# npm run smoke # or: INGEST_PORT=8791 ./scripts/smoke-ingest.sh
|
|
set -euo pipefail
|
|
|
|
cd "$(dirname "$0")/.."
|
|
PORT="${INGEST_PORT:-8787}"
|
|
BASE="http://127.0.0.1:$PORT"
|
|
DB=codegraph-telemetry
|
|
|
|
pass=0; fail=0
|
|
ok() { pass=$((pass + 1)); printf ' ok %s\n' "$1"; }
|
|
bad() { fail=$((fail + 1)); printf ' FAIL %s — expected %s, got %s\n' "$1" "$2" "$3"; }
|
|
is() { [ "$2" = "$3" ] && ok "$1" || bad "$1" "$2" "$3"; }
|
|
|
|
uuid() { node -e 'console.log(crypto.randomUUID())'; }
|
|
|
|
# HTTP status of a POST /v1/events with the given body.
|
|
post() { curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/v1/events" \
|
|
-H 'content-type: application/json' --data-binary "$1"; }
|
|
|
|
# First column of the first row of a query against the LOCAL D1 state.
|
|
q() {
|
|
npx wrangler d1 execute "$DB" --local --json --command "$1" 2>/dev/null |
|
|
node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{
|
|
const r=JSON.parse(s.slice(s.indexOf("[")))[0]?.results?.[0];
|
|
console.log(r===undefined?"":String(Object.values(r)[0]));})'
|
|
}
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Boot
|
|
# ---------------------------------------------------------------------------
|
|
echo "booting wrangler dev on :$PORT"
|
|
npx wrangler dev --port "$PORT" >/tmp/cg-smoke-ingest.log 2>&1 &
|
|
DEV_PID=$!
|
|
cleanup() { kill "$DEV_PID" 2>/dev/null || true; wait "$DEV_PID" 2>/dev/null || true; }
|
|
trap cleanup EXIT
|
|
|
|
for _ in $(seq 1 60); do
|
|
curl -sf -o /dev/null "$BASE/" && break
|
|
kill -0 "$DEV_PID" 2>/dev/null || { echo "wrangler dev died:"; cat /tmp/cg-smoke-ingest.log; exit 1; }
|
|
sleep 1
|
|
done
|
|
curl -sf -o /dev/null "$BASE/" || { echo "worker never came up:"; cat /tmp/cg-smoke-ingest.log; exit 1; }
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Request contract
|
|
# ---------------------------------------------------------------------------
|
|
echo
|
|
echo "request contract"
|
|
|
|
INFO=$(curl -s "$BASE/")
|
|
case "$INFO" in *"codegraph anonymous-telemetry ingest"*) ok "GET / serves the info text";;
|
|
*) bad "GET / serves the info text" "info text" "$INFO";; esac
|
|
case "$INFO" in *"never forwarded to any third-party analytics"*) ok "info text states the storage guarantee";;
|
|
*) bad "info text states the storage guarantee" "the no-third-party sentence" "missing";; esac
|
|
# The guarantee above holds only while the worker makes no outbound request at all,
|
|
# so the only `fetch(` anywhere in the source may be the handler's own declaration.
|
|
is "worker source makes no outbound fetch" 0 \
|
|
"$(grep -E 'fetch\(' src/*.ts | grep -vc 'async fetch(request' || true)"
|
|
|
|
is "unknown path → 404" 404 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/nope")"
|
|
is "GET /v1/events → 405" 405 "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/v1/events")"
|
|
is "non-JSON body → 400" 400 "$(post 'not json')"
|
|
is "JSON array body → 400" 400 "$(post '[]')"
|
|
is "missing machine_id → 400" 400 "$(post '{"events":[]}')"
|
|
is "malformed machine_id → 400" 400 "$(post '{"machine_id":"nope","events":[]}')"
|
|
is "chunked (no length) → 411" 411 "$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/v1/events" \
|
|
-H 'content-type: application/json' -H 'transfer-encoding: chunked' --data-binary '{"machine_id":"x"}')"
|
|
BIG=$(node -e 'process.stdout.write(JSON.stringify({machine_id:"00000000-0000-4000-8000-000000000000",pad:"x".repeat(70000),events:[]}))')
|
|
is "oversized body → 413" 413 "$(post "$BIG")"
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Accepted batches
|
|
# ---------------------------------------------------------------------------
|
|
echo
|
|
echo "ingest"
|
|
|
|
M_OK=$(uuid); M_DROP=$(uuid); M_CI=$(uuid); M_BACK=$(uuid)
|
|
TODAY=$(date -u +%F)
|
|
|
|
# Three valid events + one unknown event + unknown/malformed props that must be stripped.
|
|
is "valid batch → 204" 204 "$(post "$(node -e '
|
|
const [m] = process.argv.slice(1);
|
|
process.stdout.write(JSON.stringify({
|
|
machine_id: m, codegraph_version: "1.5.0", os: "darwin", arch: "arm64",
|
|
node_major: 22, ci: false, schema_version: 1, secret_field: "must not be stored",
|
|
events: [
|
|
{ event: "install", ts: "2026-07-27T10:00:00Z",
|
|
props: { scope: "local", kind: "fresh", targets: ["claude", "cursor"], nope: "strip me" } },
|
|
{ event: "index", ts: "2026-07-27T10:01:00Z",
|
|
props: { languages: ["typescript"], file_count_bucket: "100-1k",
|
|
duration_bucket: "bogus-bucket", repo_path: "/Users/someone/secret" } },
|
|
{ event: "usage_rollup",
|
|
props: { kind: "mcp_tool", name: "codegraph_explore", count: 12, client_name: "Claude Code" } },
|
|
{ event: "not_an_event", props: { count: 1 } },
|
|
],
|
|
}));' "$M_OK")")"
|
|
|
|
# Nothing survives the allowlist: unknown event + usage_rollup missing required props.
|
|
is "all-dropped batch → 204" 204 "$(post "$(node -e '
|
|
const [m] = process.argv.slice(1);
|
|
process.stdout.write(JSON.stringify({ machine_id: m, os: "linux", events: [
|
|
{ event: "made_up" },
|
|
{ event: "usage_rollup", props: { kind: "mcp_tool" } },
|
|
{ event: "install", props: { scope: "local" } },
|
|
]}));' "$M_DROP")")"
|
|
|
|
# NOTE: build every body into a variable first. Escaped quotes nested inside
|
|
# "$(post "…\"…\"…")" break out of the quoting context and get brace-expanded.
|
|
index_batch() { # <machine_id> [ci] [ts]
|
|
node -e 'const [m, ci, ts] = process.argv.slice(1);
|
|
const e = { event: "index", props: {} };
|
|
if (ts) e.ts = ts;
|
|
const b = { machine_id: m, os: "linux", events: [e] };
|
|
if (ci) b.ci = ci === "true";
|
|
process.stdout.write(JSON.stringify(b));' "$@"
|
|
}
|
|
|
|
# ci = true, then a non-CI batch for the same machine/day: prod must flip 0 → 1.
|
|
CI_ON=$(index_batch "$M_CI" true); CI_OFF=$(index_batch "$M_CI" false)
|
|
is "ci batch → 204" 204 "$(post "$CI_ON")"
|
|
is "same machine, non-ci → 204" 204 "$(post "$CI_OFF")"
|
|
|
|
# A late offline buffer arriving second must move first_day EARLIER, never later.
|
|
RECENT=$(index_batch "$M_BACK" "" 2026-07-27T09:00:00Z)
|
|
BACKDATED=$(index_batch "$M_BACK" "" 2026-07-20T09:00:00Z)
|
|
is "recent batch → 204" 204 "$(post "$RECENT")"
|
|
is "backdated batch → 204" 204 "$(post "$BACKDATED")"
|
|
|
|
sleep 2 # let the ctx.waitUntil writes drain
|
|
cleanup; trap - EXIT
|
|
sleep 1 # and let miniflare release the local sqlite file
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# What actually got stored
|
|
# ---------------------------------------------------------------------------
|
|
echo
|
|
echo "stored rows"
|
|
|
|
is "3 of 4 events stored (unknown dropped)" 3 "$(q "select count(*) from events where machine_id='$M_OK'")"
|
|
is "all-dropped batch stored nothing" 0 "$(q "select count(*) from events where machine_id='$M_DROP'")"
|
|
is "…and no machine_days row for it" 0 "$(q "select count(*) from machine_days where machine_id='$M_DROP'")"
|
|
is "envelope columns land in their own columns" "darwin|arm64|22|0|1.5.0" \
|
|
"$(q "select os||'|'||arch||'|'||node_major||'|'||ci||'|'||codegraph_version from events where machine_id='$M_OK' limit 1")"
|
|
is "day derived from the client ts" "2026-07-27" \
|
|
"$(q "select day from events where machine_id='$M_OK' and event='install'")"
|
|
is "day falls back to received_at when ts is absent" "$TODAY" \
|
|
"$(q "select day from events where machine_id='$M_OK' and event='usage_rollup'")"
|
|
is "ts is NULL when the client sent none" 1 \
|
|
"$(q "select ts is null from events where machine_id='$M_OK' and event='usage_rollup'")"
|
|
is "allowlisted props stored" "local|fresh|2" \
|
|
"$(q "select json_extract(props,'\$.scope')||'|'||json_extract(props,'\$.kind')||'|'||json_array_length(props,'\$.targets') from events where machine_id='$M_OK' and event='install'")"
|
|
is "unknown prop stripped" 0 \
|
|
"$(q "select count(*) from events where machine_id='$M_OK' and props like '%strip me%'")"
|
|
is "malformed enum prop stripped" 0 \
|
|
"$(q "select count(*) from events where machine_id='$M_OK' and props like '%bogus-bucket%'")"
|
|
is "path-shaped prop stripped" 0 \
|
|
"$(q "select count(*) from events where machine_id='$M_OK' and props like '%/Users/%'")"
|
|
is "unknown envelope field stored nowhere" 0 \
|
|
"$(q "select count(*) from events where props like '%must not be stored%'")"
|
|
|
|
# The valid batch mixes ts-dated events (2026-07-27) with an undated rollup (today),
|
|
# so it legitimately spans two days and must produce a machine_days row for each.
|
|
is "machine_days: one row per distinct day in the batch" 2 \
|
|
"$(q "select count(*) from machine_days where machine_id='$M_OK'")"
|
|
is "machine_days: non-ci machine is production" 1 \
|
|
"$(q "select min(prod) from machine_days where machine_id='$M_OK'")"
|
|
is "machine_days: a later non-ci batch flips the day to production" 1 \
|
|
"$(q "select prod from machine_days where machine_id='$M_CI'")"
|
|
is "machine_days: each backdated batch gets its own day" "2026-07-20,2026-07-27" \
|
|
"$(q "select group_concat(day) from (select day from machine_days where machine_id='$M_BACK' order by day)")"
|
|
|
|
is "machine_first_seen recorded" "2026-07-27" "$(q "select first_day from machine_first_seen where machine_id='$M_OK'")"
|
|
is "machine_first_seen only moves earlier" "2026-07-20" \
|
|
"$(q "select first_day from machine_first_seen where machine_id='$M_BACK'")"
|
|
|
|
echo
|
|
echo "$pass passed, $fail failed"
|
|
[ "$fail" -eq 0 ]
|