Skip to content

feat(mentions): add the per-answer terms and the Perception read - #1123

Merged
gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-perception-data
Oct 21, 2026
Merged

gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-perception-data

Conversation

@cihan-gyk

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

Copy link
Copy Markdown
Collaborator

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.

Rebased on main (2026-10-21). The earlier stack (#1114–#1118, #1121) is on main, so this PR is only the Perception data: 00161 and its server and web parts.

Migration 00161_mentions_perception.sql

  • mention_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:

    • stop words in 13 languages, from Postgres' Snowball dictionaries (English, German, French, Spanish, Italian, Portuguese, Dutch, Turkish, Swedish, Danish, Norwegian, Finnish, Russian);
    • a short list of words answers use about every brand alike ("best", "solid", "ahead", "leads"…);
    • every brand's and competitor's names;
    • the question's own words, which would otherwise rank first for every brand and say nothing about any.

    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.

    • It grows with the answers, not with the vocabulary, as a per-term daily rollup would.
    • The page's filters (topic, prompt search, platform, country) and the window before stay available.
    • RLS lets the brand's organization read it.
  • 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.

    • It rides on the same callers as refresh_mentions_daily: a completed run, the nightly sweep and backfill-mentions-daily.js.
    • It takes a per-brand advisory lock of its own ('refresh_mention_terms:' || brand), as refresh_mentions_daily does since 00192, so a run's refresh and the sweep can't collide on the (result_id, entity) key.
    • Brands and competitors are matched by the names tracking counts (name and domains).
  • mentions_perception(brand, from, to, platform, region, topic, search) uses mentions_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: security definer, with the organization check explicit; a stranger gets null.

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: getMentionsPerception returns null on PGRST202.
  • lib/mentions-perception.ts:
    • the parsed shape;
    • shares of mentions (multiplied first, so whole percentages stay whole);
    • changes;
    • each attribute's share per entity;
    • 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

  1. 00161 is already recorded on the hosted DB (2026-10-17). Don't re-apply the file: create policy has no if not exists. Apply the changed refresh_mention_terms (the lock) on its own.
  2. Deploy the server, then run node src/scripts/backfill-mentions-daily.js once, so mentions_answer_terms catches up. Nothing on main calls refresh_mention_terms yet, so it's stale until then. New answers get their terms when their run completes.

Related issue

None.

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. Apply 00161 and run the backfill.
  2. As a member of the brand's organization: select mentions_perception('<brand>', now() - interval '30 days').
    • entities[0].mentions equals the Overview's Total mentions.
    • Each co_mentions count equals the Overview's "Same answer as you".
    • brand_terms and attributes list words from the answers next to each brand.
  3. Add platform, region, topic or search arguments, and the figures narrow.
  4. As someone outside the organization: null.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no errors; the 7 warnings are in files this PR does not touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • web: yarn test (1,930) and yarn build pass.
    • lib/mentions-perception.test.ts: parsing, shares, changes, attribute shares, and the biggest gap (none, unplaced, ranked).
    • lib/actions/mentions.test.ts: the call, PGRST202 and errors.
  • server: npm run lint and npm test (1,920) pass. mentions-rollups.test.js covers the terms a day at a time, the history a day at a time, and a failed chunk.
  • bash supabase/build-schema.sh: regenerated schema.sql.
  • Dev database: rolled-back dry runs first, then applied, with the demo brand backfilled.
    • Consistency:

      • 107 mentions over 30 days, as mentions_overview;
      • co-mentions 80 / 72 / 71, as its competitors;
      • a stranger gets null and reads no rows.
    • On a realistic answer:

      • Peec AI: "affordable", "simple dashboards", "prompt tracking", "small teams".
      • Profound: "enterprise-grade", "detailed share-of-voice reporting".
      • Ansvisor: "open-source", "self-host", "search intelligence".
      • The German stop words are dropped.
    • 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.

      90d 0.66 s
      30d 0.40 s
      7d 0.15 s
      24h 0.09 s
      90d, one platform 0.20 s
      refresh ~1 ms per answer and entity named

      Two hot spots found on the way are fixed:

      • the phrase folding compared every term with every other, and now compares each entity's 60 most frequent;
      • co-mentions were a self-join, and are now one window pass.

🤖 Generated with Claude Code

@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk the Perception tab's data: deterministic terms per answer (migration 00161) and the read for the tab. Stacked on #1121 → … → #1115. On deploy, after 00161, please run node src/scripts/backfill-mentions-daily.js once more so stored answers get their terms. The UI follows in the next PR.

@gkhngyk

gkhngyk commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

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):

  • mentions_perception 24h 0.48 s, 7d 1.65 s. Of the 7d time, 0.96 s is term_counts_all: 65k answer×entity rows unnest into ~1M terms, grouped into 106k (entity, term) pairs.
  • The cost grows with rows. 30d reads 60 days, about 318k answer×entity rows, roughly 8 s; 90d is past 15 s. The page opens on 30d.
  • A day-grain rollup alone doesn't close the gap. Over 14 days, 1.36M unnested terms collapse to 561k rows by (day, entity, term, platform, region), or 390k by (day, entity, term). Only 42.6k (entity, term) pairs appear 3 or more times: most of the volume is the long tail.

Suggested direction:

  • Store the Perception payload per brand for the preset ranges with no filters set, e.g. mentions_perception_snapshots(brand_id, range_days, computed_at, payload).
  • Write it on the server after a run's terms refresh and in the nightly sweep. The service role has 120 s.
  • The page reads the snapshot when no filter is set; filtered reads (topic, search, platform, country) stay live, since they read far fewer rows.
  • For a custom range, either cap the live read (e.g. 30 days) or read the snapshot covering it.

Already on the branch (pushed as separate commits):

  • refresh_mention_terms holds the term extraction, so a sentiment correction refreshes only the rollups.
  • The backfill goes a day at a time: a busy day of the largest brand takes ~20 s of terms.
  • 00161 is applied on production with that split, and terms are filled for the largest brand's last 15 days.

gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 17, 2026
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 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.

@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.sql and 00162_refresh_insights_daily_range.sql came 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: keep exportMentions, readMentionsPage and readBrandTerms from #1125, and append getMentionsPerception.
  • _mentions-tab.test.tsx: take main's version (Export, ink highlight).
  • types/supabase.ts: regenerate it. For schema.sql, re-run bash supabase/build-schema.sh.

Small fixes before merge:

  1. refresh_mention_terms has no lock. #1227 / 00192 gave refresh_mentions_daily a per-brand pg_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).
  2. The nightly sweep passes 3 days to refreshMentionsDaily in 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 inside refreshMentionsDaily, as the history backfill already does.
  3. The PR body is out of date. It says 00161 restates refresh_mentions_daily and that history refreshes three days a call, but the code has its own refresh_mention_terms and MENTION_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.

cihan-gyk and others added 3 commits October 21, 2026 18:28
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]>
@cihan-gyk
cihan-gyk force-pushed the feature/mentions-perception-data branch from 6147aec to e39a282 Compare October 21, 2026 15:43
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Rebased on main and force-pushed. The user approved the force push for #1123, #1124 and #1126 only.

  • What's left is feat(mentions): add the per-answer terms and the Perception read #1123's own commits on top of main: the Perception data commit, your refresh_mention_terms perf commit, and the fixes below. Before pushing I compared the files with what they should be:
    • 00158, 00160, 00162, _mentions-tab.tsx / its test, _response-drawer.tsx and en.json are byte for byte main's;
    • 00161, mentions-rollups.js, the backfill, lib/mentions-perception.ts and its test are byte for byte the old branch's, except for the fixes below;
    • getMentionsPerception is added after main's exportMentions / readMentionsPage / readBrandTerms;
    • the types are main's plus 00161's table and functions; schema.sql is rebuilt.
  • 00161 keeps its number.

Fixes (e39a282):

  1. refresh_mention_terms takes pg_advisory_xact_lock(hashtextextended('refresh_mention_terms:' || p_brand_id::text, 0)), as 00192 does for refresh_mentions_daily. On the dev DB I applied only that function (the file isn't re-applied), and a run over the demo brand's days rewrote the same 439 rows. On the hosted DB the function needs applying on its own.
  2. refreshMentionsDaily refreshes the rollups for the range in one call, then the terms one day per call (MENTION_HISTORY_CHUNK_DAYS). The test checks three days as one rollups call and three terms calls.
  3. The PR body now describes refresh_mention_terms (with the lock), the per-day terms, and the deploy steps: don't re-apply 00161, apply the function, then run backfill-mentions-daily.js once the server is deployed.

Checked: server 1,920 tests, lint, Prettier; web 1,930 tests, tsc, lint, Prettier and yarn build. The old head is kept locally as backup/1123-before-rebase (6147aec).

@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.

Ready to merge. Merge order is #1123, then #1124, #1126 and #1127.

Rebase

  • The branch is main's 3867cb8b plus three commits: 0bc61302, 0d1e199e and the fix e39a282f.
  • git merge-tree onto 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.tsx are untouched, so they stay byte for byte main's.
  • getMentionsPerception sits after main's exportMentions / readMentionsPage / readBrandTerms.
  • In schema.sql the 00161 block sits between the 00160 and 00162 blocks.
  • CI is green.

Fixes

  • refresh_mention_terms now takes pg_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.
  • refreshMentionsDaily makes one refresh_mentions_daily call for the range, then one refresh_mention_terms call 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_terms and mentions_perception are identical.
  • refresh_mention_terms on 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 policy would fail.

Deploy

  1. Apply only create or replace function public.refresh_mention_terms(...) and its revoke, taken from this file.
  2. Merge and deploy the server.
  3. Run node src/scripts/backfill-mentions-daily.js once, so answers stored before the deploy get their terms. Main has never called refresh_mention_terms, so the hosted terms table only holds what was filled during testing.

@gkhngyk
gkhngyk merged commit 4fcd6dd into ansvisor:main Oct 21, 2026
5 checks passed
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants