Skip to content

chore(server): clean ChatGPT's entity tags out of stored answers and recount them, with backfill-mention-counts.js --entity-markup - #1551

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:chore/entity-markup-backfill
Oct 27, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:chore/entity-markup-backfill

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

#1097 fixed ChatGPT's <Entity … value="X" disambig="…"/> tags going forward: answers are cleaned at ingest, matching and display. Answers saved before it still hold the raw tags in prompt_results.response, and their mentions were counted from the tags' attributes:

  • a competitor named only in a disambig counted as mentioned;
  • the extra names shifted every position;
  • a brand named only in a disambig had its sentiment read.

This adds the backfill #1097 left for later, as a mode of the existing recount script. Only the maintainer runs it on prod.

node src/scripts/backfill-mention-counts.js --entity-markup [--brand <id>] [--dry-run]

What it does

  • Scope: every brand of an active or trialing organization (or --brand), and only its answers that still hold a tag.
  • How it finds them: it lists their ids first, one UTC day at a time on the brand and date index, so each answer's text is read once. That happens before any write, so a cleaned answer leaving the filter can't shift a page.
  • What it rewrites for those answers:
  • Sentiment:
    • an answer that no longer names the brand is set to 'neutral', as cloro-result-handler.js saves one;
    • one that still names it keeps its sentiment, and nothing is re-analysed.
  • Batches: rows are read 100 ids a request (selectInChunks) and written 20 at a time, as before.
  • Re-runs: idempotent, and a cleaned answer leaves the filter, so a stopped run can just be run again.
  • At the end it prints each changed brand's refreshes. Citations is new to the list:
    • Insights: backfill-insights-daily.js;
    • Mentions: backfill-mentions-daily.js, which rebuilds the answers' terms, their rollups and Perception's snapshots;
    • Citations: backfill-citations-daily.js (we_mention, comp_present).

Before running it on prod, keep a copy. Nothing else in the database holds the text with its tags.

  • Put it in a schema of its own. It has no grants, unlike a table made by hand in public, where row level security is off.
  • Fill it a week of answers at a time on the date index.
  • Drop it once the run is checked.
create schema if not exists backfill_backup;
create table backfill_backup.prompt_results_entity_markup as
  select id, brand_id, created_at, response, sentiment, mention_count, visibility_score,
         mention_position, mentioned_entity_count, competitor_mentions
  from public.prompt_results
  where false;
-- once per week of answers, oldest first:
insert into backfill_backup.prompt_results_entity_markup
  select id, brand_id, created_at, response, sentiment, mention_count, visibility_score,
         mention_position, mentioned_entity_count, competitor_mentions
  from public.prompt_results
  where created_at >= '<day>' and created_at < '<day + 7>'
    and response like '%<Entity%';

To put it back, in parts as it was filled: one brand at a time (or a week at a time on b.created_at). Then run the three refreshes it printed again:

update public.prompt_results p
  set response = b.response, sentiment = b.sentiment, mention_count = b.mention_count,
      visibility_score = b.visibility_score, mention_position = b.mention_position,
      mentioned_entity_count = b.mentioned_entity_count,
      competitor_mentions = b.competitor_mentions
  from backfill_backup.prompt_results_entity_markup b
  where p.id = b.id and b.brand_id = '<id>';

Once the run is checked, drop the copy on its own, never with the restore:

drop schema backfill_backup cascade;

The same block is in the script's header.

As it runs:

  • A brand's domains and competitors are read with retries, and a read that still fails stops the run. Counted without them, a cleaned answer would lose its domain mentions or its competitors, and couldn't be revisited. The default mode's scope read stops the same way, rather than dropping a brand without a word.
  • Each changed brand's three refreshes are printed as soon as its rows are written, and again at the end. A run stopped later and run again finds that brand clean, so its commands aren't lost.
  • A dropped connection, which supabase-js returns as an error with no code, is retried like a thrown one.
  • A dry run prints up to three rows per brand, before → after: mentions, position, competitors named, whether the text is cleaned, and whether the sentiment moves. It also prints the brand's count of sentiment changes.

Refactor: the recount moved from the script into server/src/lib/mention-recount.js (recountRow) so it can be tested. The default mode (#871) counts exactly as before, with two changes:

  • an answer that turns out not to name the brand is now 'neutral' there too;
  • it also prints the Mentions and Citations refreshes.

Notes:

  • Rows are counted by today's parser, so the tagged ones also pick up its other changes since they were saved. Untagged answers from the same days aren't touched.

Related issue

Follow-up to #1097 (no issue).

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. Run the tests:
    cd server && npx vitest run src/lib/mention-recount.test.js
  2. On a database with tagged answers, run a dry run for one brand; it changes nothing:
    cd server && node src/scripts/backfill-mention-counts.js --entity-markup --brand <id> --dry-run
    Then run it without --dry-run. Run it again: it finds nothing left.

Checklist

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

Server checks: format and lint clean; 226 test files, 2,886 passed, 3 skipped. The dev DB has no tagged answers (only prod does), so the script wasn't run against data here.

Tests (mention-recount.test.js):

  • a tagged answer is cleaned and recounted: the competitor only in disambig drops out, positions close up, and a second run changes nothing;
  • without the cleanup, the text stays;
  • an answer already counted right writes nothing;
  • a tag without a value stays;
  • a gone competitor's entry is kept;
  • an answer that no longer names the brand is neutral, and its score drops the positive lift.

Pre-push review

A review agent read the change before the push. Fixed from it:

  • the stale sentiment;
  • the Citations refresh missing from the list;
  • the id walk re-reading a busy week's text (now a day at a time);
  • a 250-uuid URL (now 100 a request);
  • the backup step (now in the script and here).

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 26, 2026 17:13
…recount them, with backfill-mention-counts.js --entity-markup

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, list tagged answers a day at a time, fetch them 100 ids a request, and print the Citations refresh too (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: one fix before merge, to the backup step in the script's header and the description. The script does what it says. The rest are follow-ups.

What I checked:

  • What it writes. With --entity-markup, it touches only rows whose response still holds <Entity. In each one it writes:

    • response, only when a tag came out;
    • sentiment, only when it moves to 'neutral';
    • mention_count, visibility_score, mention_position and mentioned_entity_count;
    • the three counts of each existing competitor_mentions entry.

    Citations, citation_count, shopping cards and search queries aren't touched. A row's values all go in one update, so a stop never leaves a row half written. There are no triggers on prompt_results.

  • Same cleaning and counting as ingest.

    • The text is stripEntityMarkup of the stored answer. That's the function parseScraperResponse has applied since #1097, and the stored answer is what Cloro sent before then. So a cleaned answer reads like one saved today.
    • The counts come from parseResponse, with the brand's name and domains and each competitor's id, name, domain, loaded the way the callback and the tracking worker load them.
    • The sentiment rule matches cloro-result-handler.js:51-55: countBrandMentions and parseResponse count the brand the same way.
    • A person's sentiment correction stays where the answer still names the brand. A correction on an answer that named the brand only inside a tag goes back to neutral, and the answer leaves the Mentions table.
  • What can't be rebuilt. The tags' other attributes (disambig, category) go, as they have at ingest since #1097. Nothing else in the database keeps the original text, so the copy is the only way back (item 1).

  • Scope and dry run.

    • The run covers every brand of an active or trialing organization, or the one brand given with --brand.
    • The only write is the update in recountRows (backfill-mention-counts.js:112), behind !dryRun. A dry run doesn't print the refresh list.
  • Listing and paging.

    • Ids are listed one UTC day at a time on the brand and date index, in id order, before the brand's first write. A cleaned row leaving the filter can't shift a page.
    • A day of the largest brand is well inside the service role's 120 s.
    • Rows are read 100 ids a request and written 20 at a time.
  • Re-runs. A cleaned row leaves the filter. A row with a tag that has no value stays in the filter, but the second time it recounts to null and nothing is written.

  • Live ingest and rollups.

    • New answers are stored clean, so the run never meets a row that tracking is writing.
    • Two other things write old answers:
      • the citation recount after a domain change, which writes only citation_count, a column the run doesn't write;
      • a sentiment correction, which could race the run on one row at most.
    • The nightly sweep covers only the trailing days. The old days need the three refreshes the script prints, and they are the right three:
      • Insights: the brand, prompt and competitor rollups, which topics, head-to-head and share of voice read.
      • Mentions: refresh_mentions_daily, then refresh_mention_terms, which re-reads each answer's text and rebuilds the Perception rollups, then the 00241 snapshots.
      • Citations: we_mention, comp_present and the gap tables.
    • The Mentions table, the response drawer and the Prompts page read prompt_results directly.
    • An action keeps the count it was created with, and 00245's check compares an action with its own list, so the run doesn't trip it.
  • Speed.

    • ENTITY_TAG can match a given text in only one way: each name ends at = and each value at its closing quote. A tag that fails costs one pass over its text.
    • I timed it on 100 KB inputs: runs of spaces, newlines and names; unclosed quotes; nested and repeated <Entity; attributes with no />; escapes. I also timed a 100 KB tagged answer through recountRow with 20 competitors. All of it is linear and runs in milliseconds.
  • Tests.

    • The six cases pass.
    • Without the cleanup and the sentiment rule, the two cases that test them fail.
    • The script's walk isn't tested. That's fine for a one-off with a dry run.
  • Merge.

    • Server only, no migration.
    • It merges cleanly on today's main (c58edb8), which hasn't changed any file it uses.
    • CI passes. Nothing runs on merge.

Before merge:

  1. Keep the copy out of public (backfill-mention-counts.js:19-23, and the description).
    • A table made by hand in public gets that schema's default grants, and row level security is off, unlike the app's tables.
    • Make the copy in a schema of its own, which has no grants, and drop it once the run is checked.
    • Fill it a week of answers at a time on the date index, so no single statement reads every answer's text:
      create schema if not exists backfill_backup;
      create table backfill_backup.prompt_results_entity_markup as
        select id, brand_id, created_at, response, sentiment, mention_count, visibility_score,
               mention_position, mentioned_entity_count, competitor_mentions
        from public.prompt_results
        where false;
      -- once per week of answers, oldest first:
      insert into backfill_backup.prompt_results_entity_markup
        select id, brand_id, created_at, response, sentiment, mention_count, visibility_score,
               mention_position, mentioned_entity_count, competitor_mentions
        from public.prompt_results
        where created_at >= '<day>' and created_at < '<day + 7>'
          and response like '%<Entity%';
    • Put the restore beside it, so it's at hand: an update … from the copy, matched by id (and by brand_id for one brand), then the three refreshes.

Follow-ups:
2. Don't lose the refresh list when a run stops (:50, :256-272).

  • withRetry retries only an error that's thrown, and supabase-js returns a dropped connection as { error }. So one network error ends a run, and a full run walks every day of every brand, thousands of requests.
  • The refresh commands are printed only at the end, and only for the brands changed in that run. A re-run finds the finished brands clean and leaves them out. Their old days then keep the tag counts in Insights, Mentions and Citations, and the nightly sweep never reaches those days.
  • Fix:
    • Print each brand's id and its three commands as soon as its rows are written.
    • Retry a returned error that has no code (a network failure) the way a thrown one is retried.
  1. Let the dry run show what would change.
    • Right now it prints only counts, and the copy is the only way back.
    • Print a few rows per brand: the id, and before → after for the mention count, the position and the competitors named, with whether the text or the sentiment changes. Add a count of sentiment changes. Then the run can be judged before it writes.

…e, print each brand's refreshes as it finishes, retry a dropped connection, and show sample rows in a dry run (review)

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

Copy link
Copy Markdown
Collaborator Author

Thanks. All three are done in c082052.

  1. The copy is kept out of public. The script's header and the description now have your block:
    • a backfill_backup schema with no grants;
    • the table made empty (where false), then filled a week of answers at a time on the date index;
    • the restore beside it: an update … from the copy by id (with and b.brand_id = '<id>' for one brand), then the three refreshes again, and drop schema backfill_backup cascade once the run is checked.
  2. The refresh list survives a stop.
    • Each changed brand's three commands are printed as soon as its rows are written, and again at the end.
    • withRetry also retries a returned error with no code (a dropped connection), up to three times, as it does a thrown one.
  3. The dry run shows what would change.
    • Up to three rows per brand: id, then mentions, position and competitors named before → after, "text cleaned" and the sentiment move when they apply.
    • It also prints the brand's count of sentiment changes.
    • Run on the dev DB's demo brand (no tagged answers there, so in the default mode), a line reads: 780b5130-…: mentions 4 → 1 · competitors named Fixture Roasters → Demo Coffee Co, Fixture Roasters.

Server checks: format and lint clean; 226 test files, 2,886 passed, 3 skipped.

🤖 Generated with Claude Code

@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: one small fix before the run on prod, in how the script loads each brand's domains and competitors. All three earlier items are done.

Earlier items:

  1. Keep the copy out of public: Done.
    • The header (backfill-mention-counts.js:22-48) and the description both have the block:
      • a backfill_backup schema;
      • an empty table, filled a week at a time;
      • the restore;
      • the drop.
    • A new schema grants nothing to other roles, so anon, authenticated and service_role have no USAGE on it.
    • Nothing in supabase/ changes that. The only default privileges are FOR ROLE postgres IN SCHEMA "public" (00001), there's no event trigger, and nothing grants on schemas in general.
    • The API's schemas in config.toml are public and graphql_public. Even if the schema were exposed, a role without USAGE can't read it.
    • The fill's created_at range runs on idx_prompt_results_created_at (00001, still on main). Its filter is the script's own (like '%<Entity%'), so the copy covers every row the script can write.
    • The restore sets exactly the seven columns recountRow can write. It matches on p.id = b.id, and the brand filter goes on b.brand_id, which the copy keeps.
  2. Don't lose the refresh list when a run stops: Done.
    • A brand's three commands print as soon as backfillBrand returns (:341-345), and again at the end.
    • withRetry (:77-93) now retries a returned error with no code the way it retries a thrown one: four tries in all, waiting 2, 4 and 6 s. I ran a copy against stubbed results:
      • A dropped connection is retried. supabase-js returns it with code: ''.
      • A gateway page that isn't JSON comes back with no code and is retried.
      • A constraint or permission error carries its SQLSTATE and isn't retried.
      • After the last try, the error reaches the caller, which throws.
    • Retrying an update is safe. It's one row, set to absolute values worked out from the row as read, so a retry after a write that did land writes the same values again.
    • A database error with a code (a timeout, PostgREST failing to connect) still ends the run. That's safe: a re-run picks up where it stopped.
    • A brand stopped partway prints nothing for itself. The re-run prints its commands when it writes the rest.
  3. Let the dry run show what would change: Done.
    • Up to three rows per brand (:143-158, :177-180) show the id, then before → after for mentions, position and competitors named, plus "text cleaned" and the sentiment move when they apply. Each brand also gets a count of sentiment changes.
    • No answer text is printed. I checked a sample line from a copy.
    • The only write is still the update at :181-187, behind !dryRun. Everything else in the script reads.

Also checked:

  • The new commit changes only the script. The six mention-recount tests are unchanged, and CI passes at c082052. The retry, the per-brand printing and the samples aren't tested. That's fine for a one-off.
  • It merges cleanly on today's main (307670b), which hasn't changed any file the script uses since the branch point. Server only, no migration, and nothing runs on merge.

Before the run on prod:

  1. Fail on an error while loading a brand's domains and competitors (:118-127).
    • brandContext drops the error of both reads, and neither goes through withRetry. A dropped connection there doesn't stop the run. The brand's answers are recounted with no domains or no competitors:
      • With no competitors, every answer that names the brand gets position 1 and an entity count of 1, and the competitor entries keep their old tag counts.
      • With no domains, mentions by domain drop out. An answer can turn neutral, and the score loses its own-domain citations.
    • The text is cleaned in the same write, so the rows leave the filter and a re-run doesn't revisit them. Only the copy or a full recount of the brand puts them right, and nothing in the output shows the problem.
    • This was already in the default mode. With --entity-markup it reaches every brand, and it can't be fixed by running again.
    • Fix:
      const [domainsRes, competitorsRes] = await Promise.all([
        withRetry(
          () => supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brand.id),
          'brand domains',
        ),
        withRetry(
          () => supabaseAdmin.from('competitors').select('id, name, domain').eq('brand_id', brand.id),
          'competitors',
        ),
      ]);
      if (domainsRes.error) throw new Error(domainsRes.error.message);
      if (competitorsRes.error) throw new Error(competitorsRes.error.message);
    • Do the same for the competitor read in the default mode's scope loop (:305-309). There, a failed read drops a brand from the run without a word.

Follow-up:
2. Restore in parts, and keep the drop apart (:39-48, and the description).

  • The restore is one update over every row in the copy, the whole tagged history's text in one statement. Split it like the fill: one brand at a time with the filter it already has, or a week at a time on b.created_at.
  • Move drop schema backfill_backup cascade out of the restore block, to a line of its own. Then running the block whole doesn't also drop the copy.

… can't be read, and restore the copy a brand at a time (review)

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Both are done in 7d3a1bf.

  1. A failed read of a brand's domains or competitors stops the run.
    • brandContext reads both through withRetry and throws on an error that's left, so no answer is recounted without them.
    • The default mode's scope loop reads competitors the same way, so a failed read stops the run rather than dropping the brand without a word.
  2. The restore runs in parts, and the drop is apart.
    • The header and the description restore one brand at a time (and b.brand_id = '<id>'), or a week at a time on b.created_at, then the three refreshes.
    • drop schema backfill_backup cascade is on its own line, "once the run is checked, on its own, never with the restore".

Dry runs on the dev DB's demo brand, in both modes, still run end to end. Server format and lint are clean, and the six mention-recount tests pass.

🤖 Generated with Claude Code

@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. Both earlier items are done. Every read the recount depends on now retries, and an error left after the retries stops the run.

Earlier items:

  1. Fail on an error while loading a brand's domains and competitors: Done.
    • brandContext (backfill-mention-counts.js:119-145) reads both through withRetry and throws on an error left after the tries.
    • It runs before the brand's ids are listed, in both modes. So a failed read stops the run before any of that brand's rows is written.
    • The scope loop's competitor read (:323-329) does the same. A failed read now stops the run, where it used to leave the brand out without a word.
    • I ran a copy of brandContext against a stubbed client:
      • a dropped connection (code: '') twice, then rows: three tries, and the rows are used;
      • a dropped connection every time, on either read: four tries, then it throws;
      • a thrown error every time: four tries, then it throws;
      • a statement timeout (57014): no retry, thrown at once.
    • The throw ends the run at the top-level loop. The brands already finished have had their refreshes printed.
  2. Restore in parts, and keep the drop apart: Done.
    • The header (:39-49) and the description both restore one brand at a time (and b.brand_id = '<id>') or a week at a time on b.created_at, then run the three refreshes.
    • drop schema backfill_backup cascade is on a line of its own in both, outside the restore block.

Every read the recount uses:

  • The brand's domains and competitors: retried, and an error left stops the run (item 1).
  • taggedRowIds (:222-250): resultDayBound throws on an error (citations-rollups.js:62-71), and withRetry retries a throw. Each day's ids are retried, and an error left stops the run.
  • Each page of rows (:259-268, and :289-301 in the default mode): selectInChunks returns the first failing chunk's error. The page is retried, and an error left stops the run.
  • The update (:199-205): retried, and an error left stops the run.
  • brandsInScope (:99-117): the organizations and brands reads throw on an error but aren't retried. That's fine: nothing has been written yet, so a failure there only ends the run at its start.
  • mention-recount.js reads nothing from the database. It works from the row and the context it's given.

Also checked:

  • The new commit changes only the script. The six mention-recount tests are unchanged, and CI passes at 7d3a1bf.
  • It merges cleanly on today's main (3b650fb). Since the branch point, main has changed only content files on the server, none that the script uses. Server only, no migration, and nothing runs on merge.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants