105 lines
12 KiB
Markdown
105 lines
12 KiB
Markdown
# A3 open-source record: session replay, click maps, surveys, experiments and exports
|
|
|
|
Package A3 of `docs/analytics/PLAN.md` (section 9.3). Notice files: `apps/product-analytics/public/player/NOTICE`, `src/replay/NOTICE`, `src/experiments/NOTICE`.
|
|
|
|
**flags merge pending.** The flags slot (branch `wave-p2-railyard`, PY2.1) was not on `main` when A3 ran (`git merge-base --is-ancestor 3324466 HEAD` fails). A3 therefore builds against the slot's contract: the public client API `GET /api/v1/flags/client` (A1's `HttpFlagsReader`, a stand-in in tests) and a copy of `FlagEnv`, `Flag` and the `setFlag` signature from `wave-p2-railyard:apps/console/lib/flags/{types,service}.ts` in `apps/console/app/(app)/product-analytics/experiments/_slot/flags-slot.ts`. After the merge, replace `connectedSlot()` there with the block written in its header comment (one function, no other change).
|
|
|
|
## Copied unmodified
|
|
|
|
| Source | Licence | Where it is now | sha256 (first 16) |
|
|
|---|---|---|---|
|
|
| rrweb-player 2.1.6 `umd/rrweb-player.min.js`, `dist/style.css` (tag `rrweb-player@2.1.6`, commit `376824c03f86`) | MIT | `apps/product-analytics/public/player/vendor/rrweb-player/` with `LICENSE` | `c73939967f282003`, `760311ccb2da5389` |
|
|
| simpleheat 0.4.0 `simpleheat.js` | BSD-2-Clause | `public/player/vendor/simpleheat/` with `LICENSE` | `5ce82dbd979299ff` |
|
|
| posthog-js 1.435.1 `dist/lazy-recorder.js`, `dist/surveys.js`, `dist/dead-clicks-autocapture.js` (the parts the browser SDK loads from its host at `/static/`) | Apache-2.0 AND MIT | `public/player/sdk/` with `LICENSE`; served by `src/replay/player-pages.ts` | `e0ba04d3a8640360`, `a0a5ccf176f925c1`, `329a35bc14da77ed`; equal to the wrapper's installed SDK (tested) |
|
|
| aws4fetch 1.0.20 `dist/aws4fetch.esm.mjs` (its type file renamed next to it) | MIT | `src/replay/vendor/aws4fetch/` with `LICENSE` | `3049cd99d00a2fb8` |
|
|
| jStat 1.9.6 `dist/jstat.js` (renamed `jstat.cjs` so Node loads it as CommonJS inside this ESM package) | MIT | `src/experiments/vendor/jstat/` with `LICENSE` | `0f259c0087245bba` |
|
|
|
|
`test/a3/vendor.test.ts` pins every hash and checks every licence file.
|
|
|
|
Why vendored and not installed: the service's `package.json` is A1's file, and the Mac had 11 GiB free (the plan's line is 10 GB). The vendored files add about 630 KB.
|
|
|
|
### Substitution: aws4fetch instead of `@aws-sdk/client-s3`
|
|
|
|
The plan names `@aws-sdk/client-s3` (Apache-2.0). A3 uses aws4fetch (MIT, 11 KB, one file) to sign plain `fetch` requests instead:
|
|
- the full client is about 3.3 MB unpacked plus its dependency tree, and would have to be added to A1's manifest;
|
|
- the service runs under a 192 MiB cap, and it only needs `PUT`, `GET` and `DELETE` of whole objects;
|
|
- the S3 fake in `test/a3/exports.test.ts` verifies every Signature V4 with its own independent code, so the signer is checked against the specification rather than against itself.
|
|
|
|
## Ported (semantics and tests re-expressed in our code)
|
|
|
|
| Upstream | Our file | What was taken |
|
|
|---|---|---|
|
|
| PostHog `products/experiments/stats/{shared,frequentist,bayesian}/*.py` (MIT, commit `645e1a78140757ea1bb9ddeb0ff9d3915c60b6f6`) | `src/experiments/stats/{statistics,methods,distributions}.ts` | Sample-mean, proportion and ratio statistics (delta method); Welch two-sided t-test with Welch-Satterthwaite degrees of freedom; the always-valid sequential test (Waudby-Smith et al., log-space e-value); Gaussian posterior with flat or proper prior, chance to win, credible interval; the same validation messages |
|
|
| PostHog `products/experiments/stats/tests/*` and GrowthBook `packages/stats/tests/{frequentist,bayesian}/test_tests.py` (MIT, commit `44e8a69cf9cf`) | `test/a3/fixtures/stats/{generate_vectors.py,vectors.json}`, `test/a3/stats.test.ts` | The upstream inputs, run through the unmodified upstream Python (scipy 1.18.1, in a scratch venv outside the repo); our port matches every value within 1e-6, and the published 4-5 decimal expectations of both suites hold |
|
|
| `@posthog/core` `getFeatureFlagHash`, `getFeatureFlagVariant` (MIT, in posthog-node 5.54.1) | `src/flags/variants.ts` | `sha1("<flag>.<distinct_id><salt>")`, first 15 hex digits over `0xfffffffffffffff`, rollout then cumulative variant buckets. Equal to the core for 10 000 ids, and the unmodified server SDK's local evaluation and the service's `/flags` give the same variant for 10 000 ids |
|
|
| posthog-js `packages/browser/src/extensions/replay/external/lazy-loaded-session-recorder.ts` (commit `666d10918246`) | `src/replay/snapshot.ts` | The recorder's partial compression (marker `cv: "2024-10"`: full snapshot data, mutation texts/attributes/removes/adds and style rule adds/removes as gzip latin1 strings), undone at ingest |
|
|
| rrweb event format (MIT) | `src/replay/snapshot.ts` | Event and node types used for masking (inputs, textareas, selects, input events, value mutations) and for the index counters |
|
|
| scipy `stats.chisquare` behaviour | `src/experiments/stats/srm.ts` | Chi-square goodness of fit of exposures against planned weights; the upper tail by continued fraction so tiny p-values keep their digits |
|
|
|
|
## Written here (glue)
|
|
|
|
- `/s/` ingest, the chunk format (gzip NDJSON of `{window_id, data}`) and index, lookups by person, event and people, the signed link (G2 shape of `LIMRUN-GAPS.md`: HMAC-SHA256 over resource, project and expiry, at most 10 minutes), the player and map pages (strict CSP, no inline script, no referrer), expiry and the privacy hook.
|
|
- Click map and scroll depth aggregation over `$$heatmap`, `$pageleave` and `$pageview` events.
|
|
- Surveys: validation, the SDKs' `/api/surveys/` and remote-config shape, results from `survey sent`, cohort targeting answers.
|
|
- Experiments: store, the flag value contract (`src/experiments/flag-value.ts`), results SQL, the flag read-back (`flag_state`).
|
|
- Exports: sealed secrets (AES-256-GCM), the outbound address guard, the cursor runner with backoff, CSV of insight answers (through A2's cache and CSV writer).
|
|
- Console screens and `_lib/a3-client.ts`.
|
|
|
|
## Environment (service)
|
|
|
|
| Name | Purpose |
|
|
|---|---|
|
|
| `PA_OBJECT_STORE` | `s3` or `fs`; unset means no recordings (the app's config keeps recording off) |
|
|
| `PA_S3_ENDPOINT`, `PA_S3_BUCKET`, `PA_S3_REGION` (default `auto`), `PA_S3_ACCESS_KEY_ID`, `PA_S3_SECRET_ACCESS_KEY`, `PA_S3_PREFIX` | Recording storage on an S3-compatible bucket (Scribase Storage S3 API or R2) |
|
|
| `PA_FS_STORE_DIR` | Recording storage in a directory (local runs) |
|
|
| `PA_PUBLIC_URL` | Base of signed player and map links (default: the origin the console called) |
|
|
| `PA_CONSOLE_ORIGIN` | Comma list of origins allowed to frame the player and map pages (default `'self'`) |
|
|
| `PA_EXPORTS_KEY` | 32 bytes (64 hex characters or base64) sealing destination secrets; unset means destinations cannot be added |
|
|
| `PA_EXPORTS_ALLOW_PRIVATE=1` | Local development and tests only: lets exports reach http and private addresses |
|
|
| `PA_A3_JOBS=off` | Stops A3's in-process jobs (exports every 30 s, recording expiry hourly) |
|
|
|
|
Console: `RAILYARD_REPLAY_LIVE` (recordings and click maps screens) and `RAILYARD_FLAGS_LIVE` (experiments screens), the same switches the copy denylist reads. Until they are `1` those screens say "arriving" and their actions refuse.
|
|
|
|
## Security notes
|
|
|
|
- Recordings: every typed value is masked twice, by the SDK wrapper's defaults and again at ingest before bytes are stored; the stored chunks are checked byte by byte in tests (unit and Chromium).
|
|
- Player and map links are signed for one resource of one project for at most 10 minutes; the pages allow only this service's scripts, send no referrer, and are framed only by `PA_CONSOLE_ORIGIN`.
|
|
- The map page loads the customer's page in a sandboxed frame with scripts off unless the viewer turns them on, so viewing a map does not count as a visit.
|
|
- Exports: https only, no credentials in URLs, private and reserved addresses refused when the request is sent, no redirects followed, 10 s timeout. A DNS answer can still change between the check and the connection; pinning the resolved address needs an HTTP agent the service does not have, and is noted here as the remaining gap.
|
|
- Destination secrets are sealed at rest; a webhook's signing secret is shown once (a 5-minute, path-scoped, httpOnly cookie on the console side) and never read back.
|
|
|
|
## Tests
|
|
|
|
Run from `apps/product-analytics` (scratch Postgres by `initdb`, the cached Chromium 1243 of playwright-core 1.63; nothing installed):
|
|
|
|
```
|
|
node --test --test-force-exit --test-concurrency=1 test/a3/*.test.ts
|
|
```
|
|
|
|
| File | What it proves |
|
|
|---|---|
|
|
| `migrations.test.ts` | 0020-0024 idempotent, row level security on every A3 table, isolation, constraints |
|
|
| `replay.test.ts` | decompress, mask, count; recording off stores nothing; chunks and index; the typed text absent from stored bytes; 30-minute cut; lookups by person, event and people; the signed link (tamper, other project, 10-minute expiry); static routes; privacy deletion and export; expiry |
|
|
| `replay-browser.test.ts` | Chromium records through the wrapper, the typed address and `[data-private]` text are absent, and the player page plays it back |
|
|
| `heatmaps.test.ts` | hand counts per bucket, type, viewport and range; scroll depth once per page view; the app's config; the overlay draws in Chromium |
|
|
| `surveys.test.ts` | validation, limits and roles; the SDKs' shape; results equal a hand count; cohort targeting answers and the response limit; the web example in Chromium; the Expo example with the React Native SDK's own functions |
|
|
| `stats.test.ts` | the port within 1e-6 of the upstream code; the published expectations; the sample-ratio check |
|
|
| `experiments.test.ts` | flag values; the hash for 10 000 ids; local evaluation and `/flags` agree for 10 000 ids; start and stop through the slot only; results equal a hand count; the 60/40 warning |
|
|
| `exports.test.ts` | sealed secrets and the address guard; signed webhook batches in order and only this project's rows; retry after 30 s then 60 s; S3 NDJSON.gz with Signature V4 checked; limits and pause; insight CSV |
|
|
| `console.test.ts` | the console client through a real service; form mappings; experiments change flags only through `setFlag`; screen parts render; copy denylist, no upstream names, no emoji, one primary action; A3 commits touch only A3's paths |
|
|
| `vendor.test.ts` | vendored files unchanged, licences present, SDK parts equal the wrapper's SDK |
|
|
| `capacity.ts` (script) | see `CAPACITY.md` |
|
|
|
|
## Hand-offs (outside A3's paths; not done)
|
|
|
|
1. **A1, `src/flags/routes.ts`:** merge the cohort survey targeting flags into the `/flags` answer: `list = [...list, ...(await surveyTargetingAnswers(deps.db, site.project_id, String(distinctId)))]` (from `src/surveys/targeting.ts`), also when the project has no flags key. Until then a survey targeted at a segment is sent to the SDKs but shows to nobody; page-address and slot-flag targeting work now.
|
|
2. **A1, `apps/console/app/(app)/product-analytics/_components/Shell.tsx`:** one link to `/product-analytics/surveys` (the A3 screens link to each other from there), so they are one click from the product analytics frame.
|
|
3. **A1, `persons/[distinct_id]/page.tsx`:** a "Recordings" link to `/product-analytics/replay?person=<distinct_id>`. **A2, the funnel drop-off list:** a link to `/product-analytics/replay?funnel=<saved insight id>&step=<n>`. Both entry points already work by URL.
|
|
4. **A1, `package.json`:** a `test:a3` script with the command above.
|
|
5. **A1, `NOTICE`:** one line pointing to the three A3 notice files.
|
|
6. **A1, `deploy/compose.fragment.yml`:** the environment names above (values from the box's secret store), and `PA_CONSOLE_ORIGIN` set to the console's origin.
|
|
7. **A1, `packages/analytics-js/examples/expo`:** wrap the app in the React Native SDK's survey provider so the example shows surveys on screen (the service side is tested with the SDK's own functions).
|
|
8. **A1, `test/a1/console-copy.test.ts`:** skip URL paths and `data-copy-source` markers when collecting copy units (A3's own copy test does). Until then the A3 screens assemble the two route segments that spell gated modules once (`PATHS`, `EXP`, `HEAT` in `_lib/a3-client.ts`) and use singular wording.
|
|
9. **A1, `test/a1/migrations.test.ts` and `test/a1/gdpr.test.ts`:** both assert exact lists that later packages extend (the migration file list, now with A2's 0010-0015 and A3's 0020-0024; the privacy job's result keys, now with A2's `cohorts`). They failed before A3 started (A2's additions) and need their expected lists widened; nothing in A3 changes their behaviour.
|
|
10. **Orchestrator, after the flags merge:** replace `connectedSlot()` as described at the top of this file, and set `RAILYARD_FLAGS_LIVE=1` once the slot passes its isolation test in production.
|