Repository navigation
chore(server): clean ChatGPT's entity tags out of stored answers and recount them, with backfill-mention-counts.js --entity-markup - #1551
Conversation
…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
left a comment
There was a problem hiding this comment.
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 whoseresponsestill 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_positionandmentioned_entity_count;- the three counts of each existing
competitor_mentionsentry.
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 onprompt_results. -
Same cleaning and counting as ingest.
- The text is
stripEntityMarkupof the stored answer. That's the functionparseScraperResponsehas 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'sid, name, domain, loaded the way the callback and the tracking worker load them. - The sentiment rule matches
cloro-result-handler.js:51-55:countBrandMentionsandparseResponsecount 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.
- The text is
-
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.
- The run covers every brand of an active or trialing organization, or the one brand given with
-
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
nulland 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 citation recount after a domain change, which writes only
- 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, thenrefresh_mention_terms, which re-reads each answer's text and rebuilds the Perception rollups, then the 00241 snapshots. - Citations:
we_mention,comp_presentand the gap tables.
- The Mentions table, the response drawer and the Prompts page read
prompt_resultsdirectly. - 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_TAGcan 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 throughrecountRowwith 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:
- Keep the copy out of
public(backfill-mention-counts.js:19-23, and the description).- A table made by hand in
publicgets 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 … fromthe copy, matched by id (and bybrand_idfor one brand), then the three refreshes.
- A table made by hand in
Follow-ups:
2. Don't lose the refresh list when a run stops (:50, :256-272).
withRetryretries 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.
- 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]>
|
Thanks. All three are done in c082052.
Server checks: format and lint clean; 226 test files, 2,886 passed, 3 skipped. 🤖 Generated with Claude Code |
gkhngyk
left a comment
There was a problem hiding this comment.
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:
- Keep the copy out of
public: Done.- The header (
backfill-mention-counts.js:22-48) and the description both have the block:- a
backfill_backupschema; - an empty table, filled a week at a time;
- the restore;
- the drop.
- a
- A new schema grants nothing to other roles, so
anon,authenticatedandservice_rolehave noUSAGEon it. - Nothing in
supabase/changes that. The only default privileges areFOR ROLE postgres IN SCHEMA "public"(00001), there's no event trigger, and nothing grants on schemas in general. - The API's schemas in
config.tomlarepublicandgraphql_public. Even if the schema were exposed, a role withoutUSAGEcan't read it. - The fill's
created_atrange runs onidx_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
recountRowcan write. It matches onp.id = b.id, and the brand filter goes onb.brand_id, which the copy keeps.
- The header (
- Don't lose the refresh list when a run stops: Done.
- A brand's three commands print as soon as
backfillBrandreturns (:341-345), and again at the end. withRetry(:77-93) now retries a returned error with nocodethe 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.
- A dropped connection is retried. supabase-js returns it with
- 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.
- A brand's three commands print as soon as
- 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.
- Up to three rows per brand (
Also checked:
- The new commit changes only the script. The six
mention-recounttests 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:
- Fail on an error while loading a brand's domains and competitors (
:118-127).brandContextdrops theerrorof both reads, and neither goes throughwithRetry. 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-markupit 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 cascadeout 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]>
|
Thanks. Both are done in 7d3a1bf.
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 🤖 Generated with Claude Code |
gkhngyk
left a comment
There was a problem hiding this comment.
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:
- Fail on an error while loading a brand's domains and competitors: Done.
brandContext(backfill-mention-counts.js:119-145) reads both throughwithRetryand 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
brandContextagainst 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.
- a dropped connection (
- The throw ends the run at the top-level loop. The brands already finished have had their refreshes printed.
- 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 onb.created_at, then run the three refreshes. drop schema backfill_backup cascadeis on a line of its own in both, outside the restore block.
- The header (
Every read the recount uses:
- The brand's domains and competitors: retried, and an error left stops the run (item 1).
taggedRowIds(:222-250):resultDayBoundthrows on an error (citations-rollups.js:62-71), andwithRetryretries a throw. Each day's ids are retried, and an error left stops the run.- Each page of rows (
:259-268, and:289-301in the default mode):selectInChunksreturns 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.jsreads 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-recounttests 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.
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 inprompt_results.response, and their mentions were counted from the tags' attributes:disambigcounted as mentioned;disambighad 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.
What it does
--brand), and only its answers that still hold a tag.stripEntityMarkup), as new answers are saved;mention_count,visibility_score,mention_position,mentioned_entity_count;competitor_mentionsentry, as the bug: brand and competitor names that start or end with a non-ASCII letter or punctuation are never counted as mentions #871 recount does.'neutral', ascloro-result-handler.jssaves one;selectInChunks) and written 20 at a time, as before.backfill-insights-daily.js;backfill-mentions-daily.js, which rebuilds the answers' terms, their rollups and Perception's snapshots;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.
public, where row level security is off.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:Once the run is checked, drop the copy on its own, never with the restore:
The same block is in the script's header.
As it runs:
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:'neutral'there too;Notes:
Related issue
Follow-up to #1097 (no issue).
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
--dry-run. Run it again: it finds nothing left.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): no web changesyarn typecheckpasses (run fromweb/): no web changesyarn format:checkpasses (run fromweb/): no web changesServer 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):disambigdrops out, positions close up, and a second run changes nothing;Pre-push review
A review agent read the change before the push. Fixed from it:
🤖 Generated with Claude Code