Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(server): count run results from the DB when stamping tracking_runs (#583)
Gökhan Geyike76c9bda3410
diff --git a/server/src/lib/pulse/metrics.js b/server/src/lib/pulse/metrics.jsindex b239118b5..436ce2225 100644--- a/server/src/lib/pulse/metrics.js+++ b/server/src/lib/pulse/metrics.js@@ -297,6 +297,22 @@ async function degradedPlatforms(now) {return degraded;}+/**+ * The last completed tracking runs' stamps, newest first (00044 ledger).+ * Empty when the brand has never completed a full run.+ */+async function latestCompletedRunTimes(brandId, limit = 3) {+ const { data, error } = await supabaseAdmin+ .from('tracking_runs')+ .select('completed_at')+ .eq('brand_id', brandId)+ .not('completed_at', 'is', null)+ .order('completed_at', { ascending: false })+ .limit(limit);+ if (error) return [];+ return (data ?? []).map((r) => new Date(r.completed_at));+}+/*** Compute the full pulse payload for a brand.*@@ -307,8 +323,30 @@ async function degradedPlatforms(now) {* history) stay fixed per the issue spec.*/export async function computePulseMetrics(brandId, { windowDays = 1, now = new Date() } = {}) {- const curFrom = new Date(now.getTime() - windowDays * DAY_MS);- const prevFrom = new Date(now.getTime() - 2 * windowDays * DAY_MS);+ // Daily KPI windows anchor to the tracking-run ledger — the exact same+ // windows the Insights 24h view resolves (getTrackingWindow) — so the+ // email can never disagree with the dashboard. A wall-clock [now-24h]+ // window double-counts whenever two runs land within 24h of each other+ // (e.g. the day the cron time moved earlier). Weekly pulses and the+ // detector windows below stay clock-based per the issue spec; brands+ // with no completed run yet fall back to the clock window.+ let curTo = now;+ let curFrom = new Date(now.getTime() - windowDays * DAY_MS);+ let prevTo = curFrom;+ let prevFrom = new Date(now.getTime() - 2 * windowDays * DAY_MS);++ if (windowDays === 1) {+ const [latest, prev, prevPrev] = await latestCompletedRunTimes(brandId, 3);+ if (latest) {+ curTo = latest;+ curFrom = new Date(Math.max(latest.getTime() - DAY_MS, prev ? prev.getTime() + 1 : 0));+ prevTo = prev ?? curFrom;+ prevFrom = prev+ ? new Date(Math.max(prev.getTime() - DAY_MS, prevPrev ? prevPrev.getTime() + 1 : 0))+ : new Date(curFrom.getTime() - DAY_MS);+ }+ }+const weekFrom = new Date(now.getTime() - 7 * DAY_MS);const twoWeekFrom = new Date(now.getTime() - 14 * DAY_MS);@@ -330,11 +368,11 @@ export async function computePulseMetrics(brandId, { windowDays = 1, now = new DlostCitations,degraded,] = await Promise.all([- visibilityRate(brandId, curFrom, now),+ visibilityRate(brandId, curFrom, curTo),visibilityRate(brandId, weekFrom, now),visibilityRate(brandId, twoWeekFrom, weekFrom),- insightsWindow(brandId, curFrom, now),- insightsWindow(brandId, prevFrom, curFrom),+ insightsWindow(brandId, curFrom, curTo),+ insightsWindow(brandId, prevFrom, prevTo),competitorRates(brandId, weekFrom, now),competitorRates(brandId, twoWeekFrom, weekFrom),promptScores(brandId, weekFrom, now),diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.jsindex 8a2737442..34749420b 100644--- a/server/src/workers/tracking-worker.js+++ b/server/src/workers/tracking-worker.js@@ -87,6 +87,7 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,// loop bound how long a stuck Cloro queue can delay the stamp.const isFullRun = !promptId && (!promptIds || promptIds.length === 0);let trackingRunId = null;+ let trackingRunStartedAt = null;if (isFullRun) {// A run that died mid-flight (crash, abort) leaves an uncompleted row;// clear those so at most one in-progress row exists per brand.@@ -99,13 +100,14 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const { data: runRow, error: runErr } = await supabaseAdmin.from('tracking_runs').insert({ brand_id: brandId, source: source || 'manual' })- .select('id')+ .select('id, started_at').single();if (runErr) {// Ledger failure must never block tracking itself.logger.warn({ err: runErr, brandId }, 'failed to create tracking_runs row');} else {trackingRunId = runRow.id;+ trackingRunStartedAt = runRow.started_at;}}@@ -519,20 +521,37 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,logger.error({ err, brandId }, 'failed to check opportunity generation eligibility');}- // Stamp the ledger row. Zero results (every task failed) deletes the row- // instead: completing it would swing the 24h anchor onto an empty window,- // and leaving it open would pin the "in progress" banner — the dashboard- // keeps showing the previous completed run either way.+ // Stamp the ledger row. The run's result count MUST come from the DB, not+ // from `insertedCount`: in webhook mode the scraper results are inserted by+ // the /cloro/callback handler, so the worker's own counter only sees the+ // API-model phase — on scraper-only brands it stays 0 even after a fully+ // successful run, and the first deploy of this ledger deleted every real+ // run's row because of it. Zero results in the DB (every task genuinely+ // failed) still deletes the row: completing it would swing the 24h anchor+ // onto an empty window. On a count error we leave the row uncompleted —+ // the dashboard keeps the previous completed run and the next run clears+ // the dangling row.if (trackingRunId) {- if (insertedCount > 0) {+ const { count: runResultCount, error: countErr } = await supabaseAdmin+ .from('prompt_results')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .gte('created_at', trackingRunStartedAt);++ if (countErr) {+ logger.error({ err: countErr, brandId, trackingRunId }, 'failed to count run results');+ } else if ((runResultCount ?? 0) > 0) {const { error: stampErr } = await supabaseAdmin.from('tracking_runs')- .update({ completed_at: new Date().toISOString(), result_count: insertedCount })+ .update({ completed_at: new Date().toISOString(), result_count: runResultCount }).eq('id', trackingRunId);if (stampErr) {logger.error({ err: stampErr, brandId, trackingRunId }, 'failed to stamp tracking run');+ } else {+ logger.info({ brandId, trackingRunId, runResultCount }, 'tracking run stamped');}} else {+ logger.warn({ brandId, trackingRunId }, 'tracking run produced no results — row removed');await supabaseAdmin.from('tracking_runs').delete().eq('id', trackingRunId);}}