Skip to content

Citations: store each citation as a row instead of expanding jsonb on every page load #732

Closed

Description

@gkhngyk

Summary

The Citations page downloads a brand's raw answer rows and parses them in the browser tier. Every page load, and every switch between date presets, repeats the whole job. On the largest brand in production that means 50 sequential requests carrying 65 MB of jsonb, and the work does not fit in the time available.

Extract each citation into its own row once, when the result is written. The page then reads a narrow indexed table instead of expanding jsonb on every view.

What the numbers say

scanFilteredResults in web/src/lib/actions/citations.ts pages through prompt_results in batches of 1000, selecting the citations jsonb column, and aggregates in Node.

Measured against the largest brand (51,679 answer rows, all within the last 90 days — so 90d and all scan the same set and are equally slow):

Rows scanned 51,679
Sequential requests 50
jsonb transferred 65 MB
Citation entries after expansion 679,304
Distinct domains 19,616

Moving the same aggregation into Postgres does not fix it. Two shapes, both measured warm:

  • realistic (domain plus per-domain answer counts): 9.9 s, spilling 168 MB to disk
  • simplest possible (domain and a count, hash aggregate, no spill): 4.6 s

The statement timeout is 8 s. The plan shows where the time goes — Nested Loop ... actual time=5.190..4368.993 — expanding 51,679 jsonb documents into 679,304 rows and running a regex on each to pull the host out of the URL. The cost is the expansion, not the transfer, and today it is paid on every single page view.

Deep offset paging adds to it: fetching the 46th page touches 47,542 buffers because OFFSET reads and discards everything before it.

Why the data cannot be read any other way today

No column holds the cited sources. citation_count counts only the brand's own citations — 4,535 against 679,304 entries actually present in the array for that brand. Competitor and neutral domains exist solely inside the jsonb. That is why the page downloads everything: there is no cheaper path to them.

Proposed change

Write one row per citation at insert time:

prompt_result_id, brand_id, prompt_id, created_at, model, region, domain, url

The domain is resolved once, on write, instead of by regex on every read. Reads become plain indexed scans over narrow rows — no jsonb, no TOAST, no regex.

What this buys:

  • No domain is lost. Every one of the 679,304 entries stays a row. No rollup grain to choose, no long tail collapsed into an "other" bucket.
  • No staleness. The rows are written in the same path that writes the result, so a newly tracked prompt appears immediately. This is not a nightly job.
  • The 50,000 row ceiling goes away. CITATIONS_SCAN_MAX_ROWS currently truncates the largest brand at 50,000 of its 51,679 rows, silently — the page reports numbers that are quietly short.
  • Server-side ranking becomes possible. Ordering by count and returning the top N is cheap once the database can rank, so the response can shrink from 19,616 rows to whatever the page shows.

Cost and risk

Storage ~265 MB across all brands (~2.2M citations)
Write cost ~13 small inserts per result row
Backfill Required for history — 177k source rows, batched

Both write paths must be hooked. prompt_results is written from server/src/workers/tracking-worker.js (synchronous mode) and server/src/lib/cloro-result-handler.js (webhook mode). Wiring one and missing the other leaves the table silently behind, which is the failure mode most worth guarding against in review.

The citations jsonb stays in place, so the data lives in two shapes for now. Removing it later would reclaim the bulk of the table's 721 MB of TOAST, but that is a separate decision and not part of this.

The expected read time is a few hundred milliseconds. That is an estimate; what is measured is the current 4.6–9.9 s.

Scope

  • Migration for the new table and its indexes
  • Write hooks in both result paths
  • An RPC that aggregates it for the overview
  • Read side of web/src/lib/actions/citations.ts, replacing scanFilteredResults
  • Backfill script for existing rows

The page UI does not change.

How to test

  1. Open Citations for the largest brand and confirm domain counts match what the current implementation reports, allowing for the rows the 50,000 ceiling drops today.
  2. Switch between 90d and all and confirm both return promptly.
  3. Run a tracking cycle and confirm new citations appear without a second page load.
  4. Trigger a manual check for a single prompt and confirm the same, through the webhook path as well as the synchronous one.
  5. Confirm the backfill is restartable and does not double-write rows it already covered.

Activity

  1. self-assigned this
    on Aug 17, 2026
  2. added
    enhancement
    citations
    on Aug 17, 2026
  3. gkhngyk commented on Aug 17, 2026

    @gkhngyk
    ContributorAuthor

    Sequencing note: this should land after #657 (and its companion #655), which are already assigned.

    Both touch web/src/lib/actions/citations.ts — #657 moves the source-scope filters client-side, this one removes scanFilteredResults entirely. Doing them in parallel would conflict.

    #657 is also the smaller change and its own body lists this work as follow-up ("push the whole aggregation into a Postgres function so only aggregates cross the wire"), so the order is natural rather than merely convenient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

citationsenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions