Repository navigation
feat(citations): write citations as rows alongside each answer (#732 phase 1) - #737
Merged
Merged
Conversation
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
This was referenced Aug 19, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.citationsholds 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:
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 —resultsCitingand the URL detail view both need it.Both write paths are wired
prompt_resultsis written from two places and both are covered here:server/src/workers/tracking-worker.js— synchronous runsserver/src/lib/cloro-result-handler.js— the Cloro webhookWiring 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_atback 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
extractDomainis a port of the page's ownextractHostname, fallback included. The first version dropped anythingnew 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.jswalks 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_atalone 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_citationsmirrorsprompt_resultsandprompt_result_shopping_cards: org members select their own rows, the service role writes.citation_urlsis 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 asSECURITY DEFINERafter 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 featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow 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-migrationlabel automatically.00058_prompt_result_citations.sql.prompt_result_citationsgains rows for the new answers, through the webhook path as well as the synchronous one.node src/scripts/backfill-citations.jsfromserver/, and confirm it is restartable — interrupt it, start it again, and confirm no duplicates and no gap.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromserver/)yarn format:checkpasses (run fromserver/)Server suite passes: 299 tests, 12 of them new.
supabase/schema.sqlregenerated. Every migration in the repo was parsed with Postgres's own grammar (pglast) — 57 files, 0 failures, the new one 15 statements. Noweb/files are touched.