Skip to content

feat(traffic): take a journey's pageviews and conversions from the AI Traffic snippet (CE-017, part 1: server) - #1527

Merged
gkhngyk merged 10 commits into
ansvisor:mainfrom
cihan-gyk:feature/ce-017-conversion-events
Oct 26, 2026
Merged

gkhngyk merged 10 commits into
ansvisor:mainfrom
cihan-gyk:feature/ce-017-conversion-events

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

CE-017, part 1 of 6: server. Conversion tracking from the AI Traffic snippet (Content Editor spec v2, §7b): follow a visitor who came from an AI assistant through the site to a goal, so the Live page tab can show what a page earns from AI visits and the journeys that got there.

The owner approved these choices:

  • Off by default, per brand. A brand that leaves conversions off gets nothing new. The snippet keeps nothing in the browser, as the docs promise today.
  • Consent first. With conversions on, the snippet (part 2) keeps a random first-party visitor id only for AI-referred visitors, and in the default wait mode only after the site's consent (its banner, or Google Consent Mode).
  • No personal data. No IP, name or email. Pages are stored without their query string or fragment, so a thank-you page's ?email=… never gets in.

This PR is server only:

Migration 00286_ai_traffic_conversions.sql

  • brands.conversions_enabled (default false) and brands.conversions_consent (wait | always, default wait).
  • ai_traffic_events: a journey's pageviews and conversions. Each row has:
    • the visitor id;
    • the page (origin + path);
    • for a conversion: goal (signup, demo, order, booking, newsletter, custom), label, origin (call, form, shopify), value, currency, units, order ref;
    • the first AI visit it's credited to (source, landing page, time).
  • An order ref is unique per visitor (a partial unique index), so an order the Shopify pixel sends twice counts once. It isn't unique per brand: the tracking code is public, and an order id sent first by someone else must not shut the real one out.
  • Members read their brands' events (RLS); only the server writes them.

POST /track/:code

  • Takes two new kinds: pv (a journey pageview) and cv (a conversion).
  • They're read with a zod schema (lib/traffic-events.js).
  • A label (a form's or call's name) and an order ref keep only what such a name is made of. Anything that looks like an email or a phone number is dropped.
  • A browser clock running ahead never dates the first visit after the event.
  • They're stored only while the brand has conversions on.
  • They're credited first-touch to an AI visit within 30 days, from a source on the AI list. Anything that can't be credited is dropped, not stored as unattributed.
  • The brand's setting is read only for an event that can be stored, in its own query. A server deployed before the migration fails only these events, never the visits. A test covers that.
  • Visits (k absent) and soft-404 marks (k: "nf") work exactly as before.

The next parts: the snippet (visitor id, journey pages, forms, ansvisor('conversion', …), consent, GTM), the Shopify pixel, the Settings section, the Live page tab and Plan strip, and docs.

Related issue

Content Editor spec v2, CE-017 (§7b points 31–35).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00286 and set conversions_enabled = true on a test brand.
  2. Send a beacon to POST /track/<tracking_code> (body as text/plain):
    {"k":"cv","id":"Vq3xT0mZ8kLp2RwYbN5sQa","u":"https://site.example/[email protected]","f":{"s":"chatgpt.com","u":"https://site.example/blog","at":<now ms>},"g":"demo","o":"form"}
  3. A row lands in ai_traffic_events with url = https://site.example/thanks (no query string) and first_source = chatgpt.com.
  4. With conversions off, or with f.s not an AI source, nothing is stored. A second cv with the same id and ref adds no row.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • npm run lint passes (run from server/)
  • npm test passes (run from server/)
  • Migration added as a new file; bash supabase/build-schema.sh run and supabase/schema.sql included
  • Changes are focused — one concern per PR

Migration applied on the dev database. Its constraints were tried there in a rolled-back transaction: a second insert of the same order is refused, and a pageview with a goal is refused. A pre-push review ran; its fixes are the last commit (per-visitor order index, label and order ref checks, check before the brand read, a test for a server before the migration).

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 26, 2026 02:16
… Traffic snippet, for brands with conversions on (CE-017, part 1: server)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rder id sent first by anyone can't shut the real one out; keep no label or order ref that looks personal; check an event before reading the brand (pre-push review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes.

What I checked:

  • Visits are untouched. pv and cv branch off after the brand lookup and before the address is read. A journey event never computes or stores an IP, a visitor key, a country or a user agent. A body without k, or with k: "nf", takes the old path. Today's snippet never sends pv or cv, so deploying this changes nothing until part 2 ships.
  • Who can write what.
    • The brand comes from the tracking code alone, so an event lands only on the brand whose code it carries.
    • The answer is 204 whether the event was stored or not, so it doesn't tell anyone whether a brand has conversions on.
    • With conversions off, nothing is stored.
    • A server running before 00286 fails only these events and logs them. Visits are still stored (tested).
  • The body.
    • It's read with a zod schema, and unknown keys are dropped. The visitor id must match [A-Za-z0-9_-]{16,64}. Goals and origins come from fixed lists.
    • Value is 0 to 1e9, which fits numeric(14,2). Units are 0 to 100,000. A currency is kept only with a value, and only as three letters.
    • A page, and the first visit's landing page, keep only their origin and path. Sign-in details go with the origin.
    • A label is dropped if it has an @, a +, brackets or a run of seven digits.
    • The source must be on the AI list, and the first visit must be within 30 days and not in the future. Anything else is dropped before the brand is read.
    • The beacon body is capped at 64 kb. The 60-a-minute limit per address covers these events too.
  • Logs. A failed insert logs only the database's message, never the row. An order sent again (23505) isn't logged.
  • 00286.
    • RLS is on. anon and authenticated lose the default grants, authenticated gets select back, and service_role writes. The one policy is the same membership read as ai_traffic_logs's.
    • Turning conversions on is an update to brands, which RLS keeps to admins and managers.
    • The checks match the server's bounds, and the kind check keeps goal, origin and order ref off pageviews.
    • It's safe to run again (if not exists, drop policy if exists). The two new brands columns have constant defaults, so adding them only checks a small table once.
    • A write reads only the brand, by idx_brands_tracking_code and by primary key. The journey index is the one 00287 and 00288 read a visitor's pages through.
    • schema.sql is the build script's output.
  • Merge. It's built on current main and merges cleanly. Once #1514 lands, only schema.sql conflicts.

Before merge:

  1. server/src/lib/traffic-events.js:56-64: the query string and the fragment go, but the path is kept as is, and a path can hold an email (/unsubscribe/[email protected], /account/ann%40example.com). The Live page tab would then show it in a journey.
    • Fix: give the path the same check as the label. Replace any segment that holds an @, raw or as %40, with a fixed placeholder. The page still counts, and the address stays out.
    • That covers first_url too. Add a test.
  2. server/src/routes/traffic.js:231-248: beyond the per-address limit, nothing bounds how many rows one visitor id, or one tracking code, can store. Tighten that, so the table and the journey reads (00287, 00288) stay bounded whatever a sender does:
    • Per visitor id: skip a pageview once the visitor already has a few hundred in the attribution window, and keep a visitor's conversions to a few a day. The journey index answers both with a short limited read.
    • Per tracking code: add a limiter for pv and cv, keyed by the code, and sized well above a big shop's AI pageviews.
    • Add tests.

Follow-ups:
3. server/src/lib/traffic-events.js:79-83 and :123: order_ref is only ever compared (the unique index), and nothing reads it back.

  • Fix: store a hash of it (for example sha256 of the brand id and the ref) instead of the ref itself. It still fits the 128-character check.
  • Then neither a checkout token nor a number that isn't an order is ever kept as is. Part 3's pixel sends the checkout token when Shopify gives no order id.
  1. supabase/migrations/00286_ai_traffic_conversions.sql:70-71: ai_traffic_events_brand_time has no reader in this stack, because 00287 adds its own partial index for conversions. Every pageview still pays for it. Nothing deletes events either, as with visits.
    • Fix: drop the index, or keep it for a sweep that deletes events older than the longest window the reads use (366 days in 00287). Say the period in the docs.

cihan-gyk and others added 3 commits October 26, 2026 09:36
…id and one tracking code can store, keep an order's id only as a hash, and drop an index nothing reads (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… journey's reads compare keys instead of working each address out again (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se that ran 00286 before them, and keep a handle such as /@acme in a path: only an email goes (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Thanks, all four are in (fb41530).

Before merge

  1. No email in a path. eventUrl stores a path segment that holds an @, raw or as %40 (any case), as [email]. The page still counts. It reads first_url the same way. Tests: /unsubscribe/[email protected], /account/ann%40example.com/orders, and an upper-case %40.
  2. Bounds.
    • Per visitor id: storeEvent reads the visitor's earlier events of the same kind through the journey index, with a limited read, and stores no more past VISITOR_LIMITS: 300 pageviews in the 30-day window and 10 conversions a day.
    • Per tracking code: journeyEventLimiter allows 3,000 a minute, keyed by the code, beside the 60 per address. It counts only pv and cv; visits skip it. Past the limit, events are dropped with a 204, as the address limiter does.
    • Tests: the limit read's filters and both limits, plus isJourneyBeacon and journeyEventKey.

Follow-ups, done here
3. order_ref is now sha256(brand id + ":" + the shop's id): 64 hex characters, compared only and never kept as it is.
4. ai_traffic_events_brand_time is gone from 00286, and dropped on the dev database.

One more, for #1530/#1531's reads. Each event now stores its pages' keys as generated columns: page_key and first_key = lower(normalize_page_path(...)). They are made once on insert, so the journey reads compare keys instead of decoding each address per read. This is what makes the bounded reads in #1530/#1531 cheap; the timing is there.

00286 edited in place. It isn't merged and isn't on prod, so I edited it rather than adding a migration, and re-applied it on the dev database. In case a database ran the older 00286, it now also adds page_key and first_key with add column if not exists, and drops ai_traffic_events_brand_time with if exists, so running it again brings that database up to date.

The path rule replaces only a segment shaped like an email (a name, an @ or %40, then a domain). A handle such as /@acme/post keeps its key, so its page still matches on the Live page tab.

Server: npm run format, npm run lint (clean), npm test: 2,763 passed (1 skipped as on main). 00286 is re-applied on the dev database.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes.

What I checked:

  • Earlier items.
    1. Done, with one change to the new check (item 1 below) (6c089db, fb41530).
      • eventUrl stores a path segment that holds an email, raw or as %40 in any case, as [email]. The page still counts, and first_url is read the same way.
      • A handle such as /@acme/post keeps its segment, so its page still matches on the Live page tab.
      • Tests cover the raw, encoded and upper-case forms, a handle, and first_url.
    2. Done (6c089db).
      • Per visitor id. storeEvent (routes/traffic.js:235) reads the visitor's earlier events of the same kind through ai_traffic_events_journey, limited to the cap. It stores no more past 300 pageviews in the 30-day window or 10 conversions a day. kind isn't in the index, so the read walks the visitor's rows in the window, and the caps keep those to a few hundred. Two events at once can pass the cap by one, which is harmless.
      • Per tracking code. journeyEventLimiter (rate-limiter.js:205) allows 3,000 a minute per code. It counts only pv and cv, after the 64 KB read, and answers 204 past the cap. A sender can use up a brand's minute, and the brand's real events for that minute are then dropped. That's the trade a per-code cap makes, and the per-address limit still applies to every sender.
      • Tests cover the read's filters, both caps, isJourneyBeacon and journeyEventKey.
    3. Done. order_ref is sha256(brand id + ":" + the shop's id), 64 hex characters, inside the 128-character check. The unique index compares hashes, and nothing reads the column back. #1532's docs don't describe it as the raw id.
    4. Done. The index is gone from the create, and drop index if exists removes it from a database that ran the older file. With the index gone, keeping events like visits is fine.
  • The page keys (934227c).
    • page_key and first_key are lower(normalize_page_path(...)), stored on insert. normalize_page_path is immutable and unchanged since 00075.
    • It never raises: url_decode_safe returns the input when it can't decode it. So an odd address never fails an insert.
    • The keys are made from the stored address, after the [email] swap.
  • 00286 edited in place.
    • It isn't on prod, so editing it is fine.
    • On a fresh run, the add column if not exists is a no-op. On a database that ran the older file, the same run adds the keys and drops the index.
    • schema.sql mirrors it, and CI's schema check passes.
  • Merge.
    • There are no merge commits. On 4085418 (with #1533), it merges cleanly.
    • After the merge, a beacon goes through the per-address limiter, then the 64 KB text read for every content type, then the per-code limiter, then the handler. isJourneyBeacon always gets the string. #1533's two tests use the same mocks, and the mocks now include journeyEventLimiter.
    • On today's main (with #1514 and #1515), only schema.sql conflicts.
    • CI passes at fb41530.
  • Before the API is deployed. This PR is server and migration only, so users see no change. After the deploy, nothing sends pv or cv until part 2 ships.

Before merge:

  1. server/src/lib/traffic-events.js:68 and :81-84: replace EMAIL_IN_SEGMENT with a single pass over each segment. The check runs on any sender's address, up to 16 KB.
    • For example:
      function holdsEmail(segment) {
        let text;
        try {
          text = decodeURIComponent(segment);
        } catch {
          text = segment.replace(/%40/gi, '@'); // a malformed escape elsewhere in it
        }
        const at = text.indexOf('@', 1); // an @ at the start is a handle
        return at > 0 && text.indexOf('.', at + 2) > 0;
      }
    • It keeps /@acme and /@acme.dev, and catches everything the pattern catches.
    • Decoding first also catches an encoded dot (ann%40example%2Ecom). Today the pattern misses that segment, and page_key stores it decoded as [email protected].
    • Tests: keep the current cases, and add ann%40example%2Ecom. Add a 16 KB path that's checked in a few milliseconds.

…ersion-events

# Conflicts:
#	supabase/schema.sql
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Merged main forward (995fe1b). The only conflict was supabase/schema.sql (main gained 00285); I rebuilt it with build-schema.sh. 00286 is still this PR's own migration.

Checks after the merge:

cihan-gyk and others added 2 commits October 26, 2026 14:48
…irst, so a long address reads fast and an encoded dot is caught (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Done (879538c): holdsEmail replaces EMAIL_IN_SEGMENT, as you wrote it.

  • It makes one pass over the segment, decoded first; a malformed escape elsewhere still has its %40 read.
  • An @ at the start is a handle: /@acme and /@acme.dev keep their segment.
  • New tests:
    • ann%40example%2Ecom (the encoded dot);
    • a malformed escape;
    • three 16 KB segments, read in under 50 ms together. The old pattern took 444 ms on one 16 KB segment here.

The fix is merged up through #1528–#1531.

Checks: server format and lint clean, 224 test files, 2,795 passed, 3 skipped. At #1531: web 427 files, 4,020 passed, build OK, and server tests passed.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs changes.

What I checked:

  • Earlier item.
    1. Partly (d4a48f6, 879538c). holdsEmail (server/src/lib/traffic-events.js:73-83) replaces EMAIL_IN_SEGMENT.
      • It decodes the segment first. When an escape is malformed, it reads the segment's %40 and %2E as @ and . (:79).
      • An @ at the start is a handle, so /@acme and /@acme.dev keep their segment (traffic-events.test.js:64-65).
      • It catches ann%40example%2Ecom, and also the same segment with a malformed escape after it (:29, :60).
      • It catches every segment the old pattern caught:
        • The pattern needed a character before the @ and one between the @ and a dot. at > 0 and at + 2 still ask for both, and decoding never makes a part empty.
        • I ran 200,000 random segments built from @, dots, %40, %2E, and valid and malformed escapes. The new check missed none that the pattern caught.
      • The work grows linearly with the input: one decode (or two replaces), then two indexOf calls. A 16 KB segment takes about 0.02 ms. The old pattern took about 420 ms on the same segment.
      • One cost is left (item 1 below).
  • The rest of the path. I read every regex and loop a beacon meets on /track/:code (routes/traffic.js, traffic-events.js, rate-limiter.js, ai-sources.js):
    • The visitor id's pattern is anchored, with one character class.
    • eventLabel and orderRef read at most 80 and 200 characters. Their patterns are anchored, with one class each.
    • classifyAiSource compares at most 255 characters with the source list.
    • landingMedium walks a query string of at most 2,048 characters.
    • The body is parsed twice, by isJourneyBeacon and by the route. Each parse is linear in its 64 KB.
    • None of these does more than linear work.
  • 00286 hasn't changed since round 31: the file is the same at fb41530 and 879538c.
  • Merge of main (995fe1b).
    • Re-merging its parents (fb41530 and 4efa150) gives the same tree, apart from supabase/schema.sql, the one conflict.
    • The committed schema.sql is exactly what build-schema.sh builds from the migrations at 995fe1b: 00285 from main, then 00286. The same holds at 879538c. I rebuilt it from the files at each commit, without running the script.
    • The PR merges cleanly on 4efa150. On today's main (a443462, with 00289), only schema.sql conflicts.
    • CI passes at 879538c.
  • Before the API is deployed. This PR is server and migration only, so users see no change.

Before merge:

  1. server/src/lib/traffic-events.js:75-80: bound the work on a long address that has many segments.
    • decodeURIComponent throws on a segment with a malformed escape, and a throw costs far more than the scan. On an address split into many short segments, those throws add up, and an event has two addresses.
    • Read the encoded @ and dot directly, with no decode. The answer is the same for every segment: an escape always decodes to at least one character, and only %40 and %2E decode to an @ or a dot.
      export function holdsEmail(segment) {
        // Its @ and dots, raw or encoded: no other escape makes either.
        const text = segment.replace(/%40/gi, '@').replace(/%2e/gi, '.');
        const at = text.indexOf('@', 1); // an @ at the start is a handle
        return at > 0 && text.indexOf('.', at + 2) > 0;
      }
    • On 200,000 random segments, it gives the current check's answer every time, and its time stays linear in the address.
    • Tests: keep the current cases. Add a timing test for eventUrl on a 16 KB address of many short segments with malformed escapes: it should finish within a few milliseconds.

…ng it, so an address of many segments with malformed escapes reads in linear time (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Done (978e51a): holdsEmail now reads the segment's %40 and %2E as they are, with no decode, as you wrote it.

New test: eventUrl on a 16 KB address of 3,200 short segments with malformed escapes, plus an encoded email first, finishes in under 8 ms. Here, a decode per segment took about 11 ms for that address, and the new read takes under 1 ms. The earlier cases stay.

Checks: server format and lint clean; 224 test files, 2,796 passed, 3 skipped.

I haven't merged main forward while your merge run was going. The conflict is schema.sql only (00289 and 00290 on main).

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, with a follow-up.

What I checked:

  • Round 32's before-merge item: done (978e51a). holdsEmail reads the segment's %40 and %2E as they are, with no decode, so a malformed escape costs nothing and the read is linear in the address. Its answer is the decoded one's for every segment, as the comment says.
  • Tests. The earlier cases stay, including the encoded dot and the malformed escape, and a 16 KB address of 3,200 short segments with malformed escapes is read with its email swapped for [email].
  • Nothing else changed in the commit: traffic-events.js and its test.
  • Migration 00286 is unchanged; it's applied on prod just before this merge.
  • Merge. On today's main only schema.sql conflicts; the merge commit rebuilds it with build-schema.sh, putting 00286 after 00290. The combined tree with the rest of the chain passes server and web tests, tsc, lint, Prettier and the schema build.

Follow-up:

  1. traffic-events.test.js: the new timing test's limit is 8 ms. On a busy CI runner that can fail with nothing wrong. A limit of 100 ms still catches the decode-per-segment shape on a longer address, or compare against a plain address of the same length.

@gkhngyk
gkhngyk merged commit 55e6af3 into ansvisor:main Oct 26, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants