Skip to content

fix(action-center): keep an action's prompts, pages and competitors once, as its count (AC-009, 1/3) - #1388

Merged
gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:fix/action-count-source
Oct 23, 2026
Merged

gkhngyk merged 7 commits into
ansvisor:mainfrom
cihan-gyk:fix/action-count-source

Conversation

@cihan-gyk

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

Copy link
Copy Markdown
Collaborator

Summary

AC-009, part 1 of 3: an action now keeps the list of what it is about (its prompts, pages, competitors…) once, when it is created. Prompts deleted or paused since, and competitors deleted, are marked removed.

The web reads counts from this list in part 2 (stacked on this); part 3 adds the nightly drift check.

Why. One action showed 13 prompts in its title, 12 in its detail and 13 in a task:

  • the title, the chips and the tasks read payload.targetCount, saved at creation;
  • the drawer, Copy all, both CSVs and the MCP export re-count the action's open signals, which the nightly pass rewrites;
  • deleting or pausing a prompt changed nothing on actions;
  • group signals named only their first 50 targets, while their true count sat in current_value.

Migration 00244

  • action_entities (action_id, entity_type, entity_key, label, removed_at, removed_reason). Members can select it (as actions); the service role can write.

  • An AFTER INSERT trigger on actions writes the list from the payload, so every way an action is made keeps it alike: the engine plus the seven Send-to-Action-Center paths. The list comes from:

    • targetIds;
    • else promptIds (prompts) or pages (pages);
    • else the named targets, or the list under the targetEntity (Improve's platforms).

    Empty lists fall through to the next source. Labels come from the payload, or from the prompt's text.

  • The trigger never refuses an action. An error becomes a warning, and part 3's check finds the action. It then moves targetIds out of the payload, so reads of the action don't carry up to a thousand keys.

  • Statement-level triggers:

    • a prompt deleted is marked deleted;
    • a prompt paused is marked paused, and cleared when it's resumed;
    • a competitor deleted is marked deleted, matched by id or name across its brand's actions.
  • action_entity_counts(uuid[]): per action and type, the total, the removed and up to 20 removed names. Security invoker, read under the member's policy.

  • Backfill: existing actions get the list their payload still names (for a big group, the first 50; their count stays the payload's). Prompts already gone are marked removed.

    • A topic opportunity counts its suggestions, so the backfill reads its targets, not the tracked prompts it measures (payload - 'promptIds').
    • An action whose payload names nothing a list can hold keeps none. On prod those are the 15 old fix_low_scores with { url, score } ids and 4 old convert_mentions. Part 2 (fix(action-center): show an action's count, less what was removed since, everywhere (AC-009, 2/3) #1389) never reads total: it shows payload.targetCount less the rows removed, so these keep their saved count.

Server

  • Signals:

    • A group signal names 50 targets and, past 50, lists every target's id (targetIds, up to MAX_TARGET_IDS = 1000, lib/target-ids.js).
    • Uncited mentions list every uncited prompt.
    • Site Audit's low scores list every low page.
  • collectTargets / targetPayload: count the whole group, named ones first, and pass targetIds on.

  • One count, one list. targetKeys(values) (lib/target-ids.js) gives the keys an action keeps exactly as 00244 keeps them: trimmed of spaces, once each, in order, at most 1,000, with no empty key, object or list. Every path that sets a counted list takes targetCount from it:

    • targetPayload (signals each capped at 1,000 can add up past it);
    • an opportunity's prompts (duplicate texts);
    • a topic opportunity's suggestions (empty or duplicate texts). With no suggestion that has words, it refuses (409) rather than fall back to the tracked prompts;
    • g02's uncited prompts;
    • F01, whose count was the signal's raw current_value;
    • a topic gap's prompts.

    Content drafts, mentions and traffic pages send unique ids or paths, a few at a time.

  • Audit signal: targetIds only past the 10 pages urls lists, as group signals list theirs past 50.

  • g02 counts and keeps its uncited prompts.

  • Person-sent paths keep the keys of what their count counts:

    • an opportunity's prompts (targetCount = that list), else the prompts it names;
    • a topic opportunity's suggestions (by text);
    • traffic pages (by path).
  • Fix: Site Audit's urls entries are { url, score }. legacyTargets read them as strings, so every page collapsed into one "[object Object]" key.

  • Priority demand still reads the first 50 of a signal's prompts, as before.

Verified on the dev DB (00244 applied):

  • the backfill wrote Improve's 3 platforms;
  • a prompt target given as text inserts fine (it would have failed the uuid cast before the review fix);
  • an 11-prompt action keeps 11, drops targetIds from its payload, and marks nothing removed at creation;
  • pausing one and deleting one reads total 11, removed 2;
  • resuming clears the pause;
  • a member sees their actions' rows; anon can't call the RPC.

Deploy note

Apply 00244 with or before the server deploy; there's no order trap. The trigger and backfill don't need the server, and the server's new targetIds only add keys the trigger reads.

Related issue

AC-009 "Single count source" (ROADMAP, Drive › Diğer). No GitHub issue.

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 00244. Every action whose payload names its targets has a list (select action_id, count(*) from action_entities group by 1). The old actions listed above don't, and keep their saved count.
  2. Insert an action whose payload has targetEntity: 'prompts' and targets: ["some prompt text"]. It inserts, with one row labelled with that text.
  3. For an action with prompt rows:
    • pause one prompt: action_entity_counts shows removed 1;
    • resume it: removed 0;
    • delete it: removed 1 (deleted).
  4. Delete a competitor named by an action: its row is marked deleted.

Tests:

  • target-ids.test.js: keys trimmed, once, in order, no empty key, object or list, capped at 1,000;
  • definitions/_helpers.test.js: the whole group counted, named first; two big signals capped at 1,000; names whose keys differ listed; audit urls by address; F01 and g02 counting their lists;
  • signals/library/group.test.js: targetIds past 50;
  • signals/audit-low-score.test.js: no targetIds at 10 pages, all of them past 10;
  • from-opportunity.test.js: actionTargets, a prompt named twice counted once;
  • from-topic-opportunity.test.js: suggestions counted as kept, and none with words refused;
  • uncited-mentions.test.js.

There is no SQL test pattern in the repo; the SQL was checked on the dev DB as above.

Checklist

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

Also run:

  • server npm run format, npm run lint and npm test (2,115 tests);
  • bash supabase/build-schema.sh.

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 23, 2026 02:50
…nce, as its count

One action showed 13 prompts in its title, 12 in its detail and 13 in a
task: the title and tasks read the count saved at creation, the detail
and exports re-counted signals the nightly pass rewrites, and deleting
or pausing a prompt changed nothing. Migration 00244 keeps each action's
targets in action_entities when it is created (a trigger, so every way
an action is made keeps them alike), marks a prompt deleted or paused
and a competitor deleted as removed, and reads the counts per action
(action_entity_counts). Group signals now list every target's id beyond
the 50 they name, so an action counts and keeps the whole group, and
Site Audit's low pages count by their addresses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t each count counts

Review fixes on the action list (00244): a prompt kept by its text no
longer fails the uuid cast (which would have refused the action), the
insert trigger never refuses an action, and moves the target keys out of
the payload once kept. Each action sent by a person keeps the keys of
what its count counts (an opportunity's prompts, a topic opportunity's
suggestions, traffic pages by path); empty lists fall through. Nothing
is marked removed when a new action is made; only the backfill marks
prompts already gone. The counts RPC returns `total`; the limit is one
constant; priority still reads the first 50 prompts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 23, 2026
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk AC-009 part 1/3 (00244, server + SQL): actions keep their target list once; prompt delete/pause and competitor delete mark it. Part 2 (web reads one count everywhere, '(1 removed since this action was created)') follows stacked on this; part 3 is the nightly drift check.

…ounts

action_entity_counts also returns the removed targets' keys, so a list
of an action's prompts or pages can leave them out by id rather than by
name (two prompts can share a text, and only 20 names come back).

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

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

A few fixes before merge. Most are in the backfill, which runs once on prod and is cheaper to get right before it runs than to repair afterwards.

I ran the backfill on prod as a pg_temp copy in a rolled-back transaction:

  • 739 live actions gave 4,129 rows in about 0.45 s.
  • 316 rows were marked removed: 121 deleted and 195 paused.
  • 664 actions get exactly payload.targetCount rows.
  • The rest are below.
  1. Backfill: the topic opportunity gets the prompts it measures, not the suggestions it counts.

    • 00244_action_entities.sql:92-99 reads promptIds before targets for a prompts action.
    • For topic_opportunity, promptIds are the topic's tracked prompts. from-topic-opportunity.js:123-124 says so itself.
    • New sends are fine, because their targetIds take precedence. The existing one on prod gets its 3 tracked prompts for a count of 2.
    • Fix at :315: pass case when a.kind = 'topic_opportunity' then a.payload - 'promptIds' else a.payload end.
  2. Backfill: 19 actions that show a count get no list.

    • 15 fix_low_scores actions have the old { url, score } object as their target id. :136 now skips it, correctly. Their counts run from 1 to 25.
    • 4 convert_mentions actions never named their prompts. Their counts run from 3 to 13.
    • (49 more have no targetEntity and no count, so an empty list is right for them.)
    • If part 2 reads total from action_entity_counts, these 19 show 0. Do one of these:
      • Make part 2 fall back to payload.targetCount for an action with no rows, and say so here so part 2 is held to it.
      • Or backfill what can be recovered. For convert_mentions, the linked uncited_mentions signals' promptIds (through action_signals) recover 19 of their 24 prompts.
    • Either way, step 1 of How to test ("every action … has a list") doesn't hold on prod.
  3. Two code paths count more items than the stored list keeps. The trigger keeps each key once and at most 1,000 keys. The JS counts the raw list:

    • from-opportunity.js:108-110: with no prompt ids, the keys are prompt texts. One content opportunity on prod has 20 texts but only 18 distinct ones. Its payload would say 20 and its list keep 18.
    • from-topic-opportunity.js:121-125: targetCount is suggestions.length, but targetIds drops empty texts and the trigger merges duplicate ones.
    • definitions/_helpers.js:82-86: targetCount is the size of the union across signals. Each signal is capped at 1,000 but the union isn't, so two big signals give targetCount > 1,000 with 1,000 rows kept.

    Fix: dedupe the keys in JS ([...new Set(keys)]). Derive targetCount from the same list the trigger keeps, capped at MAX_TARGET_IDS, so the payload and action_entities agree.

  4. Low, fine as a follow-up: signal payloads now carry up to 1,000 ids each.

    • Signals that grow:
      • group signals past 50 rows carry targetIds;
      • uncited_mentions carries up to 1,000 promptIds;
      • audit_low_score carries targetIds even when urls already lists every page (record.js:336-340).
    • The MCP list_signals tool (web/src/lib/mcp/data.ts:3143) returns raw payloads for up to 200 signals, so an agent gets all of those ids.
    • Fix:
      • Add targetIds to the audit signal only past 10 pages, as group() does past 50.
      • Leave targetIds out of the MCP raw row.

Checked and fine:

  • Policy and grants. The policy is the same one action_signals and action_events use. authenticated gets select only and anon gets nothing.

  • Functions. The definer functions pin search_path and are revoked from public, anon and authenticated. action_entity_counts runs as the invoker. As a member, asking for 500 mixed action ids returned only that member's org's actions.

  • Timing. action_entity_counts as authenticated on the brand with the most actions took about 21 ms. 500 ids took about 3 ms.

  • Triggers.

    • prompts already has statement-level transition-table triggers on update and delete.
    • The payload self-update in the insert trigger doesn't fire either existing actions trigger: one fires only on status, the other only on baseline.
    • actions isn't in a realtime publication.
  • Priority. No stored score moves:

    • no action payload has more than 19 promptIds;
    • no signal has more than 47 promptIds;
    • so slice(0, 50) in promptIdsOf changes nothing today.
  • 44ec1e58 (pushed during this review) only adds removed_keys to action_entity_counts, and it's fine. Unlike the labels, the keys aren't capped at 20. That is what leaving them out of a list needs, and an action holds at most 1,000.

Merge notes

  • It merges cleanly on current main (5b679380) and contains no other open PR.
  • 00244 doesn't clash with 00240–00243, and none of those touch actions, prompts or competitors.
  • For part 2: web/src/types/supabase.ts needs action_entities and action_entity_counts.

action_entities.kept_at says when a list was written: as its action was
created, or by the backfill for one made before. The nightly count check
(AC-009 part 3) judges only lists kept at creation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cihan-gyk and others added 2 commits October 23, 2026 09:53
Review fixes for AC-009 part 1:
- targetKeys gives the keys an action keeps as 00244 keeps them (trimmed,
  once, in order, at most 1,000, no empty key, object or list); every
  path that sets a counted list takes targetCount from it: targetPayload,
  an opportunity's prompts, a topic opportunity's suggestions (refused
  when none has words), g02, F01 (no longer the signal's raw count) and a
  topic gap's prompts.
- The backfill reads a topic opportunity's suggestions, not the tracked
  prompts it measures.
- The audit signal lists targetIds only past the 10 pages it shows.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Thanks for running the backfill on prod. Everything is in 95708c6, on top of a merge of main (3a3291b).

  1. Topic opportunity backfill: the final select passes case when a.kind = 'topic_opportunity' then a.payload - 'promptIds' else a.payload end. On the dev DB, in a rolled-back transaction, an action with 3 tracked promptIds and 2 targets was kept as its 2 suggestions; the old form kept 3.

  2. The 19 actions with no list: part 2 (fix(action-center): show an action's count, less what was removed since, everywhere (AC-009, 2/3) #1389) never reads total. It shows payload.targetCount less the rows marked removed, so an action with no rows keeps its saved count. The migration comment and this PR's body say so now, and How to test step 1 names the exceptions. I didn't recover convert_mentions from their signals: the fallback covers them, and the nightly check (feat(action-center): check every night that each action's count and its list agree (AC-009, 3/3) #1390) only flags missing lists on actions made after 00244.

  3. One count, one list: targetKeys (lib/target-ids.js) keys a list the way 00244 does: trimmed of spaces, once each, in order, at most 1,000, with no empty key, object or list. targetCount comes from it in:

    • targetPayload;
    • actionTargets (opportunities);
    • the topic opportunity, which now refuses with a 409 when no suggestion has words, instead of falling back to the tracked prompts;
    • g02;
    • F01, which still used the signal's raw current_value (the same override as g02's);
    • the topic gap's prompts.

    targetPayload lists targetIds whenever the names shown aren't exactly the kept keys, e.g. a key with a trailing space.

  4. Signal sizes: the audit signal carries targetIds only past the 10 pages urls shows. MCP list_signals and get_action drop targetIds in part 2 (withoutTargetIds).

One thing I couldn't check on the dev DB, which has no old opportunities: an old opportunity's count was sd.prompts.length, and its backfilled list is the cluster's promptIds. If you'd like to see whether they differ on prod, this compares them per kind:

select a.kind, count(*) actions,
       count(*) filter (where l.total = (a.payload->>'targetCount')::numeric) same,
       count(*) filter (where l.total = 0) no_list,
       count(*) filter (where l.total > 0 and l.total <> (a.payload->>'targetCount')::numeric) differ
from actions a
cross join lateral (select count(*) total from action_entities e where e.action_id = a.id) l
where a.deleted_at is null and jsonb_typeof(a.payload->'targetCount') = 'number'
  and (a.payload->>'targetCount')::numeric > 0
group by 1 order by 1;

Part 2 caps the removed count at the saved count, so a smaller list can only understate what was removed.

Server: 2,115 tests, lint and format pass; schema.sql rebuilt. #1389 (now with action_entities / action_entity_counts in supabase.ts) and #1390 get this merged forward next.

gkhngyk
gkhngyk previously approved these changes Oct 23, 2026

@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. All four items from the last review are done or answered. One note on the deploy order is below.

Earlier items

  1. Topic opportunity backfill: done.
    • 00244_action_entities.sql:329 now passes payload - 'promptIds' for topic_opportunity.
    • On prod, the existing one now keeps its 2 suggestions instead of its 3 tracked prompts.
  2. The 19 actions with no list: answered.
    • #1389 shows payload.targetCount less the removed rows, so these actions keep their saved count.
    • The migration comment (:322-325) and How to test step 1 now say so.
    • On prod it is the same 19: 15 fix_low_scores and 4 convert_mentions.
  3. Payload count vs kept list: done.
    • targetKeys (lib/target-ids.js:16) builds keys by 00244's rules. Spaces are trimmed (only spaces, like btrim). Each key is kept once, in order, up to 1,000. Empty keys, objects, lists and text starting with { or [ are dropped.
    • Every path that sets a counted list now takes targetCount from it: targetPayload (which lists targetIds whenever the names shown differ from the keys), actionTargets, the topic opportunity, g02, F01 and the topic gap.
    • I checked the other paths. Content drafts, mentions, traffic pages and Improve send unique keys, so their counts already match what the trigger keeps.
  4. Signal payload size: done.
    • The audit signal carries targetIds only past 10 pages (record.js:340).
    • The MCP rows and the drawer drop targetIds in #1389 (withoutTargetIds).

Backfill re-run on prod (pg_temp copy in a rolled-back transaction, head 95708c69)

  • 739 live actions gave 4,128 rows in about 0.38 s. That's one fewer than last time: the topic opportunity's 3 rows became 2.
  • 121 rows are marked deleted and 195 paused, as before.
  • 685 actions have a targetCount above 0. 665 of them now get exactly that many rows (last time 664).
  • The other 20:
    • 19 keep no list. These are the actions in item 2. Their payload names nothing a list can hold:
      • the 15 fix_low_scores have { url, score } objects as target ids;
      • the 4 convert_mentions never named their prompts.
    • 1 content opportunity counts 20 but keeps 18.
      • It names its prompts by text, with no promptIds, and two of the 20 texts are duplicates.
      • The old path counted the duplicates; the list keeps each text once.
      • #1389 still shows 20, and #1390 doesn't judge lists written by the backfill, so nothing flags it. Fine to leave.
  • 54 actions have no count: 49 have no targetEntity, and 5 have one with a count of 0. They correctly keep no rows.
  • No action names more than 50 targets, so no backfilled list is cut at 50.
  • Of the opportunities you asked about: the 4 with promptIds all match, and 3 of the 4 named by text do.

Deploy order (no code change)

  • The PR body says to apply 00244 "with or before the server deploy".
  • The server on prod still makes fix_low_scores actions with { url, score } target ids every night. Three were made in the last two days.
  • If 00244 goes in before this server, any made in between keep no list. #1390 then reports each one as missing every night until it closes.
  • Deploy this server first, or in the same window before the next nightly run.
  • Server first is safe: nothing in the server needs 00244. The backfill reads the targetIds the new server writes, and keeps the full list for any action made in between.

Merge notes

  • It merges cleanly on current main (c4568814).
  • Re-merging the parents of 3a3291b4 gives the same tree except schema.sql. That file is main's plus 00244's 329 lines, with nothing else changed.
  • 95708c69 touches only the files listed above.
  • It contains no other open PR. #1389 and #1390 both contain its head.
  • 00244 doesn't clash with 00243, 00245, 00246 or 00247.

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

Re-approving after merging main into the branch. The merge only brings in the squashed parent PR; the tree matches the one tested (web and server tests, typecheck, lint, format).

@gkhngyk
gkhngyk merged commit a394c2d into ansvisor:main Oct 23, 2026
4 of 5 checks passed
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