Skip to content

feat(citations): write citations as rows alongside each answer (#732 phase 1) - #737

Merged
gkhngyk merged 1 commit into
mainfrom
feature/732-citation-rows-phase1
Aug 18, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
feature/732-citation-rows-phase1

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Summary

Phase 1 of #732: the tables and the write path. Nothing reads them yet — the Citations page keeps using the jsonb until phase 2, so the two can be compared against each other before anything switches over.

prompt_results.citations holds the provider's array as jsonb, which is cheap to store and expensive to read. Every page load expands it again: on the largest brand, 51,679 answers become 679,304 citation entries, and pulling the host out of each URL accounts for 4.4s of the 4.6s a plain aggregate over that window takes — past the 8s statement timeout as soon as anything else is asked of it. The page works around this by paging the raw rows out to the app tier instead: 50 sequential requests carrying 65 MB of jsonb, capped at 50,000 rows, which silently truncates that same brand at its 51,679.

Expanding once at write time turns that into an ordinary indexed read.

Two tables, because the obvious shape does not fit

The issue estimated ~265 MB for one row per citation. That was wrong — it assumed 120 bytes a row against real URLs averaging 92 bytes and titles 63. Measured properly:

Shape Heap
One row per citation, url + title inline 513 MB
Dictionary + narrow fact table 262 MB

There are 2,023,979 citation entries across the database but only 449,559 distinct URLs — the expensive part repeats 4.5 times on average. With the database already at 1.1 GB on a 2 GB instance, the inline shape would push it to roughly 1.76 GB and defeat the point of the change, which is to make the working set fit in cache.

A daily rollup was measured as the alternative and rejected: (brand, day, url) compresses 2.02M rows to 1.48M, a 27% saving that does not pay for losing per-answer identity — resultsCiting and the URL detail view both need it.

Both write paths are wired

prompt_results is written from two places and both are covered here:

  • server/src/workers/tracking-worker.js — synchronous runs
  • server/src/lib/cloro-result-handler.js — the Cloro webhook

Wiring one and missing the other is what this design is most exposed to: the table would simply be short, with nothing reporting it. Worth a second look in review.

Both calls are best-effort. The answer is already stored and the jsonb column still holds the same data, so a failure costs a backfill rather than the result. Both now read created_at back from the insert rather than stamping it in app code, so the citation rows carry the same timestamp as their parent instead of one a round trip later.

A bug worth calling out

extractDomain is a port of the page's own extractHostname, fallback included. The first version dropped anything new URL() could not parse; the original recovers a hostname-like token from strings with no scheme.

That is not hypothetical: 252 of the 2,023,979 citations in production have no scheme, and the page counts them today. A writer that dropped them would have quietly lowered every figure the moment phase 2 switched the page over — the kind of regression that looks like a real change in the data. Parity with the original was checked across 22 URL shapes, including ports, credentials, IPv6, IDN, and bare hostnames.

Backfill

server/src/scripts/backfill-citations.js walks by keyset on (created_at, id) rather than OFFSET, so it is restartable — an interrupted run is simply started again. It pauses between small batches on purpose: it runs against the same instance serving the dashboard, and finishing in twenty minutes without evicting the cache beats finishing in five.

Ordering on created_at alone would be ambiguous, since a nightly run writes thousands of answers inside the same second and a cursor that cannot separate them either repeats a page or skips one.

Row level security

prompt_result_citations mirrors prompt_results and prompt_result_shopping_cards: org members select their own rows, the service role writes.

citation_urls is deliberately different. It is a cross-tenant dictionary with no brand column, so no row-level rule can express who may read a given URL — the answer lives in the join. RLS is enabled with no select policy at all, so direct reads are denied to everyone but the service role, and the phase 2 aggregate will reach it as SECURITY DEFINER after checking the caller owns the brand. A permissive policy here would let any authenticated user enumerate every URL ever cited for every customer.

Related issue

Refs #732 — deliberately not Closes, since the page still reads jsonb until phase 2.

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

The migration has not been applied to the hosted database — that is a deliberate step for the maintainer, and this PR should pick up the needs-migration label automatically.

  1. Apply 00058_prompt_result_citations.sql.
  2. Run a tracking cycle and confirm prompt_result_citations gains rows for the new answers, through the webhook path as well as the synchronous one.
  3. Run node src/scripts/backfill-citations.js from server/, and confirm it is restartable — interrupt it, start it again, and confirm no duplicates and no gap.
  4. Compare the two sources for a brand, which must agree exactly:
    select (select count(*) from prompt_result_citations where brand_id = :b) as rows,
           (select sum(jsonb_array_length(coalesce(citations,'[]'::jsonb)))
              from prompt_results where brand_id = :b) as jsonb_entries;
    A small shortfall is expected and explainable: entries whose URL yields no host at all are not stored.
  5. Confirm the Citations page is unchanged, since nothing reads the new tables yet.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from server/)
  • yarn format:check passes (run from server/)
  • Changes are focused — one concern per PR

Server suite passes: 299 tests, 12 of them new. supabase/schema.sql regenerated. Every migration in the repo was parsed with Postgres's own grammar (pglast) — 57 files, 0 failures, the new one 15 statements. No web/ files are touched.

Phase 1 of #732: the tables and the write path. Nothing reads them yet.

prompt_results.citations keeps the provider's array as jsonb, which is cheap
to store and expensive to read. Every Citations page load expands it again:
on the largest brand, 51,679 answers become 679,304 citation entries, and
pulling the host out of each URL accounts for 4.4s of the 4.6s a plain
aggregate over that window takes — past the 8s statement timeout as soon as
anything else is asked of it. The page works around this by paging the raw
rows out to the app tier instead: 50 sequential requests carrying 65 MB of
jsonb, capped at 50,000 rows, which silently truncates that same brand at
51,679.

Expanding once at write time turns that into an ordinary indexed read.

Two tables rather than one, because the obvious shape does not fit. There are
2,023,979 citation entries across the database but only 449,559 distinct URLs
— the expensive part (url ~92 bytes, title ~63) repeats 4.5 times on average.
One row per citation with the text inline measures 513 MB of heap against
262 MB split into a dictionary and a narrow fact table, and the instance holds
2 GB of RAM for a database already at 1.1 GB. A daily rollup was measured as
the alternative and rejected: it compresses 2.02M rows to 1.48M, which does
not pay for losing per-answer identity.

Both write paths are covered — the tracking worker for synchronous runs and
the Cloro webhook handler for asynchronous ones. Wiring one and missing the
other is the failure this design is most exposed to, since the table would
simply be short without anything reporting it. Both are best-effort: the
answer is already stored and the jsonb column still holds the same data, so
anything missed costs a backfill rather than the result.

extractDomain is a port of the page's own extractHostname, fallback included.
252 of the 2,023,979 citations in production arrive with no scheme at all, and
the page counts them today by recovering a hostname-like token; a writer that
dropped them would quietly lower every figure the moment the page switched
over. Parity was checked against the original across 22 URL shapes.

The backfill walks by keyset on (created_at, id) rather than OFFSET, so it is
restartable, and pauses between small batches: it runs against the same
instance that serves the dashboard, and finishing in twenty minutes without
evicting the cache beats finishing in five.

Refs #732
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Aug 18, 2026
@gkhngyk
gkhngyk merged commit 7d583ab into main Aug 18, 2026
6 checks passed
@gkhngyk
gkhngyk deleted the feature/732-citation-rows-phase1 branch August 18, 2026 21:18
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.

1 participant