Count the visits, and say whether anyone got anywhere

A hosted demo raises a question a local app never does: is anyone using it,
and do they reach the part that matters? `/analytics` answers it — visitors,
pages, referrers, countries, devices, which shared scenarios get played, turns
and demo-key spend, API and turn errors, and a funnel from visited to played a
turn to signed up.

Not a third-party script, for reasons specific to this one. The CSP allows
`script-src 'self'`, so a tracker means loosening it; adblockers eat the
popular ones, which silently biases exactly the technical audience this
project gets shown to; and none of them can see the measurement that actually
matters here, which is a turn, not a pageview.

**A visit is a write and never a read.** After the 189x egress fix it would be
perverse to add a feature that reads rows per request, so counts accumulate in
a process-local dict and flush every 60s as UPSERTs. Storage is a generic
`(day, metric, label) -> hits` counter, so measuring something new later costs
a constant rather than a migration, plus one row per visitor per day for the
funnel flags. Every dashboard query is a GROUP BY returning tens of rows
however much traffic sits behind it; a month reads back in a few kilobytes.
The buffer's cost is that a hard restart can lose up to a minute — the flusher
also runs on shutdown, and a tier that sleeps when idle sleeps on an empty
buffer anyway.

**The counters are anonymous; the access log beside them is not, on purpose.**
A visitor is `HMAC(secret, "visitor:<user id>")` truncated to 32 chars —
one-way, so `analytics_daily` and `analytics_visitor_days` cannot be joined
back to `users`, and keyed, so no client can compute one. Story content never
reaches that module, and the only content it ever names is a seeded public
scenario's title; a player's own titles are theirs. `accesslog.py` is the
identifying half and is a separate module writing a separate table so that
separation is a property of the code rather than a convention: `access_events`
records sessions, sign-ins, registrations and failed attempts with address,
email and device, read on a second tab of the same page behind the same gate.

Both halves are gated on `AIDND_ANALYTICS_EMAILS`, not `POWER_USERS`. An
unmetered tester is not automatically someone who should see the traffic. The
route 404s and the nav link is absent for everyone else, the same treatment
AI Chat gets; unset in a hosted deploy means nobody sees it, including me.

Three things came out of building it that a test would not have suggested.

**A failed turn is an HTTP 200 with a bad ending.** The status-code middleware
cannot see one, so a demo whose model had started refusing every request would
look perfectly healthy from outside. All five SSE error paths in
`_generate_turn` now go through a `turn_error()` helper that counts on the way
out. Error buckets elsewhere are labelled by the matched route template rather
than the requested path — one bucket per endpoint instead of one per adventure
id, and, the reason it isn't merely tidier, an unmatched path is entirely
attacker-chosen, so labelling by it would let anyone mint rows.

**The funnel counts people, not clicks.** A player who starts six adventures
is one person who started an adventure. That is the whole reason the
per-visitor-day table exists; its flags only ever turn on, and `is_new` is
settled by the first write of a visitor's first day.

**The tests run on SQLite and production is Neon.** A flush that raises is
caught and logged, so a dialect mistake in the UPSERTs would have stayed
invisible until the dashboard quietly never filled.
`test_the_upserts_compile_for_postgres` compiles both statements against the
Postgres dialect without connecting to one.

Two things this leans on elsewhere. `limits._client_ip` is now public
`client_ip`: the access log needs the same answer, and two functions both
deciding which hop is the caller's is how one of them ends up trusting a
header it shouldn't. And the cleanup sweeper now starts if *either* job has
work — a deployment can keep every guest forever and still want its
visitor-day rows aged out.

No migration. Both tables are new and `bootstrap()` calls `create_all` on
existing databases too, the route `branches` took in Phase 14, so
`LATEST_VERSION` is still 64.

497 tests green, frontend lint and build clean, driven by hand against a
synthetic 90-day fixture at 1568px. The narrow-screen layout follows the
existing 720px block but is unverified: `resize_window` is ignored on a
maximized Chrome and `frame-ancestors 'none'` rules out checking it in a sized
iframe. Also repaired here: a rename in test_ratelimit_hardening.py had run
through the test names themselves, leaving `testclient_ip_*` — still collected
by pytest, which is why it passed unnoticed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DfMCsN1KBLsTqMkj5hSgrY
This commit is contained in:
parththakkar106
2026-08-22 16:24:42 +05:30
co-authored by Claude Opus 5
parent 3b9e6b3d50
commit 041f9e25f3
24 changed files with 2698 additions and 45 deletions
+38
View File
@@ -23,6 +23,7 @@ what makes it a service rather than a demo. Part 4 is the web plumbing, kept sho
- [1.8 Why there is no agent framework](#18-why-there-is-no-agent-framework)
- [Part 2 — Data and correctness](#part-2--data-and-correctness)
- [Part 3 — Production concerns](#part-3--production-concerns)
- [3.6 Counting visits](#36-counting-visits)
- [Part 4 — The web plumbing, briefly](#part-4--the-web-plumbing-briefly)
- [Part 5 — Measured results and known limitations](#part-5--measured-results-and-known-limitations)
@@ -1048,6 +1049,43 @@ Two things worth knowing about the free tier:
CI runs the backend tests, the frontend lint and build, and a Docker image build on every
push.
## 3.6 Counting visits
A hosted demo raises a question a local app never does: is anyone using it, and do they get
anywhere? The answer is an owner-only dashboard at `/analytics`, gated on
`AIDND_ANALYTICS_EMAILS` — a list kept separate from `AIDND_POWER_USERS`, since an unmetered
tester is not automatically someone who should see the traffic.
**Why it isn't a third-party script.** The CSP allows `script-src 'self'`, so a tracker would
mean loosening it; adblockers eat the popular ones, which silently biases exactly the
technical audience this project is shown to; and none of them can see the measurement that
matters here — a *turn*. The interesting funnel step is not a pageview.
**Egress is the budget.** After the 189x fix (§2.5) it would be perverse to add a feature
that reads rows per request. So counts accumulate in a process-local dict and flush every 60
seconds as UPSERTs: **a visit is a write and never a read**. Storage is a generic
`(day, metric, label) -> hits` counter plus one row per visitor per day for the funnel flags.
Every dashboard query is a `GROUP BY` that returns tens of rows regardless of the traffic
behind it, so a month costs a few kilobytes to read back. The cost of the buffer is that a
hard restart can lose up to a minute; the flusher also runs on shutdown, and on a tier that
sleeps when idle the buffer it sleeps on is empty anyway.
**The numbers are the server's, not the browser's.** The client reports one fact — which page
was viewed — and even that is normalized to a route (`/play/12` → `/play/:id`) against a
whitelist, so the page list cannot be polluted by anything a stranger posts. Everything that
means something — a turn, an adventure, a sign-up — is recorded by the code that performs it.
That also fixes a blind spot: a failed turn is an HTTP 200 with a bad ending, so a
status-code tally cannot see it, and a demo whose model has started refusing looks perfectly
healthy from outside. `turn_error` is counted where the SSE error is written.
The funnel counts **people, not clicks** — a player who starts six adventures is one person
who started an adventure — which is the entire reason the per-visitor-day table exists.
One smaller decision worth naming: error buckets are labelled by the matched *route template*,
never the requested path. That gives one bucket per endpoint instead of one per adventure id,
and — the reason it isn't merely tidier — an unmatched path is entirely attacker-chosen, so
labelling by it would let anyone mint rows.
---
# Part 4 — The web plumbing, briefly