Repository navigation
feat(mentions): add the per-answer terms and the Perception read - #1123
Conversation
|
Holding #1123 and #1124 for one change: the Perception read doesn't fit the 8 s request timeout on the largest brand at the page's default range. Measured (authenticated member, production, terms filled for 15 days):
Suggested direction:
Already on the branch (pushed as separate commits):
|
Built on main without the Perception commits (ansvisor#1123, ansvisor#1124), which are on hold; this branch only shared context lines with them. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
@cihan-gyk this needs a rebase on main. Most of the stack is already there, and only the Perception data part is new.
Already on main, drop from the diff:
00160_mention_sentiment_override.sqland00162_refresh_insights_daily_range.sqlcame in with #1121 and match this branch byte for byte.00158(with the read-first perf fix) came in with #1117.- The earlier stack (#1114–#1118, #1121) was squash-merged, so its commits and merge commits will drop out.
What stays: 00161_mentions_perception.sql (mention_stopword, mention_terms, mentions_answer_terms, refresh_mention_terms, mentions_perception), the mentions-rollups.js / backfill changes, lib/mentions-perception.ts, getMentionsPerception, and the types.
Migration number: keep 00161. It sorts after 00157/00158/00160, nothing later on main redefines its objects, and the hosted DB already recorded it as mentions_perception on 2026-10-17. For the same reason, don't re-apply the file there as it stands: create policy has no if not exists and would fail. Any change to a function in it has to be applied to the hosted DB on its own.
Conflicts: take main's side, then add yours on top.
web/src/lib/actions/mentions.ts: keepexportMentions,readMentionsPageandreadBrandTermsfrom #1125, and appendgetMentionsPerception._mentions-tab.test.tsx: take main's version (Export, ink highlight).types/supabase.ts: regenerate it. Forschema.sql, re-runbash supabase/build-schema.sh.
Small fixes before merge:
refresh_mention_termshas no lock. #1227 / 00192 gaverefresh_mentions_dailya per-brandpg_advisory_xact_lock. Without one here, a run's refresh and the nightly sweep can overlap on the same days, and one of them fails on the(result_id, entity)key. Take the same kind of lock, with its own key (e.g.'refresh_mention_terms:' || p_brand_id).- The nightly sweep passes 3 days to
refreshMentionsDailyin one call. By this PR's own comment, three busy days of the largest brand near the 120 s service-role timeout. Refresh the terms one day at a time insiderefreshMentionsDaily, as the history backfill already does. - The PR body is out of date. It says 00161 restates
refresh_mentions_dailyand that history refreshes three days a call, but the code has its ownrefresh_mention_termsandMENTION_HISTORY_CHUNK_DAYS = 1.
Deploy note: nothing on main calls refresh_mention_terms, so mentions_answer_terms on the hosted DB is stale. Run backfill-mentions-daily.js once the server is deployed.
The Perception tab's data (MS-09), deterministic as spec §9 asks for V1: - migration 00161: mention_terms() takes the sentences of an answer that name an entity and returns their words and two-word phrases, minus stop words in 13 languages (Snowball dictionaries), words answers use about every brand alike, every brand's names and the question's own words; mentions_answer_terms keeps the distinct terms per answer and entity named (the brand or a competitor), filled by refresh_mentions_daily with the mention rollups; mentions_perception() reads a window and the one before: the brand's top terms with their trend, the 8 attributes that tell it and its four most mentioned competitors apart with each one's share of mentions, and the competitors named in the same answers - the mention history refreshes three days a call: the terms make each call heavier than the citation rollups' fortnight - web: getMentionsPerception, the parsed shape, shares, and the biggest gap (a competitor leading an attribute by 20+ points) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reading the answers' text for their terms takes about 2.4 ms per answer and entity named: about 7 s for a recent day of the largest brand, and more on its busier days. Inside refresh_mentions_daily that also ran in a sentiment correction (00160), within the person's 8 s request, where the terms never change. refresh_mention_terms now holds that part, and refresh_mentions_daily stays as 00157 wrote it. The server calls both for a completed run, the nightly sweep and the backfill; the backfill goes a day at a time. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
…day at a time - refresh_mention_terms takes a per-brand advisory lock of its own, as refresh_mentions_daily does since 00192: a run's refresh and the nightly sweep can cover the same days, and the second insert would fail on the (result_id, entity) key. - refreshMentionsDaily refreshes the rollups for the range in one call and the terms one day per call, so the sweep's three days stay well inside the service role's statement timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
6147aec to
e39a282
Compare
|
@gkhngyk Rebased on
Fixes (e39a282):
Checked: server 1,920 tests, lint, Prettier; web 1,930 tests, tsc, lint, Prettier and |
gkhngyk
left a comment
There was a problem hiding this comment.
Ready to merge. Merge order is #1123, then #1124, #1126 and #1127.
Rebase
- The branch is main's
3867cb8bplus three commits:0bc61302,0d1e199eand the fixe39a282f. git merge-treeonto the current main (4ac82ce5) is clean. The result differs from main only in this PR's 10 files, so nothing on main is reverted.00158,00160,00162,en.json,_mentions-tab.tsx/ its test and_response-drawer.tsxare untouched, so they stay byte for byte main's.getMentionsPerceptionsits after main'sexportMentions/readMentionsPage/readBrandTerms.- In
schema.sqlthe 00161 block sits between the 00160 and 00162 blocks. - CI is green.
Fixes
refresh_mention_termsnow takespg_advisory_xact_lock(hashtextextended('refresh_mention_terms:' || p_brand_id::text, 0))before the delete. The key is separate from 00192's, so the rollups and the terms don't wait on each other.refreshMentionsDailymakes onerefresh_mentions_dailycall for the range, then onerefresh_mention_termscall per day (MENTION_HISTORY_CHUNK_DAYS = 1). It stops at the first failure.- The PR body now describes both, plus the deploy steps.
Hosted DB. I compared the stored function bodies (prosrc md5) with this file:
mention_stopword,mention_termsandmentions_perceptionare identical.refresh_mention_termson prod is the previous body, without the lock. It's the only thing to apply.- The table, index, RLS policy and grants are already in place.
- Don't re-apply the whole of 00161:
create policywould fail.
Deploy
- Apply only
create or replace function public.refresh_mention_terms(...)and itsrevoke, taken from this file. - Merge and deploy the server.
- Run
node src/scripts/backfill-mentions-daily.jsonce, so answers stored before the deploy get their terms. Main has never calledrefresh_mention_terms, so the hosted terms table only holds what was filled during testing.
ansvisor#1123 is squash-merged on main; this keeps only this branch's own change on top. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
Summary
The data for the Mentions & Sentiment Perception tab (MS-09): what AI says next to the brand and its competitors. Spec §9 wants it deterministic in V1, so the terms come from the stored answers by rule, with no LLM call. The tab's UI follows in the next PR.
Migration
00161_mentions_perception.sqlmention_terms(text, names, exclude)reads the sentences of an answer that name an entity (a whole word, ignoring case) and returns their words and two-word phrases. It drops:Links read as their labels and ChatGPT's entity tags as their names. A phrase never spans a comma or a bracket.
mentions_answer_terms: one row per answer and entity it names (the brand, or a competitor by id), holding the distinct terms.refresh_mention_terms(brand, from, to): fills the table for a UTC day range, in its own function, so a sentiment correction (00160) refreshes only the rollups.refresh_mentions_daily: a completed run, the nightly sweep andbackfill-mentions-daily.js.'refresh_mention_terms:' || brand), asrefresh_mentions_dailydoes since 00192, so a run's refresh and the sweep can't collide on the(result_id, entity)key.mentions_perception(brand, from, to, platform, region, topic, search)usesmentions_list's window (00158) and the window before it:entities: the brand, then its four most mentioned competitors, with mentions now and before;brand_terms: the brand's 15 top terms with their previous counts. A word that nearly always comes in one phrase ("fresh" in "fresh roast", 80%+) is listed as the phrase;attributes: the 8 terms that tell those entities apart most, by the widest spread of shares of mentions, with each entity's count. These feed the heat map and the radar;co_mentions: every competitor named in the same answers as the brand, now and before ("Frequently mentioned with" and its trend).security definer, with the organization check explicit; a stranger getsnull.Terms describe what is said next to a brand: a sentence naming two brands lends its words to both. Themes and polarity come with the V1.5 classifier (spec §3).
Server
refreshMentionsDaily: refreshes the rollups for the range in one call, then the terms one day per call (MENTION_HISTORY_CHUNK_DAYS = 1). Reading each answer's text for its terms costs about a millisecond per answer and entity, so even the sweep's three busy days of the largest brand would near the service role's statement timeout.refreshMentionHistory: one day per call, for the same reason.backfill-mentions-daily.js: its header says it fills the terms too.Web
lib/actions/mentions.ts:getMentionsPerceptionreturnsnullonPGRST202.lib/mentions-perception.ts:biggestGap: the attribute a competitor leads by the widest margin, at least 20 points, and the brand's place on it (none if AI never uses the term for the brand). Spec §9's example: "Enterprise: Profound fix(tracking): keep job active until webhook results drain #1, you unplaced".types/supabase.ts: gets the table and the function.Deploy
create policyhas noif not exists. Apply the changedrefresh_mention_terms(the lock) on its own.node src/scripts/backfill-mentions-daily.jsonce, somentions_answer_termscatches up. Nothing on main callsrefresh_mention_termsyet, so it's stale until then. New answers get their terms when their run completes.Related issue
None.
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
select mentions_perception('<brand>', now() - interval '30 days').entities[0].mentionsequals the Overview's Total mentions.co_mentionscount equals the Overview's "Same answer as you".brand_termsandattributeslist words from the answers next to each brand.null.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): no errors; the 7 warnings are in files this PR does not touchyarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)Also run:
web:yarn test(1,930) andyarn buildpass.lib/mentions-perception.test.ts: parsing, shares, changes, attribute shares, and the biggest gap (none, unplaced, ranked).lib/actions/mentions.test.ts: the call,PGRST202and errors.server:npm run lintandnpm test(1,920) pass.mentions-rollups.test.jscovers the terms a day at a time, the history a day at a time, and a failed chunk.bash supabase/build-schema.sh: regeneratedschema.sql.Consistency:
mentions_overview;nulland reads no rows.On a realistic answer:
Timing: 10,000 synthetic multi-sentence answers over 90 days, as
authenticated, rolled back and vacuumed. A hosted dev database, ~70 ms of network included.Two hot spots found on the way are fixed:
🤖 Generated with Claude Code