Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/replacement-rerun-db-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ jobs:
supabase/migrations/20261118100000_harden_metric_finalization_search_path.sql \
supabase/migrations/20261204120000_multilingual_brand_matching.sql \
supabase/migrations/20261204160000_recompute_keeps_history.sql \
supabase/migrations/20261204200000_fewer_false_mentions.sql
supabase/migrations/20261204200000_fewer_false_mentions.sql \
supabase/migrations/20261204220000_overall_rank_all_answers.sql
do
echo "Applying $migration"
psql "$DB_URL" -v ON_ERROR_STOP=1 -f "$migration"
Expand Down Expand Up @@ -103,6 +104,12 @@ jobs:
-v ON_ERROR_STOP=1 \
-f supabase/tests/recompute_keeps_history_behaviour.sql

- name: Run Overall rank behavioural test
run: |
psql "postgresql://postgres:postgres@127.0.0.1:54322/postgres" \
-v ON_ERROR_STOP=1 \
-f supabase/tests/overall_rank_behaviour.sql

- name: Run synthetic candidate validation behavioural tests
run: |
psql "postgresql://postgres:postgres@127.0.0.1:54322/postgres" \
Expand Down
1 change: 1 addition & 0 deletions lib/metric-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const METRIC_DEFINITIONS: Record<MetricKey, { label: string; short: strin
detail: [
"The number after the slash is the rank population: the tracked brand plus competitors with at least one valid response in that scope.",
"Rank compares exact unrounded scores. Equal scores share a rank (1, 1, 3).",
"Overall rank measures every brand across all of the day's answers. Category rank uses that category's answers.",
"Competitors without a valid observation are excluded, never counted as zero.",
"Rows labelled \"population unverified\" predate verified run lineage.",
],
Expand Down
35 changes: 35 additions & 0 deletions supabase/maintenance/20261204_restate_overall_rank.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
-- Apply the Overall rank definition from 20261204220000 to published history.
-- A day whose stored answers no longer add up to its published answer count keeps
-- its published figures.
do $restate$
declare r record; v_total integer; v_done integer := 0; v_kept integer := 0;
begin
for r in
select distinct v.project_id, v.run_id, v.source_run_ids, v.tracking_location, v.metric_date,
v.response_count, t.provider
from public.visibility_daily v
join public.tracking_runs t on t.id = v.run_id and t.run_kind = 'overall_aggregate'
where v.category = 'Overall'
loop
select count(*) into v_total
from public.tracking_runs m
cross join lateral public.run_category_responses(m.id) c
join public.ai_responses ar on ar.id = c.response_id
where m.id = any(r.source_run_ids) and c.category = m.category
and ar.response_status = 'completed' and ar.tracking_location = r.tracking_location;
if v_total = 0 or v_total is distinct from r.response_count then
v_kept := v_kept + 1;
continue;
end if;
perform public.pool_overall_competitor_presence(r.project_id, r.run_id, r.source_run_ids, r.tracking_location, r.provider);
update public.visibility_daily v set
visibility_rank = k.visibility_rank, rank_population_count = k.rank_population_count,
rank_population_status = k.rank_population_status
from public.visibility_daily s
cross join lateral public.canonical_scoped_rank(
s.project_id, s.run_id, 'Overall', s.metric_date, r.provider, s.tracking_location, s.presence_count, s.response_count) k
where s.id = v.id and v.run_id = r.run_id and v.category = 'Overall';
v_done := v_done + 1;
end loop;
raise notice 'restated %, kept %', v_done, v_kept;
end $restate$;
74 changes: 74 additions & 0 deletions supabase/migrations/20261204220000_overall_rank_all_answers.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
-- Overall rank compares every brand across all of the day's answers.
--
-- The tracked brand's Overall rate uses every answer, but each competitor's Overall
-- rate was the sum of its category results, so a competitor assigned to one category
-- was measured on that category's answers only. One mention in 10 answers then beat
-- several mentions in 50. Overall presence and answer counts of competitors now use
-- the same answers as the tracked brand. Category results, share of voice, position
-- and citation counts are unchanged.

create or replace function public.pool_overall_competitor_presence(
p_project_id uuid, p_run_id uuid, p_member_runs uuid[], p_location text, p_provider text)
returns integer
language plpgsql security definer set search_path = public, pg_temp as $fn$
declare v_rows integer;
begin
with members as materialized (
select r.id as run_id, r.category from public.tracking_runs r
where r.id = any(p_member_runs) and r.project_id = p_project_id
),
resp as materialized (
select ar.id, public.mention_text(ar.response_text) as visible_text
from members m
cross join lateral public.run_category_responses(m.run_id) c
join public.ai_responses ar on ar.id = c.response_id
where c.category = m.category and ar.response_status = 'completed' and ar.tracking_location = p_location
),
entities as materialized (
select e.brand_id, public.alias_match_pattern(array_agg(distinct a.alias)) as pattern
from public.competitor_entities(p_project_id) e
cross join lateral unnest(e.aliases) as a(alias)
where e.category in (select m.category from members m)
group by e.brand_id
),
hits as materialized (
select e.brand_id, h.presence
from entities e
cross join lateral (
select count(*)::integer as presence from resp r where r.visible_text ~* e.pattern
) h
where e.pattern is not null
)
update public.category_brand_observations o set
presence_count = hits.presence, response_count = (select count(*) from resp)
from hits
where o.project_id = p_project_id and o.run_id = p_run_id and o.category = 'Overall'
and o.tracking_location = p_location and o.llm_provider = p_provider and o.brand_id = hits.brand_id
and exists (select 1 from resp);
get diagnostics v_rows = row_count;
return v_rows;
end
$fn$;
revoke all on function public.pool_overall_competitor_presence(uuid, uuid, uuid[], text, text) from public, anon, authenticated;
grant execute on function public.pool_overall_competitor_presence(uuid, uuid, uuid[], text, text) to service_role;

do $patch$
declare
d text;
anchor constant text := 'select * into v_rank from public.canonical_scoped_rank(';
target record;
begin
for target in select * from (values
('public.publish_engine_overall_metrics(uuid,date,text,text,boolean)',
'perform public.pool_overall_competitor_presence(p_project_id, v_agg, v_members, p_location, p_provider);'),
('public.publish_cross_engine_metrics(uuid,date,text)',
'if sc = ''Overall'' then perform public.pool_overall_competitor_presence(p_project_id, v_agg, v_members, p_location, ''Overall''); end if;')
) as t(fn, call)
loop
d := pg_get_functiondef(target.fn::regprocedure);
if (length(d) - length(replace(d, anchor, ''))) / length(anchor) <> 1 then
raise exception 'expected one rank step in %', target.fn;
end if;
execute replace(d, anchor, target.call || E'\n\n ' || anchor);
end loop;
end $patch$;
71 changes: 71 additions & 0 deletions supabase/tests/overall_rank_behaviour.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
-- Overall rank measures every brand on the same answers.
-- Runs only in the disposable local Supabase database in GitHub Actions.

begin;
set local role postgres;
select set_config('request.jwt.claim.role', 'service_role', true);

do $overall_rank$
declare
v_project uuid; v_tracked uuid; v_beta uuid; v_gamma uuid; v_skin uuid; v_hair uuid;
v_today date := (now() at time zone 'Asia/Kuala_Lumpur')::date;
ts timestamptz;
v_row record;
begin
ts := (v_today::text || ' 12:00:00+08')::timestamptz;
insert into public.projects (brand_name, brand_terms, brand_domains, categories, tracking_market, tracking_locations)
values ('Synthetic Overall Brand', array['Acme Clinic'], array['acme.example'], array['Skin', 'Hair'], 'MY', array['MY'])
returning id into v_project;
insert into public.brand_registry (project_id, canonical_name, normalized_key, aliases, primary_website, is_tracked_brand, is_active)
values (v_project, 'Acme Clinic', 'acme-clinic', array['Acme'], 'acme.example', true, true) returning id into v_tracked;
insert into public.brand_registry (project_id, canonical_name, normalized_key, aliases, primary_website, is_tracked_brand, is_active)
values (v_project, 'Beta Clinic', 'beta-clinic', array['Beta'], 'beta.example', false, true) returning id into v_beta;
insert into public.brand_registry (project_id, canonical_name, normalized_key, aliases, primary_website, is_tracked_brand, is_active)
values (v_project, 'Gamma Clinic', 'gamma-clinic', array['Gamma'], 'gamma.example', false, true) returning id into v_gamma;
insert into public.category_brand_assignments (project_id, category, brand_id, role, aliases, websites, include_in_metrics)
values (v_project, 'Skin', v_beta, 'competitor', array['Beta'], array['beta.example'], true),
(v_project, 'Hair', v_gamma, 'competitor', array['Gamma'], array['gamma.example'], true);

insert into public.tracking_runs (project_id, provider, status, total_prompts, completed_prompts, failed_prompts, started_at, completed_at, tracking_location, category, run_kind)
values (v_project, 'chatgpt', 'completed', 1, 1, 0, ts, ts, 'MY', 'Skin', 'category') returning id into v_skin;
insert into public.tracking_runs (project_id, provider, status, total_prompts, completed_prompts, failed_prompts, started_at, completed_at, tracking_location, category, run_kind)
values (v_project, 'chatgpt', 'completed', 3, 3, 0, ts, ts, 'MY', 'Hair', 'category') returning id into v_hair;
insert into public.ai_responses (project_id, llm_provider, captured_at, prompt_snapshot, raw_response, response_text, response_status, run_id, tracking_location)
values (v_project, 'chatgpt', ts, 'skin one', '{}'::jsonb, 'Beta Clinic is great.', 'completed', v_skin, 'MY'),
(v_project, 'chatgpt', ts, 'hair one', '{}'::jsonb, 'Acme Clinic and Gamma Clinic.', 'completed', v_hair, 'MY'),
(v_project, 'chatgpt', ts, 'hair two', '{}'::jsonb, 'Acme Clinic and Beta Clinic.', 'completed', v_hair, 'MY'),
(v_project, 'chatgpt', ts, 'hair three', '{}'::jsonb, 'Acme Clinic. See https://gamma.example/page', 'completed', v_hair, 'MY');
insert into public.visibility_daily (project_id, metric_date, category, llm_provider, tracking_location, run_id, visibility_score, citation_count, presence_count, response_count, rank_population_status)
values (v_project, v_today, 'Skin', 'chatgpt', 'MY', v_skin, 0, 0, 0, 1, 'unverified'),
(v_project, v_today, 'Hair', 'chatgpt', 'MY', v_hair, 100, 0, 3, 3, 'unverified');
insert into public.response_brand_evidence (project_id, response_id, brand_id, category, match_source, matched_value, evidence_text, first_position, occurrence_count, confidence)
select v_project, a.id, v_tracked, 'Hair', 'response_text', 'Acme Clinic', 'Published mention', 0, 1, 'verified'
from public.ai_responses a where a.run_id = v_hair;
update public.tracking_runs set published_at = ts where id in (v_skin, v_hair);

perform public.recompute_competitor_metrics(v_project);

select * into v_row from public.visibility_daily
where project_id = v_project and category = 'Overall' and llm_provider = 'chatgpt';
if v_row.run_id is null then raise exception 'no Overall row was published'; end if;
if v_row.presence_count <> 3 or v_row.response_count <> 4 or v_row.visibility_rank <> 1 or v_row.rank_population_count <> 3 then
raise exception 'unexpected Overall tracked row: %', to_jsonb(v_row);
end if;

-- Beta: its own category answer plus one from the other category. Gamma: a link alone does not count.
if not exists (select 1 from public.category_brand_observations where run_id = v_row.run_id and category = 'Overall'
and brand_id = v_beta and presence_count = 2 and response_count = 4) then
raise exception 'Beta Overall presence is not measured across all answers';
end if;
if not exists (select 1 from public.category_brand_observations where run_id = v_row.run_id and category = 'Overall'
and brand_id = v_gamma and presence_count = 1 and response_count = 4) then
raise exception 'Gamma Overall presence is not measured across all answers';
end if;
-- Category results are unchanged.
if not exists (select 1 from public.category_brand_observations where run_id = v_skin and brand_id = v_beta
and presence_count = 1 and response_count = 1) then
raise exception 'category observation changed';
end if;
end $overall_rank$;

rollback;
Loading