Skip to content

feat(insights): explain the visibility change beside the platform table - #1042

Merged
gkhngyk merged 35 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-why-changed
Oct 16, 2026
Merged

gkhngyk merged 35 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-why-changed

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Stacked on #1041 (VIS-004) → #1039 (VIS-008) → #1038 (VIS-006) → #1037 (VIS-003) → #1036 (VIS-002) → #1035 (VIS-001). Until those merge, this PR also shows their commits. The VIS-009 change is the last commit, 26e857a.

Summary

The v2 mockup explains the Visibility change in a box beside the By AI platform table. This is VIS-009 in the Visibility spec v2. The mockup's example:

Why it changed                                    Full breakdown →
GAINS
[Platform] Google AI Mode                        4.9 → 21.0   +0.9
[Topic]    Open Source AEO                      31.2 → 48.6   +0.7
[Prompt]   Most popular open-source GEO…        37.6 → 52.6   +0.1
DROPS
[Platform] ChatGPT                              11.3 → 8.1    −0.4
[Topic]    AI Rank Tracker                      22.0 → 17.5   −0.2
┆ 509 new prompts · Sep 29 · own baseline, not counted          ┆

What it shows:

  • Gains and Drops: up to three each, across platforms, topics and prompts. Each row has the slice's own Visibility before → after (the card's formula over that slice, as the breakdown panel scores it) and its effect on the overall score.
  • Effect: how much higher the overall score is than it would be had the slice kept last period's rates at this period's volume.
    • Large slices weigh more, so a prompt with a handful of answers can't top the list just because it went 0 → 100.
    • When one slice is the only thing that moved, its effect is exactly the overall change (tested).
    • Effects under 0.1 pts are left out.
  • Sample size: it follows Compare: Same prompts (feat(insights): compare changes on the same prompts by default #1036). With fewer than 20 compared answers in either period, the box says so instead of naming drivers, the same 20-answer rule as feat(insights): replace the share of voice charts with the by AI platform table #1039.
  • New prompts line: "6 new prompts · Oct 12 · own baseline, not counted", or "counted in the change" with Same prompts off.
    • The date covers only prompts created this period; a prompt answered again after a pause counts as new but adds no date.
    • The mockup's "View →" isn't here: the Prompts page has no date-added sort or filter to link to yet.
  • Opening the panel: a row opens the breakdown panel on its tab (Platforms, Topics or Prompts). "Full breakdown →" opens the panel. The panel takes a new optional initialTab.
  • Layout: the box sits beside By AI platform (flex: 1 1 420px next to 1 1 520px) and drops below it on narrow screens. All time has nothing to compare, so the box is hidden and the table keeps the full width.

Code:

  • lib/insights-drivers.ts holds the logic as pure functions:
    • parseChangeDrivers reads the RPC payload;
    • whyChanged folds and scores the slices and ranks them.
  • _why-changed.tsx is the box.

Data

Migration 00135 adds insights_change_drivers_daily (prompt-grain rollups) and insights_change_drivers (raw rows, for the 24h and topic views). They return:

  • the Visibility components per prompt and per (model, platform) in both windows, over the shared prompts when p_same_prompts;
  • each prompt's text and topic;
  • the new prompts' count, and when those created this period were added.

Both are security invoker, with the same windows as insights_platform_compare[_daily]. On a dev database they return the same totals. No new backfill: they read the 00130 columns.

Review

I ran a code review before opening this. It found 9 things and 7 are fixed:

  • the rows' screen-reader label hid their numbers;
  • the new-prompts date could show a long-ago creation date for a resumed prompt;
  • the box read Same prompts from the comparison, which can be missing; it now comes with the box's data;
  • a deleted prompt's history went under "Uncategorized";
  • a misplaced doc comment;
  • the panel imported its tab type from the box;
  • no test for slices whose volume changed at the same rates.

Left as notes:

  • Different platform names: the box names platforms as By AI platform does (resolveProvider, e.g. "Gemini"). The breakdown panel groups by prompt_results.platform and its own labels (e.g. "Google Gemini"), so a Platform row can open on differently named panel rows. That difference predates this PR.
  • Another rollup read: the box adds one more read of the prompt rollups per page load. It could share the presence set with the other comparison RPCs.

Related issue

None. Product spec: Visibility spec v2, task VIS-009. Depends on #1041, #1039, #1038, #1037, #1036 and #1035.

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 00129 to 00135, then refill the rollups (backfill script, or refresh_insights_daily per brand).
  2. Open Insights with 30d on a brand with steady tracking. "Why it changed" sits to the right of By AI platform.
  3. Check the rows:
    • with Same prompts on, they explain the Visibility card's change;
    • a Platform row's before → after matches the panel's row for that platform.
  4. Click a Topic row: the breakdown panel opens on Topics. "Full breakdown →" opens it on Prompts.
  5. Turn Same prompts off: the new-prompts line says "counted in the change".
  6. Pick All: the box disappears and the table takes the full width.
  7. Check 1024px (the box drops below the table) and dark mode.

On the demo seed, the 30-day same-prompt set has 2 answers this period, so the box shows the low-sample note. I checked the rows with the mockup's values as a temporary stand-in, not committed.

Checklist

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

Also run:

  • yarn test: 604/604. New tests are in insights-drivers.test.ts:
    • parsing;
    • one slice moving equals the whole change;
    • weighting by answers;
    • gains and drops apart, with a limit;
    • volume at the same rates;
    • a slice in one window;
    • low sample.
  • yarn build: passed.
  • bash supabase/build-schema.sh: schema.sql is up to date.
  • npm run version:check: passed.
  • The migration is applied on a dev database. I checked the page in the browser at 1440px and 1024px, in light and dark mode, with Same prompts on and off, and on All time.

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits October 14, 2026 17:51
Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…form table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is ready for review. It's VIS-009 from the Visibility spec v2, stacked on #1041 → #1039 → #1038 → #1037 → #1036 → #1035. Until those merge, the VIS-009 change is the last commit.

It adds the mockup's "Why it changed" box beside By AI platform. It lists the platforms, topics and prompts that moved Visibility most, each with its own before → after and its effect on the overall score, plus a line for the prompts new this period. A row opens the breakdown panel on its tab.

Things to look at:

  • Migration 00135 adds insights_change_drivers[_daily]: per-prompt and per-engine Visibility components in both windows, from the prompt-grain rollups (raw rows for 24h/topic), security invoker. It needs no new backfill.
  • How a slice's effect is computed: the overall score now, minus what it would be had that slice kept last period's rates at this period's volume. It's documented in whyChanged and tested; with one slice moving, it equals the whole change.
  • Under 20 compared answers in either period, the box says so instead of naming drivers. On the demo seed's 30 days that's what you'll see.
  • Not included: the mockup's "View →" on the new-prompts line, since the Prompts page has no date-added sort or filter yet. I can add that sort as a separate PR.

Code review (7 of 9 findings fixed, the rest noted in the description), yarn test (604/604), lint, typecheck and build pass. I checked it in the browser at 1440px and 1024px, in light and dark mode.

@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Blocker: insights_change_drivers_daily times out on the largest brand.

00135 is applied to the hosted database, and the rollups are backfilled. I timed this RPC on the largest brand (~219k answers), 30d against the previous 30d:

  • As the owner (no RLS): 0.58 s.
  • As authenticated, for a real org member: more than 20 s. The role's statement_timeout is 8 s.
  • With work_mem = 64MB and plan_cache_mode = force_custom_plan: 12.3 s, still over the limit.

The same query with literal values plans fine (index scan and a hashed RLS subplan), so the slowdown comes from the parameterized plan inside the function combined with RLS. The call is wrapped in lenient, so the page doesn't break, but "Why it changed" never shows for this brand and every open burns 8 s of database time. Smaller brands are fine (~0.4 s on the second largest).

Same fix direction as #1036: for example, security definer with an explicit org-membership check, as in 00119.

cihan-gyk and others added 4 commits October 15, 2026 23:43
…bers

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
insights_change_drivers_daily took 0.58 s as the owner but over 20 s for
an org member: a SQL function is planned without its argument values on
PostgreSQL 17, and RLS was planned into that guess.

00148 makes both change-driver RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rows are folded per
prompt, engine and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
00147 (ansvisor#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

Copy link
Copy Markdown
Collaborator Author

Thanks @gkhngyk! This is fixed in a new migration, 00148 (00135 is untouched), the same way as 00147 on #1036:

  • plpgsql with force_custom_plan. On PostgreSQL 17, a SQL-language function is planned without its argument values. That's why the literal query planned fine and plan_cache_mode didn't help. Each call is now planned with its real arguments.
  • Security definer with an explicit org-membership check, as in 00119. RLS no longer runs inside the scan. The service role still reads (the cached 24h view uses it), non-members get null, and anon loses execute.
  • A cheaper query. The rows are folded to one row per prompt, engine and window before the presence check and the two groupings read them.

The output is unchanged. Both RPCs return identical JSON before and after for 30d with Same prompts on and off, 90d, 24h and a topic view, as a member and as the service role.

Local timings. I used the same setup as on #1036: our dev database (PostgreSQL 17.11) and a synthetic brand with 210,416 answers over 62 days, rollups backfilled. These are medians of 5 runs as authenticated, with a real org member's JWT claims:

Window Before After
30d vs previous 30d 729 ms 201 ms
30d, Same prompts off 1,019 ms 217 ms
90d 398 ms 202 ms
24h (raw) 884 ms 104 ms
Topic, 30d (raw) 944 ms 1,018 ms
  • As the owner, the old function took ~0.8 s, close to your 0.58 s.
  • The dev database doesn't reproduce the 20 s member time, because its RLS subquery reads a one-row profiles table. With the definer, the membership check runs once per call.
  • The topic view reads its answers prompt by prompt and stays about the same.

Re-timing on the hosted database is yours to run. As the owner without JWT claims, the new functions return null at once. Please time them with a member's claims, as health_probe does.

The change is SQL only. build-schema.sh regenerated schema.sql. yarn test (648/648), lint (0 errors; the 7 warnings are in files this PR doesn't touch), typecheck and build pass.

@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@cihan-gyk 00148 is applied to production, along with 00147 and 00149 (see #1037 for the restack after #1036). If 00148 changes when the stack reaches this PR, mention it here so we re-apply it before merge.

…nto feature/insights-kpi-cards

# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
…i-cards

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking-visibility-parity.test.ts
#	web/src/lib/actions/tracking.ts
#	web/src/lib/insights-same-prompts.test.ts
#	web/src/lib/insights-same-prompts.ts
#	web/src/types/supabase.ts
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
…mmary-line

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking.ts
#	web/src/types/supabase.ts
…aderboard

# Conflicts:
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/insights-summary.test.ts
#	web/src/lib/insights-summary.ts
…to feature/insights-why-changed

# Conflicts:
#	supabase/schema.sql
…y-changed

# Conflicts:
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx

@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, thanks. 00135 and 00148 match production. Timed as a signed-in member of the largest brand: insights_change_drivers_daily 0.3 s for 30 days, insights_change_drivers 0.08 s for 24h and 1.25 s on the largest topic over 30 days. The tree equals main plus this PR; web tests pass (707) and CI is green.

@gkhngyk
gkhngyk merged commit 8ac663f into ansvisor:main Oct 16, 2026
5 checks passed
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 16, 2026
…ture/insights-topic-heatmap

Brings in main with ansvisor#1042, squash-merged after this branch took its earlier
head. Resolved: en.json, insights/page.tsx, tracking.ts and the generated
supabase types keep both ansvisor#1042's Why-it-changed and this branch's Topics vs
competitors; schema.sql rebuilt.
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