Skip to content

Open source alternative to Semrush and Ahrefs

Retry errored and suspect rank checks through the queue, keeping the best position (#953)

Carter Smith965a03e74b75
diff --git a/src/client/features/rank-tracking/CheckConfirmModal.tsx b/src/client/features/rank-tracking/CheckConfirmModal.tsx
index c7afdfcc..67b73804 100644
--- a/src/client/features/rank-tracking/CheckConfirmModal.tsx
+++ b/src/client/features/rank-tracking/CheckConfirmModal.tsx
@@ -43,7 +43,7 @@ export function CheckConfirmModal({
{costUsd != null ? (
<>
{" "}
- Costs about{" "}
+ Costs up to{" "}
<span className="font-mono font-semibold text-foreground">
${costUsd.toFixed(2)}
</span>
diff --git a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
index e1de967e..c3d6bdc1 100644
--- a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
+++ b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
@@ -401,15 +401,15 @@ function CostEstimate({
<div className="space-y-0.5 rounded-lg bg-muted px-3 py-2.5 text-xs text-muted-foreground">
<div>
<span className="font-mono font-semibold text-foreground">
- ~${costPerKeyword.toFixed(4)}
+ up to ${costPerKeyword.toFixed(4)}
</span>{" "}
per keyword per check
</div>
{schedule !== "manual" && (
<div>
- 50 keywords would cost{" "}
+ 50 keywords would cost up to{" "}
<span className="font-mono font-semibold text-foreground">
- ~${(costPerKeyword * 50 * checksPerMonth).toFixed(2)}
+ ${(costPerKeyword * 50 * checksPerMonth).toFixed(2)}
</span>
/month
</div>
diff --git a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
index 50e8b2c2..2040219e 100644
--- a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
@@ -91,7 +91,7 @@ export function RankTrackingDetailHeader({
</>
)}
{costEstimate && costEstimate.keywordCount > 0 && (
- <> &middot; ~${costEstimate.costUsd.toFixed(2)}/check</>
+ <> &middot; up to ${costEstimate.costUsd.toFixed(2)}/check</>
)}
</p>
</div>
diff --git a/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts b/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
index 0d1ecb89..fc3dff0d 100644
--- a/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
+++ b/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
@@ -29,6 +29,16 @@ beforeAll(async () => {
client = createClient({ url: "file::memory:" });
testDb = drizzle(client);
vi.doMock("@/db", () => ({ db: testDb }));
+ // Run batched writes one by one against the same in-memory database.
+ vi.doMock("@/db/runBatch", () => ({
+ DB_BATCH_SIZE: 100,
+ executeInBatches: async <T>(
+ items: T[],
+ build: (tx: typeof testDb, item: T) => Promise<unknown>,
+ ) => {
+ for (const item of items) await build(testDb, item);
+ },
+ }));
await client.executeMultiple(`
CREATE TABLE projects (
@@ -83,8 +93,12 @@ beforeAll(async () => {
keyword TEXT NOT NULL,
device TEXT NOT NULL,
position INTEGER,
- checked_at TEXT NOT NULL
+ url TEXT,
+ serp_features TEXT,
+ checked_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
+ CREATE UNIQUE INDEX rank_snapshots_run_keyword_device_idx
+ ON rank_snapshots (run_id, tracking_keyword_id, device);
`);
({ RankTrackingRepository } = await import("./RankTrackingRepository"));
@@ -371,3 +385,68 @@ describe("getConfigTrend", () => {
]);
});
});
+
+async function seedRun(id: string, status: string) {
+ await client.execute({
+ sql: "INSERT INTO rank_check_runs (id, config_id, project_id, status, started_at) VALUES (?, 'cfg_a', 'proj_1', ?, ?)",
+ args: [id, status, NOW],
+ });
+}
+
+function snapshotRow(
+ runId: string,
+ trackingKeywordId: string,
+ device: "desktop" | "mobile",
+ position: number | null,
+) {
+ return { runId, trackingKeywordId, keyword: "kw", device, position };
+}
+
+describe("retry snapshot queries", () => {
+ it("finds each keyword's best position on any device from completed runs only", async () => {
+ await seedRun("run_done", "completed");
+ await seedRun("run_active", "running");
+ await RankTrackingRepository.insertSnapshots([
+ snapshotRow("run_done", "kw_ranked", "desktop", null),
+ snapshotRow("run_done", "kw_ranked", "mobile", 4),
+ snapshotRow("run_done", "kw_never", "desktop", null),
+ snapshotRow("run_active", "kw_never", "mobile", 1),
+ ]);
+
+ const best =
+ await RankTrackingRepository.getBestPositionsForKeywords("cfg_a");
+
+ expect(best).toEqual(
+ expect.arrayContaining([
+ { trackingKeywordId: "kw_never", position: null },
+ { trackingKeywordId: "kw_ranked", position: 4 },
+ ]),
+ );
+ });
+
+ it("upserts a retry's result over the saved one, and keeps it through miss cleanup", async () => {
+ await seedRun("run_a", "running");
+ await RankTrackingRepository.insertSnapshots([
+ snapshotRow("run_a", "kw_0", "desktop", null),
+ ]);
+
+ await RankTrackingRepository.upsertSnapshots([
+ snapshotRow("run_a", "kw_0", "desktop", 2),
+ snapshotRow("run_a", "kw_1", "desktop", 7),
+ ]);
+
+ // Cleanup of unconfirmed misses never removes a row that holds a position.
+ await RankTrackingRepository.deleteNotFoundSnapshots([
+ { runId: "run_a", trackingKeywordId: "kw_0", device: "desktop" },
+ ]);
+
+ const rows = await RankTrackingRepository.getSnapshotsForRun("run_a");
+ expect(rows).toHaveLength(2);
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ trackingKeywordId: "kw_0", position: 2 }),
+ expect.objectContaining({ trackingKeywordId: "kw_1", position: 7 }),
+ ]),
+ );
+ });
+});
diff --git a/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts b/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
index 5db0d0cd..b61ad762 100644
--- a/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
+++ b/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
@@ -21,6 +21,7 @@ import { DB_BATCH_SIZE, executeInBatches } from "@/db/runBatch";
import type { RankTrackingSkipReason } from "@/shared/rank-tracking";
import {
getLatestSnapshotsForKeywords,
+ getBestPositionsForKeywords,
getSnapshotsBeforeDate,
getEarliestSnapshotsForKeywords,
getKeywordHistory,
@@ -35,6 +36,8 @@ import {
getLatestRunForConfig,
getActiveRunForConfig,
insertSnapshots,
+ upsertSnapshots,
+ deleteNotFoundSnapshots,
getSnapshotsForRun,
} from "./runQueries";
@@ -402,6 +405,8 @@ export const RankTrackingRepository = {
getLatestRunForConfig,
getActiveRunForConfig,
insertSnapshots,
+ upsertSnapshots,
+ deleteNotFoundSnapshots,
getSnapshotsForRun,
getKeywordsForConfig,
addKeywordsToConfig,
@@ -411,6 +416,7 @@ export const RankTrackingRepository = {
getKeywordCountsForConfigs,
getConfigSummaries,
getLatestSnapshotsForKeywords,
+ getBestPositionsForKeywords,
getSnapshotsBeforeDate,
getEarliestSnapshotsForKeywords,
getKeywordHistory,
diff --git a/src/server/features/rank-tracking/repositories/runQueries.ts b/src/server/features/rank-tracking/repositories/runQueries.ts
index 1e10128e..28c3c6dc 100644
--- a/src/server/features/rank-tracking/repositories/runQueries.ts
+++ b/src/server/features/rank-tracking/repositories/runQueries.ts
@@ -118,6 +118,56 @@ export async function insertSnapshots(
);
}
+/** Insert snapshots, replacing the result of any already saved for the pair. */
+export async function upsertSnapshots(
+ snapshots: Array<
+ Omit<InferInsertModel<typeof rankSnapshots>, "id" | "checkedAt">
+ >,
+) {
+ await executeInBatches(snapshots, (tx, snapshot) =>
+ tx
+ .insert(rankSnapshots)
+ .values(snapshot)
+ .onConflictDoUpdate({
+ target: [
+ rankSnapshots.runId,
+ rankSnapshots.trackingKeywordId,
+ rankSnapshots.device,
+ ],
+ set: {
+ position: snapshot.position,
+ url: snapshot.url,
+ serpFeatures: snapshot.serpFeatures,
+ },
+ }),
+ );
+}
+
+/**
+ * Delete "not found" snapshots, matched by run/keyword/device. A row that holds
+ * a position is left alone.
+ */
+export async function deleteNotFoundSnapshots(
+ keys: Array<{
+ runId: string;
+ trackingKeywordId: string;
+ device: "desktop" | "mobile";
+ }>,
+) {
+ await executeInBatches(keys, (tx, key) =>
+ tx
+ .delete(rankSnapshots)
+ .where(
+ and(
+ eq(rankSnapshots.runId, key.runId),
+ eq(rankSnapshots.trackingKeywordId, key.trackingKeywordId),
+ eq(rankSnapshots.device, key.device),
+ isNull(rankSnapshots.position),
+ ),
+ ),
+ );
+}
+
export async function getSnapshotsForRun(runId: string) {
return db.select().from(rankSnapshots).where(eq(rankSnapshots.runId, runId));
}
diff --git a/src/server/features/rank-tracking/repositories/snapshotQueries.ts b/src/server/features/rank-tracking/repositories/snapshotQueries.ts
index 4d1ae6f5..78de5cae 100644
--- a/src/server/features/rank-tracking/repositories/snapshotQueries.ts
+++ b/src/server/features/rank-tracking/repositories/snapshotQueries.ts
@@ -33,6 +33,18 @@ function cutoffTimestamp(sinceDays: number): string {
);
}
+/** Best position each keyword has had on any device across completed runs. */
+export async function getBestPositionsForKeywords(configId: string) {
+ return db
+ .select({
+ trackingKeywordId: rankSnapshots.trackingKeywordId,
+ position: min(rankSnapshots.position),
+ })
+ .from(rankSnapshots)
+ .where(inArray(rankSnapshots.runId, completedRunIdsForConfig(configId)))
+ .groupBy(rankSnapshots.trackingKeywordId);
+}
+
/**
* Flat per-keyword position series across completed runs, ordered oldest first.
* `null` position = checked but not found within serpDepth (a real event, not a
diff --git a/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts b/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
index 15f95d06..cc2ed83d 100644
--- a/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
@@ -203,7 +203,7 @@ function scheduledApprovalError(
) {
return new AppError(
"VALIDATION_ERROR",
- `Adding these keywords would make each ${scheduleInterval} scheduled check cost a nominal queued estimate of ${estimate.costCredits} credits (~$${estimate.costUsd.toFixed(4)} per check; ~${estimate.monthlyCostCredits} credits/month). Call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate and live-fallback caveat to the user, then retry with maxEstimatedScheduledCheckCredits set to the approved per-check estimate. Live fallback for rejected, failed, or timed-out queued tasks may use additional separately billed credits.`,
+ `Adding these keywords would make each ${scheduleInterval} scheduled check cost up to ${estimate.costCredits} credits including retries (~$${estimate.costUsd.toFixed(4)} per check; up to ~${estimate.monthlyCostCredits} credits/month). Call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate to the user, then retry with maxEstimatedScheduledCheckCredits set to the approved per-check estimate.`,
);
}
diff --git a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts b/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
index 04ec00d7..b1dbc554 100644
--- a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
@@ -124,8 +124,7 @@ describe("RankTrackingService management invariants", () => {
expect(error).toBeInstanceOf(Error);
if (!(error instanceof Error) || !("code" in error)) throw error;
expect(error.code).toBe("VALIDATION_ERROR");
- expect(error.message).toContain("nominal queued estimate");
- expect(error.message).toContain("Live fallback");
+ expect(error.message).toContain("including retries");
expect(mocks.addKeywordsToConfig).not.toHaveBeenCalled();
});
@@ -147,14 +146,14 @@ describe("RankTrackingService management invariants", () => {
["seo", "technical seo"],
{
kind: "credit_ceiling",
- maxEstimatedScheduledCheckCredits: 4,
+ maxEstimatedScheduledCheckCredits: 12,
},
),
).resolves.toMatchObject({
added: 2,
scheduledEstimate: {
scheduleInterval: "weekly",
- costCredits: 4,
+ costCredits: 12,
checksPerMonth: 4,
},
});
@@ -182,7 +181,7 @@ describe("RankTrackingService management invariants", () => {
["seo", "technical seo"],
{
kind: "credit_ceiling",
- maxEstimatedScheduledCheckCredits: 4,
+ maxEstimatedScheduledCheckCredits: 12,
},
).catch((cause: unknown) => cause);
expect(error).toBeInstanceOf(Error);
@@ -267,19 +266,19 @@ describe("RankTrackingService management invariants", () => {
const error: unknown = await RankTrackingService.triggerCheck({
...run,
- maxCostCredits: 11,
+ maxCostCredits: 19,
}).catch((cause: unknown) => cause);
expect(error).toBeInstanceOf(Error);
if (!(error instanceof Error) || !("code" in error)) throw error;
expect(error.code).toBe("VALIDATION_ERROR");
- expect(error.message).toContain("costs 12 credits");
+ expect(error.message).toContain("costs 20 credits");
expect(mocks.beginRankCheckRun).not.toHaveBeenCalled();
await expect(
- RankTrackingService.triggerCheck({ ...run, maxCostCredits: 12 }),
+ RankTrackingService.triggerCheck({ ...run, maxCostCredits: 20 }),
).resolves.toEqual({ ok: true, runId: "run_1" });
expect(mocks.beginRankCheckRun).toHaveBeenCalledWith(
- expect.objectContaining({ maxCostCredits: 12 }),
+ expect.objectContaining({ maxCostCredits: 20 }),
);
});
diff --git a/src/server/features/rank-tracking/services/scheduledRankChecks.ts b/src/server/features/rank-tracking/services/scheduledRankChecks.ts
index c24cd578..6d467f00 100644
--- a/src/server/features/rank-tracking/services/scheduledRankChecks.ts
+++ b/src/server/features/rank-tracking/services/scheduledRankChecks.ts
@@ -17,8 +17,8 @@ import {
// and up to three ticks' ~15-minute poll windows overlap the */5 cron — so a
// full tick can burst ~1,000 polls into a single minute, stacking with the
// residual rounds of the two prior ticks. Overruns aren't
-// loud failures: throttled polls age into the live fallback at ~3× cost,
-// billed to the customer, so keep real headroom under the cap.
+// loud failures: throttled polls leave tasks unfinished, which are retried
+// and billed to the customer again, so keep real headroom under the cap.
// 1,000/tick ≈ 288,000 units/day, ~45× steady-state demand — it only binds
// during backlog catch-up.
const SCHEDULED_TASK_UNIT_BUDGET = 1000;
diff --git a/src/server/lib/dataforseo/pricing.test.ts b/src/server/lib/dataforseo/pricing.test.ts
index fc4bdcb1..77c7ff1d 100644
--- a/src/server/lib/dataforseo/pricing.test.ts
+++ b/src/server/lib/dataforseo/pricing.test.ts
@@ -161,14 +161,15 @@ describe("dataforseoPricing", () => {
depth: 20,
targetDomain: "example.com",
});
- expect(creditsForProviderUsd(estimateUsd)).toBe(
+ // The estimate is the worst case: this post plus two queued retries.
+ expect(3 * creditsForProviderUsd(estimateUsd)).toBe(
estimateRankCheckCredits(keywords, "desktop", 20, "queued").costCredits,
);
});
it("prices a live operator rank check the way the rank check estimate does", () => {
const keyword = "site:example.com seo";
- const estimateUsd = dataforseoPricing.serp.rankCheck({
+ const liveUsd = dataforseoPricing.serp.rankCheck({
keyword,
keywordId: "id",
...location,
@@ -176,7 +177,16 @@ describe("dataforseoPricing", () => {
depth: 20,
targetDomain: "example.com",
});
- expect(creditsForProviderUsd(estimateUsd)).toBe(
+ const retryUsd = dataforseoPricing.serp.rankCheckTaskPost({
+ tasks: [{ keyword, keywordId: "id", device: "desktop" }],
+ ...location,
+ depth: 20,
+ targetDomain: "example.com",
+ });
+ // The estimate is the worst case: the live call plus two queued retries.
+ expect(
+ creditsForProviderUsd(liveUsd) + 2 * creditsForProviderUsd(retryUsd),
+ ).toBe(
estimateRankCheckCredits([keyword], "desktop", 20, "live").costCredits,
);
});
diff --git a/src/server/lib/dataforseo/serp.ts b/src/server/lib/dataforseo/serp.ts
index b3f3e495..b63d696a 100644
--- a/src/server/lib/dataforseo/serp.ts
+++ b/src/server/lib/dataforseo/serp.ts
@@ -206,8 +206,8 @@ export async function fetchRankCheckSerp(input: {
// ---------------------------------------------------------------------------
// Task-queue rank checks (scheduled runs). DataForSEO's standard queue costs
// ~30% of the live endpoint; tasks complete in ~5 minutes on average. The flow
-// is task_post (charged) -> poll task_get (free) -> live fallback for
-// stragglers, orchestrated by the rank check workflow.
+// is task_post (charged) -> poll task_get (free), orchestrated by the rank
+// check workflow, which retries stragglers through the queue.
// ---------------------------------------------------------------------------
export interface RankCheckTaskInput {
diff --git a/src/server/mcp/tools/add-rank-tracking-keywords.ts b/src/server/mcp/tools/add-rank-tracking-keywords.ts
index 1c329f36..db482bfe 100644
--- a/src/server/mcp/tools/add-rank-tracking-keywords.ts
+++ b/src/server/mcp/tools/add-rank-tracking-keywords.ts
@@ -30,7 +30,7 @@ const inputSchema = {
.positive()
.optional()
.describe(
- "Nominal queued credits per scheduled check that the user approved after seeing estimate_rank_tracker_cost with additionalKeywords. Required for scheduled trackers. This is an estimate approval, not a runtime cap; live fallback may add separately billed credits.",
+ "Most credits per scheduled check, including retries, that the user approved after seeing estimate_rank_tracker_cost with additionalKeywords. Required for scheduled trackers.",
),
} as const;
@@ -41,7 +41,7 @@ export const addRankTrackingKeywordsTool = {
config: {
title: "Add rank tracking keywords",
description:
- "Add keywords to an existing rank tracker. The mutation itself uses no credits and does not start a check or fetch metrics, but scheduled trackers will spend credits on future recurring public Google searches. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate and live-fallback caveat to the user, and pass the approved nominal per-check estimate as maxEstimatedScheduledCheckCredits. This approval is not a runtime spending cap: rejected, failed, or timed-out queued tasks may use additional separately billed live fallback. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",
+ "Add keywords to an existing rank tracker. The mutation itself uses no credits and does not start a check or fetch metrics, but scheduled trackers will spend credits on future recurring public Google searches. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate to the user, and pass the approved per-check estimate as maxEstimatedScheduledCheckCredits. The estimate is the most a check can cost, including retries. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",
inputSchema,
outputSchema: z
.object({
@@ -82,7 +82,7 @@ export const addRankTrackingKeywordsTool = {
);
const requested = args.keywords.length;
return mcpResponse({
- text: `Added ${result.added} of ${requested} requested keyword${requested === 1 ? "" : "s"} to tracker ${args.trackerId}. No check was started and no credits were used.${result.scheduledEstimate ? ` Future ${result.scheduledEstimate.scheduleInterval} checks have a nominal estimate of ${result.scheduledEstimate.costCredits} credits each (~${result.scheduledEstimate.monthlyCostCredits} credits/month); live fallback may add separately billed credits.` : ""}`,
+ text: `Added ${result.added} of ${requested} requested keyword${requested === 1 ? "" : "s"} to tracker ${args.trackerId}. No check was started and no credits were used.${result.scheduledEstimate ? ` Future ${result.scheduledEstimate.scheduleInterval} checks cost at most ${result.scheduledEstimate.costCredits} credits each, including retries (up to ~${result.scheduledEstimate.monthlyCostCredits} credits/month).` : ""}`,
meta: buildProjectMeta(
context,
args.projectId,
diff --git a/src/server/mcp/tools/estimate-rank-tracker-cost.ts b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
index 376d3932..33905938 100644
--- a/src/server/mcp/tools/estimate-rank-tracker-cost.ts
+++ b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
@@ -37,7 +37,7 @@ export const estimateRankTrackerCostTool = {
config: {
title: "Estimate rank tracker cost",
description:
- "Estimate rank tracker cost without spending credits or starting a check. The live estimate covers one explicit run_rank_tracker check. For a scheduled tracker, the response also includes nominal queued per-check and approximate monthly recurring cost. Pass additionalKeywords before adding keywords to project the post-add cost. Scheduled estimates are not runtime caps; rejected, failed, or timed-out queued tasks may use additional separately billed live fallback.",
+ "Estimate rank tracker cost without spending credits or starting a check. Each estimate is the most a check can cost: it includes up to two queued retries of every keyword/device check, which run only for checks that error or read as lost, so most checks cost less. The live estimate covers one explicit run_rank_tracker check. For a scheduled tracker, the response also includes the queued per-check and approximate monthly recurring cost. Pass additionalKeywords before adding keywords to project the post-add cost.",
inputSchema,
outputSchema: z
.object({
@@ -78,7 +78,7 @@ export const estimateRankTrackerCostTool = {
Array<string>(args.additionalKeywordCount ?? 0).fill(""),
);
return mcpResponse({
- text: `One live check for tracker ${args.trackerId} is estimated at $${estimate.costUsd.toFixed(4)} (${estimate.costCredits} credits): ${estimate.keywordCount} keyword${estimate.keywordCount === 1 ? "" : "s"} × ${estimate.devicesCount} device${estimate.devicesCount === 1 ? "" : "s"} = ${estimate.totalChecks} SERP checks.${estimate.additionalKeywordCount > 0 ? ` This projects ${estimate.additionalKeywordCount} additional keyword${estimate.additionalKeywordCount === 1 ? "" : "s"}.` : ""}${estimate.scheduledEstimate ? ` Its ${estimate.scheduledEstimate.scheduleInterval} queued checks have a nominal estimate of $${estimate.scheduledEstimate.costUsd.toFixed(4)} (${estimate.scheduledEstimate.costCredits} credits) each, or about $${estimate.scheduledEstimate.monthlyCostUsd.toFixed(4)} (${estimate.scheduledEstimate.monthlyCostCredits} credits) per month. Show the user that rejected, failed, or timed-out queued tasks may use additional separately billed live fallback, then use the per-check estimate as maxEstimatedScheduledCheckCredits when adding keywords.` : ""} No check was started.`,
+ text: `One live check for tracker ${args.trackerId} costs at most $${estimate.costUsd.toFixed(4)} (${estimate.costCredits} credits, including retries): ${estimate.keywordCount} keyword${estimate.keywordCount === 1 ? "" : "s"} × ${estimate.devicesCount} device${estimate.devicesCount === 1 ? "" : "s"} = ${estimate.totalChecks} SERP checks.${estimate.additionalKeywordCount > 0 ? ` This projects ${estimate.additionalKeywordCount} additional keyword${estimate.additionalKeywordCount === 1 ? "" : "s"}.` : ""}${estimate.scheduledEstimate ? ` Its ${estimate.scheduledEstimate.scheduleInterval} queued checks cost at most $${estimate.scheduledEstimate.costUsd.toFixed(4)} (${estimate.scheduledEstimate.costCredits} credits) each, or up to about $${estimate.scheduledEstimate.monthlyCostUsd.toFixed(4)} (${estimate.scheduledEstimate.monthlyCostCredits} credits) per month. Use the per-check estimate as maxEstimatedScheduledCheckCredits when adding keywords.` : ""} No check was started.`,
meta: buildProjectMeta(
context,
args.projectId,
diff --git a/src/server/workflows/RankCheckWorkflow.test.ts b/src/server/workflows/RankCheckWorkflow.test.ts
index 53e504bc..034008d3 100644
--- a/src/server/workflows/RankCheckWorkflow.test.ts
+++ b/src/server/workflows/RankCheckWorkflow.test.ts
@@ -34,6 +34,7 @@ vi.mock("@/server/features/rank-tracking/services/rankCheckRunGuards", () => ({
vi.mock("@/server/workflows/rankCheckPaths", () => ({
runLiveCheck: mocks.runLiveCheck,
runQueuedCheck: vi.fn(),
+ retryRankChecks: vi.fn(),
}));
vi.mock("@/server/workflows/pgStep", () => ({
pgStep: (
@@ -117,7 +118,7 @@ describe("rank check workflow credit ceiling", () => {
it("rejects a keyword-list race before balance or DataForSEO calls", async () => {
mocks.getKeywordsForConfig.mockResolvedValue(keywords(5));
- await expect(runWorkflow({ maxCostCredits: 12 })).rejects.toMatchObject({
+ await expect(runWorkflow({ maxCostCredits: 20 })).rejects.toMatchObject({
code: "VALIDATION_ERROR",
});
@@ -130,7 +131,7 @@ describe("rank check workflow credit ceiling", () => {
// callers without a ceiling — every scheduled check — must not be treated
// as approving zero credits.
it.each([
- ["at the approved ceiling", 12, 4],
+ ["at the approved ceiling", 20, 4],
["without a ceiling", undefined, 5],
])("checks the reloaded list %s", async (_label, maxCostCredits, count) => {
mocks.getKeywordsForConfig.mockResolvedValue(keywords(count));
diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.ts
index 9facaeef..84942e7c 100644
--- a/src/server/workflows/RankCheckWorkflow.ts
+++ b/src/server/workflows/RankCheckWorkflow.ts
@@ -9,9 +9,9 @@ import type { BillingCustomerContext } from "@/server/billing/subscription";
import { RankTrackingRepository } from "@/server/features/rank-tracking/repositories/RankTrackingRepository";
import { failRunIfActive } from "@/server/features/rank-tracking/services/rankCheckRunGuards";
import {
+ retryRankChecks,
runLiveCheck,
runQueuedCheck,
- type QueuedCheckStats,
} from "@/server/workflows/rankCheckPaths";
import { pgStep } from "@/server/workflows/pgStep";
import { createDataforseoClient } from "@/server/lib/dataforseo";
@@ -101,6 +101,7 @@ async function prepareRankCheckKeywords(input: {
// Verify the user has enough credits for the full check before starting.
// Scheduled checks go through the cheaper task queue, so estimate at queued
// pricing — a live-price estimate would skip checks the user can afford.
+ // The estimate is the worst case, so it covers every retry.
if (await isHostedServerAuthMode()) {
const [monthlyCheck, topupCheck] = await Promise.all([
autumn.check({
@@ -143,7 +144,6 @@ async function finalizeRankCheckRun(input: {
trigger: RankCheckParams["trigger"];
devices: RankCheckParams["devices"];
batchError: string | null;
- queueStats: QueuedCheckStats | null;
}) {
// If stale-cleanup already marked our run failed, don't overwrite that
// decision with a completed status — a replacement run may already be
@@ -218,17 +218,13 @@ async function finalizeRankCheckRun(input: {
});
}
- // One-line summary per run so fallback rates are visible in Workers Logs.
- // Keys match the PostHog event properties for log/event correlation.
- const queueSummary = input.queueStats
- ? ` queue_tasks=${input.queueStats.queueTasks} queue_collected=${input.queueStats.queueCollected} fallback_tasks=${input.queueStats.fallbackTasks} fallback_checked=${input.queueStats.fallbackChecked}`
- : "";
+ // One-line summary per run, visible in Workers Logs.
// Error text can echo vendor/user content — keep it one line and bounded.
const errorSummary = errorMessage
? ` error="${errorMessage.replace(/\s+/g, " ").slice(0, 200)}"`
: "";
console.log(
- `[rank-check] ${input.runId} ${status} org=${input.billingCustomer.organizationId} project=${input.projectId} trigger=${input.trigger} keywords=${keywordsChecked}/${keywordsTotal}${queueSummary}${errorSummary}`,
+ `[rank-check] ${input.runId} ${status} org=${input.billingCustomer.organizationId} project=${input.projectId} trigger=${input.trigger} keywords=${keywordsChecked}/${keywordsTotal}${errorSummary}`,
);
await captureServerEvent({
@@ -240,14 +236,6 @@ async function finalizeRankCheckRun(input: {
status,
trigger: input.trigger,
keywords_checked: keywordsChecked,
- ...(input.queueStats
- ? {
- queue_tasks: input.queueStats.queueTasks,
- queue_collected: input.queueStats.queueCollected,
- fallback_tasks: input.queueStats.fallbackTasks,
- fallback_checked: input.queueStats.fallbackChecked,
- }
- : {}),
},
});
}
@@ -364,7 +352,6 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<
console.log(`[rank-check] ${runId} loaded ${keywords.length} keywords`);
let batchError: string | null = null;
- let queueStats: QueuedCheckStats | null = null;
try {
const checkContext = {
@@ -379,12 +366,14 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<
runId,
};
// Scheduled checks use DataForSEO's task queue (~30% of live cost);
- // manual checks stay on the live endpoint for instant results, and
- // only the pairs the live endpoint missed go to the queue.
- queueStats =
- trigger === "scheduled"
- ? await runQueuedCheck(step, checkContext)
- : await runLiveCheck(step, checkContext);
+ // manual checks stay on the live endpoint for instant results.
+ // Retries always go through the queue.
+ if (trigger === "scheduled") {
+ await runQueuedCheck(step, checkContext);
+ } else {
+ await runLiveCheck(step, checkContext);
+ }
+ await retryRankChecks(step, checkContext, configId);
} catch (error) {
// Batch failure — snapshots for completed batches are already
// persisted incrementally. Continue to finalization.
@@ -401,7 +390,6 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<
trigger,
devices,
batchError,
- queueStats,
}),
);
} catch (error) {
diff --git a/src/server/workflows/rankCheckPaths.test.ts b/src/server/workflows/rankCheckPaths.test.ts
index d55759b9..f3238077 100644
--- a/src/server/workflows/rankCheckPaths.test.ts
+++ b/src/server/workflows/rankCheckPaths.test.ts
@@ -1,11 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { WorkflowStep } from "cloudflare:workers";
import type { RankCheckTaskInput } from "@/server/lib/dataforseo";
-import { runLiveCheck } from "./rankCheckPaths";
+import { retryRankChecks, runLiveCheck } from "./rankCheckPaths";
const mocks = vi.hoisted(() => ({
getSnapshotsForRun: vi.fn(),
+ getBestPositionsForKeywords: vi.fn(),
insertSnapshots: vi.fn(),
+ upsertSnapshots: vi.fn(),
+ deleteNotFoundSnapshots: vi.fn(),
+ setRunErrorIfEmpty: vi.fn(),
updateRun: vi.fn(),
fetchRankCheckTaskResult: vi.fn(),
rankCheckBatch: vi.fn(),
@@ -29,123 +33,131 @@ vi.mock("@/server/workflows/pgStep", () => ({
) => fn(),
}));
-const keywords = Array.from({ length: 11 }, (_, index) => ({
- id: `kw_${index}`,
- keyword: `keyword ${index}`,
-}));
+// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only sleep is reached; pgStep is mocked
+const step = { sleep: vi.fn() } as unknown as WorkflowStep;
+
+function checkContext(keywordIds: string[]) {
+ return {
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the check paths only call these two serp methods
+ client: {
+ serp: {
+ rankCheckBatch: mocks.rankCheckBatch,
+ rankCheckTaskPost: mocks.rankCheckTaskPost,
+ },
+ } as never,
+ keywords: keywordIds.map((id) => ({ id, keyword: `keyword ${id}` })),
+ devices: "desktop" as const,
+ serpDepth: 10,
+ domain: "openseo.so",
+ locationCode: 2840,
+ languageCode: "en",
+ runId: "run_1",
+ };
+}
-function runManualCheck() {
- return runLiveCheck(
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only sleep is reached; pgStep is mocked
- { sleep: vi.fn() } as unknown as WorkflowStep,
- {
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the check paths only call these two serp methods
- client: {
- serp: {
- rankCheckBatch: mocks.rankCheckBatch,
- rankCheckTaskPost: mocks.rankCheckTaskPost,
- },
- } as never,
- keywords,
- devices: "desktop",
- serpDepth: 10,
- domain: "openseo.so",
- locationCode: 2840,
- languageCode: "en",
- runId: "run_1",
- },
- );
+function snapshot(keywordId: string, position: number | null) {
+ return { trackingKeywordId: keywordId, device: "desktop", position };
}
-describe("runLiveCheck", () => {
- beforeEach(() => {
- mocks.rankCheckBatch.mockImplementation(
- async (inputs: RankCheckTaskInput[]) =>
- inputs.map((input) => ({
- status: "fulfilled",
- value: { ...input, position: 3, url: null, serpFeatures: [] },
- })),
- );
- mocks.rankCheckTaskPost.mockImplementation(
- async ({ tasks }: { tasks: RankCheckTaskInput[] }) =>
- tasks.map((task) => ({ ...task, taskId: `task_${task.keywordId}` })),
- );
- mocks.fetchRankCheckTaskResult.mockImplementation(
+/** Each task_get answers with the next position. */
+function queuedResults(...positions: Array<number | null>) {
+ for (const position of positions) {
+ mocks.fetchRankCheckTaskResult.mockImplementationOnce(
async (task: RankCheckTaskInput) => ({
status: "completed",
- result: { ...task, position: 5, url: null, serpFeatures: [] },
+ result: { ...task, position, url: null, serpFeatures: [] },
}),
);
- });
+ }
+}
- it("keeps going after a failed live batch and queues only the missing pairs", async () => {
- // The first batch step dies after its calls; the second batch saves kw_10.
+beforeEach(() => {
+ mocks.rankCheckBatch.mockImplementation(
+ async (inputs: RankCheckTaskInput[]) =>
+ inputs.map((input) => ({
+ status: "fulfilled",
+ value: { ...input, position: 3, url: null, serpFeatures: [] },
+ })),
+ );
+ mocks.rankCheckTaskPost.mockImplementation(
+ async ({ tasks }: { tasks: RankCheckTaskInput[] }) =>
+ tasks.map((task) => ({ ...task, taskId: `task_${task.keywordId}` })),
+ );
+ mocks.fetchRankCheckTaskResult.mockImplementation(
+ async (task: RankCheckTaskInput) => ({
+ status: "completed",
+ result: { ...task, position: 5, url: null, serpFeatures: [] },
+ }),
+ );
+ mocks.getBestPositionsForKeywords.mockResolvedValue([
+ { trackingKeywordId: "kw_0", position: 1 },
+ { trackingKeywordId: "kw_never", position: null },
+ ]);
+});
+
+describe("runLiveCheck", () => {
+ it("keeps going after a failed live batch", async () => {
mocks.insertSnapshots.mockRejectedValueOnce(new Error("step timed out"));
- mocks.getSnapshotsForRun.mockResolvedValue([
- { trackingKeywordId: "kw_10", device: "desktop" },
- ]);
- const stats = await runManualCheck();
+ await runLiveCheck(
+ step,
+ checkContext(Array.from({ length: 11 }, (_, i) => `kw_${i}`)),
+ );
expect(mocks.rankCheckBatch).toHaveBeenCalledTimes(2);
- expect(mocks.rankCheckTaskPost).toHaveBeenCalledOnce();
- expect(mocks.rankCheckTaskPost).toHaveBeenCalledWith(
- expect.objectContaining({
- tasks: keywords
- .slice(0, 10)
- .map((kw): unknown => expect.objectContaining({ keywordId: kw.id })),
- }),
- );
- expect(stats).toMatchObject({ queueTasks: 10, queueCollected: 10 });
});
+});
- it("makes no second live call when a queued retry fails", async () => {
+describe("retryRankChecks", () => {
+ it("retries a check that errored through the queue, keeping a not found for a keyword that never ranked", async () => {
mocks.getSnapshotsForRun.mockResolvedValue([]);
- mocks.fetchRankCheckTaskResult.mockResolvedValue({
- status: "failed",
- message: "Internal SE Server Error.",
- });
+ queuedResults(null);
- const stats = await runManualCheck();
+ await retryRankChecks(step, checkContext(["kw_never"]), "config_1");
- // Two live batches, then no live fallback for the failed queue tasks:
- // that call could exceed the credits the user approved.
- expect(mocks.rankCheckBatch).toHaveBeenCalledTimes(2);
- expect(stats).toMatchObject({ queueTasks: 11, fallbackTasks: 0 });
+ expect(mocks.rankCheckBatch).not.toHaveBeenCalled();
+ expect(mocks.rankCheckTaskPost).toHaveBeenCalledOnce();
+ expect(mocks.upsertSnapshots).toHaveBeenCalledWith([
+ expect.objectContaining({
+ trackingKeywordId: "kw_never",
+ position: null,
+ }),
+ ]);
+ expect(mocks.deleteNotFoundSnapshots).not.toHaveBeenCalled();
});
- it("leaves a pair unchecked when its queued retry doesn't find the domain", async () => {
- mocks.getSnapshotsForRun.mockResolvedValue([]);
- mocks.fetchRankCheckTaskResult.mockImplementation(
- async (task: RankCheckTaskInput) => ({
- status: "completed",
- result: {
- ...task,
- position: task.keywordId === "kw_0" ? null : 5,
- url: null,
- serpFeatures: [],
- },
- }),
- );
+ it("retries a keyword that lost its known rank and keeps the best position found", async () => {
+ mocks.getSnapshotsForRun.mockResolvedValue([
+ snapshot("kw_0", null),
+ snapshot("kw_never", null),
+ ]);
+ queuedResults(15, 20);
- await runManualCheck();
+ await retryRankChecks(step, checkContext(["kw_0", "kw_never"]), "config_1");
- // The queue round saves every pair except kw_0's not-found.
- expect(mocks.insertSnapshots).toHaveBeenLastCalledWith(
- keywords
- .slice(1)
- .map((kw): unknown =>
- expect.objectContaining({ trackingKeywordId: kw.id, position: 5 }),
- ),
+ // 15 is still far below #1, so it gets the second retry too.
+ expect(mocks.rankCheckTaskPost).toHaveBeenCalledTimes(2);
+ expect(mocks.rankCheckTaskPost).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tasks: [expect.objectContaining({ keywordId: "kw_0" })],
+ }),
);
+ expect(mocks.upsertSnapshots).toHaveBeenCalledOnce();
+ expect(mocks.upsertSnapshots).toHaveBeenCalledWith([
+ expect.objectContaining({ trackingKeywordId: "kw_0", position: 15 }),
+ ]);
});
- it("skips the queue when the live endpoint checked every pair", async () => {
- mocks.getSnapshotsForRun.mockResolvedValue(
- keywords.map((kw) => ({ trackingKeywordId: kw.id, device: "desktop" })),
- );
+ it("never saves a not found for a keyword that ranked before", async () => {
+ mocks.getSnapshotsForRun.mockResolvedValue([snapshot("kw_0", null)]);
+ queuedResults(null, null);
- expect(await runManualCheck()).toBeNull();
- expect(mocks.rankCheckTaskPost).not.toHaveBeenCalled();
+ await retryRankChecks(step, checkContext(["kw_0"]), "config_1");
+
+ expect(mocks.rankCheckTaskPost).toHaveBeenCalledTimes(2);
+ expect(mocks.upsertSnapshots).not.toHaveBeenCalled();
+ expect(mocks.deleteNotFoundSnapshots).toHaveBeenCalledWith([
+ { runId: "run_1", trackingKeywordId: "kw_0", device: "desktop" },
+ ]);
});
});
diff --git a/src/server/workflows/rankCheckPaths.ts b/src/server/workflows/rankCheckPaths.ts
index b3bc171f..1e527fcf 100644
--- a/src/server/workflows/rankCheckPaths.ts
+++ b/src/server/workflows/rankCheckPaths.ts
@@ -12,7 +12,7 @@ import type {
} from "@/server/lib/dataforseo";
import { AppError } from "@/server/lib/errors";
import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
-import { KEYWORDS_PER_BATCH } from "@/shared/rank-tracking";
+import { KEYWORDS_PER_BATCH, RETRY_ROUNDS } from "@/shared/rank-tracking";
import { pgStep } from "@/server/workflows/pgStep";
const SINGLE_ATTEMPT_STEP_CONFIG = {
@@ -141,18 +141,13 @@ async function checkBatchLive(
* Snapshots are written incrementally after each batch so partial results
* survive batch failures. ~6s per keyword batch.
* Each batch is billed with one credit hold and one settle (checkBatchLive).
- * A failed batch step doesn't stop the run. Afterwards, every keyword/device
- * pair still without a snapshot goes through the task queue (runQueuedCheck),
- * which retries timeouts and in-band task errors at queue price. Failed live
- * calls aren't billed, so the retry stays within the live estimate the user
- * approved. Exception: a step that died after its calls were metered gets
- * billed again at queue price. Returns the queue stats, or null when nothing
- * was missing.
+ * A failed batch step doesn't stop the run; its pairs are retried by
+ * retryRankChecks.
*/
export async function runLiveCheck(
step: WorkflowStep,
ctx: CheckContext,
-): Promise<QueuedCheckStats | null> {
+): Promise<void> {
for (let i = 0; i < ctx.keywords.length; i += KEYWORDS_PER_BATCH) {
const keywordBatch = ctx.keywords.slice(i, i + KEYWORDS_PER_BATCH);
const batchTasks = expandToTaskInputs(keywordBatch, ctx.devices);
@@ -174,60 +169,18 @@ export async function runLiveCheck(
},
);
} catch (error) {
- // Earlier batches are already saved; this batch's pairs go to the
- // queue below.
console.warn(
`[rank-check] ${ctx.runId} live-batch-${batchIndex} failed:`,
error,
);
}
}
-
- // Diff against the DB rather than batch return values, so pairs from a
- // batch step that threw are included too.
- const missing = await pgStep(
- step,
- "find-missing",
- COLLECT_STEP_CONFIG,
- async () => {
- const snapshots = await RankTrackingRepository.getSnapshotsForRun(
- ctx.runId,
- );
- const checked = new Set(
- snapshots.map((s) => `${s.trackingKeywordId}:${s.device}`),
- );
- // Live progress counts attempted keywords; reset it to the real count
- // while the queue runs.
- await RankTrackingRepository.updateRun(ctx.runId, {
- keywordsChecked: new Set(snapshots.map((s) => s.trackingKeywordId))
- .size,
- });
- return expandToTaskInputs(ctx.keywords, ctx.devices).filter(
- (t) => !checked.has(`${t.keywordId}:${t.device}`),
- );
- },
- );
- if (missing.length === 0) return null;
-
- console.log(
- `[rank-check] ${ctx.runId} queue fallback for ${missing.length} task(s)`,
- );
- // No live fallback here: these pairs already had their live attempt, and a
- // second one could take the run past the credits the user approved.
- // A "not found" from the queue isn't saved either: queued SERPs often miss a
- // domain the live endpoint finds, so the pair stays "Not checked" and keeps
- // its previous position instead of reading as lost.
- return runQueuedCheck(step, ctx, {
- taskInputs: missing,
- liveFallback: false,
- saveNotFound: false,
- });
}
// Poll cadence for queued tasks. Standard-priority tasks complete in ~5
// minutes on average, so the first check waits 4 minutes; cumulative waits are
-// 4 / 6 / 8 / 10 / 12 / 15 minutes, after which stragglers fall back to the
-// live endpoint.
+// 4 / 6 / 8 / 10 / 12 / 15 minutes, after which unfinished tasks are left for
+// retryRankChecks.
const QUEUED_POLL_INTERVALS = [
"4 minutes",
"2 minutes",
@@ -246,34 +199,26 @@ const TASK_GETS_PER_COLLECT = 500;
// Collect steps may issue hundreds of task_get calls, so they get more room
// than SINGLE_ATTEMPT_STEP_CONFIG's 2-minute timeout. Unlike the metered
// steps, retrying is safe and free: task_get isn't charged and snapshot
-// inserts are onConflictDoNothing.
+// writes are idempotent.
const COLLECT_STEP_CONFIG = {
retries: { limit: 2, delay: "10 seconds" as const },
timeout: "5 minutes" as const,
};
-interface CollectRoundOutcome {
- /** Snapshots written this round. */
- collected: number;
- /** Tasks still in DataForSEO's queue — poll again next round. */
- stillPending: PostedRankCheckTask[];
- /** Tasks DataForSEO failed — route to the live fallback. */
- failed: PostedRankCheckTask[];
-}
-
/**
- * Fetch results for queued tasks (one free task_get each), persist completed
- * snapshots, and update run progress. Transient task_get failures stay
- * pending for the next round.
+ * Fetch results for queued tasks (one free task_get each). Transient task_get
+ * failures stay pending for the next round; tasks DataForSEO failed are
+ * dropped.
*/
-async function collectQueuedRound(
+async function fetchQueuedRound(
ctx: CheckContext,
tasks: PostedRankCheckTask[],
- saveNotFound: boolean,
-): Promise<CollectRoundOutcome> {
+): Promise<{
+ completed: RankCheckResultWithDevice[];
+ stillPending: PostedRankCheckTask[];
+}> {
const completed: RankCheckResultWithDevice[] = [];
const stillPending: PostedRankCheckTask[] = [];
- const failed: PostedRankCheckTask[] = [];
for (let i = 0; i < tasks.length; i += TASK_GET_CONCURRENCY) {
const chunk = tasks.slice(i, i + TASK_GET_CONCURRENCY);
@@ -302,82 +247,36 @@ async function collectQueuedRound(
console.warn(
`[rank-check] ${ctx.runId} task ${task.taskId} failed: ${result.value.message}`,
);
- // No run error here: a live call records it. That is the live
- // fallback, or for a manual retry, the live attempt before the queue.
- failed.push(task);
- } else if (saveNotFound || result.value.result.position !== null) {
+ } else {
completed.push({ ...result.value.result, device: task.device });
}
});
}
-
- if (completed.length > 0) {
- await RankTrackingRepository.insertSnapshots(
- mapResultsToSnapshotRows(ctx.runId, completed),
- );
- // Progress for the UI; finalize recounts from the DB anyway.
- const snapshots = await RankTrackingRepository.getSnapshotsForRun(
- ctx.runId,
- );
- await RankTrackingRepository.updateRun(ctx.runId, {
- keywordsChecked: new Set(snapshots.map((s) => s.trackingKeywordId)).size,
- });
- }
-
- return { collected: completed.length, stillPending, failed };
-}
-
-/** Per-run accounting for the queued path, in keyword/device task units. */
-export interface QueuedCheckStats {
- /** Tasks accepted into DataForSEO's queue. */
- queueTasks: number;
- /** Task results collected from the queue within the polling window. */
- queueCollected: number;
- /** Tasks routed to the live fallback (rejected, failed, or timed out). */
- fallbackTasks: number;
- /** Fallback tasks that produced a snapshot. */
- fallbackChecked: number;
+ return { completed, stillPending };
}
/**
- * Check keywords via DataForSEO's standard task queue (~30% of live cost).
- * Posts every keyword/device pair (or just taskInputs) as a queued task, then
- * polls task_get for ~15 minutes, writing snapshots incrementally as tasks
- * complete. Anything still unfinished after the polling window — plus tasks
- * DataForSEO rejected or failed — gets one shot at the live endpoint so a run
- * never hangs on a stuck queue, unless `liveFallback` is false. With
- * `saveNotFound` false, a result without the domain isn't saved. Billing
- * happens at task_post (and per live-fallback batch).
+ * Post tasks to DataForSEO's standard queue (~30% of live cost), one metered
+ * step per 100, then poll task_get for ~15 minutes. `onCollected` runs inside
+ * each collect step with that round's results. A task that's rejected, fails
+ * or never finishes gets no result. Returns every collected result.
*/
-export async function runQueuedCheck(
+async function runQueuedTasks(
step: WorkflowStep,
ctx: CheckContext,
- {
- taskInputs = expandToTaskInputs(ctx.keywords, ctx.devices),
- liveFallback = true,
- saveNotFound = true,
- }: {
- taskInputs?: RankCheckTaskInput[];
- liveFallback?: boolean;
- saveNotFound?: boolean;
- } = {},
-): Promise<QueuedCheckStats> {
- // Post all tasks to the queue, <=100 per request, one metered step each.
- // A failed chunk must not abort the run — earlier chunks were already
- // charged at DataForSEO, so their results have to be collected. The failed
- // chunk's pairs go to the live fallback instead.
+ tasks: RankCheckTaskInput[],
+ label: string,
+ onCollected?: (results: RankCheckResultWithDevice[]) => Promise<void>,
+): Promise<RankCheckResultWithDevice[]> {
+ // A failed post must not abort the run: earlier chunks were already
+ // charged at DataForSEO, so their results have to be collected.
let pending: PostedRankCheckTask[] = [];
- const fallback: RankCheckTaskInput[] = [];
- for (let i = 0; i < taskInputs.length; i += MAX_TASKS_PER_POST) {
- const chunk = taskInputs.slice(i, i + MAX_TASKS_PER_POST);
- const postIndex = Math.floor(i / MAX_TASKS_PER_POST);
- let posted: PostedRankCheckTask[];
+ for (let i = 0; i < tasks.length; i += MAX_TASKS_PER_POST) {
+ const chunk = tasks.slice(i, i + MAX_TASKS_PER_POST);
+ const postLabel = `${label}post-tasks-${Math.floor(i / MAX_TASKS_PER_POST)}`;
try {
- posted = await pgStep(
- step,
- `post-tasks-${postIndex}`,
- SINGLE_ATTEMPT_STEP_CONFIG,
- async () =>
+ pending.push(
+ ...(await pgStep(step, postLabel, SINGLE_ATTEMPT_STEP_CONFIG, () =>
ctx.client.serp.rankCheckTaskPost({
tasks: chunk,
locationCode: ctx.locationCode,
@@ -386,97 +285,230 @@ export async function runQueuedCheck(
depth: ctx.serpDepth,
targetDomain: ctx.domain,
}),
+ )),
);
} catch (error) {
- console.warn(
- `[rank-check] ${ctx.runId} post-tasks-${postIndex} failed:`,
- error,
- );
- fallback.push(...chunk);
- continue;
- }
- pending.push(...posted);
- if (posted.length < chunk.length) {
- const acceptedKeys = new Set(
- posted.map((t) => `${t.keywordId}:${t.device}`),
- );
- fallback.push(
- ...chunk.filter((t) => !acceptedKeys.has(`${t.keywordId}:${t.device}`)),
- );
+ console.warn(`[rank-check] ${ctx.runId} ${postLabel} failed:`, error);
}
}
+ const collected: RankCheckResultWithDevice[] = [];
- const stats: QueuedCheckStats = {
- queueTasks: pending.length,
- queueCollected: 0,
- fallbackTasks: 0,
- fallbackChecked: 0,
- };
-
- // Poll until everything is collected or the ~15 minute window closes. A
- // collect failure (past its retries) leaves that round's tasks pending for
- // the next round — or the live fallback — instead of failing the run; the
- // posted tasks are already paid for.
+ // A collect failure (past its retries) leaves that round's tasks pending for
+ // the next round instead of failing the run.
for (
let round = 0;
round < QUEUED_POLL_INTERVALS.length && pending.length > 0;
round++
) {
- await step.sleep(`wait-${round}`, QUEUED_POLL_INTERVALS[round]);
+ await step.sleep(`${label}wait-${round}`, QUEUED_POLL_INTERVALS[round]);
// Cap task_gets per round so one collect step stays well inside the
// per-invocation subrequest limit at the 1000-keyword config ceiling.
const batch = pending.slice(0, TASK_GETS_PER_COLLECT);
const overflow = pending.slice(TASK_GETS_PER_COLLECT);
-
- let outcome: CollectRoundOutcome;
try {
- outcome = await pgStep(
+ // Results come back as the step's output, so a replay sees them too.
+ const outcome = await pgStep(
step,
- `collect-${round}`,
+ `${label}collect-${round}`,
COLLECT_STEP_CONFIG,
- () => collectQueuedRound(ctx, batch, saveNotFound),
+ async () => {
+ const fetched = await fetchQueuedRound(ctx, batch);
+ if (onCollected && fetched.completed.length > 0) {
+ await onCollected(fetched.completed);
+ }
+ return fetched;
+ },
);
+ collected.push(...outcome.completed);
+ pending = [...outcome.stillPending, ...overflow];
} catch (error) {
- console.warn(`[rank-check] ${ctx.runId} collect-${round} failed:`, error);
- continue;
+ console.warn(
+ `[rank-check] ${ctx.runId} ${label}collect-${round} failed:`,
+ error,
+ );
}
-
- stats.queueCollected += outcome.collected;
- pending = [...outcome.stillPending, ...overflow];
- fallback.push(...outcome.failed);
}
+ return collected;
+}
- // Live fallback: queued tasks that never finished, failed, or were rejected
- // at post time. A straggler is double-billed (customer was metered the
- // queued post cost and now the live call too — fractions of a cent).
- // Progress isn't updated here; finalize recounts keywordsChecked from the
- // DB.
- const stragglers: RankCheckTaskInput[] = [...fallback, ...pending];
- if (stragglers.length === 0) return stats;
- if (!liveFallback) {
- console.log(
- `[rank-check] ${ctx.runId} ${stragglers.length} task(s) left unchecked, no live fallback`,
+/**
+ * Check every keyword/device pair through the task queue (scheduled runs),
+ * writing snapshots as tasks complete. Billing happens at task_post. Pairs
+ * left without a result are retried by retryRankChecks.
+ */
+export async function runQueuedCheck(
+ step: WorkflowStep,
+ ctx: CheckContext,
+): Promise<void> {
+ await runQueuedTasks(
+ step,
+ ctx,
+ expandToTaskInputs(ctx.keywords, ctx.devices),
+ "",
+ async (results) => {
+ await RankTrackingRepository.insertSnapshots(
+ mapResultsToSnapshotRows(ctx.runId, results),
+ );
+ // Progress for the UI; finalize recounts from the DB anyway.
+ const snapshots = await RankTrackingRepository.getSnapshotsForRun(
+ ctx.runId,
+ );
+ await RankTrackingRepository.updateRun(ctx.runId, {
+ keywordsChecked: new Set(snapshots.map((s) => s.trackingKeywordId))
+ .size,
+ });
+ },
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Retries. A check that errors gets retried, and so does one that reads far
+// worse than the keyword's known position: Google serves some scraped searches
+// a fake results page that looks normal but leaves out sites that really rank.
+// Retries are billed like any other check, and the best position found wins.
+// ---------------------------------------------------------------------------
+
+/** A result this many positions below the keyword's known rank is retried. */
+const RETRY_DROP_POSITIONS = 10;
+
+interface RetryPair extends RankCheckTaskInput {
+ /** Best position saved for this run; null if not found or never answered. */
+ position: number | null;
+ /** Whether any try got a results page back. */
+ answered: boolean;
+ /**
+ * Best position the keyword has had: on either device in an earlier check,
+ * or on its other device in this run. Null if it never ranked.
+ */
+ knownPosition: number | null;
+}
+
+function needsRetry(pair: RetryPair): boolean {
+ if (!pair.answered) return true;
+ if (pair.knownPosition === null) return false;
+ return (
+ pair.position === null ||
+ pair.position - pair.knownPosition >= RETRY_DROP_POSITIONS
+ );
+}
+
+function key(keywordId: string, device: string) {
+ return `${keywordId}:${device}`;
+}
+
+/**
+ * Find the pairs to retry: ones the first check got no answer for, and ones
+ * that miss or fall far below the keyword's known position.
+ */
+async function findRetryPairs(
+ ctx: CheckContext,
+ configId: string,
+): Promise<RetryPair[]> {
+ // The run is still active, so completed runs are all earlier checks.
+ const [current, previous] = await Promise.all([
+ RankTrackingRepository.getSnapshotsForRun(ctx.runId),
+ RankTrackingRepository.getBestPositionsForKeywords(configId),
+ ]);
+ const previousPositions = new Map(
+ previous.map((s) => [s.trackingKeywordId, s.position]),
+ );
+ const currentPositions = new Map(
+ current.map((s) => [key(s.trackingKeywordId, s.device), s.position]),
+ );
+
+ return expandToTaskInputs(ctx.keywords, ctx.devices).flatMap((task) => {
+ const otherDevice = task.device === "desktop" ? "mobile" : "desktop";
+ const known = [
+ previousPositions.get(task.keywordId),
+ currentPositions.get(key(task.keywordId, otherDevice)),
+ ].filter((position) => position != null);
+ const pair: RetryPair = {
+ ...task,
+ position: currentPositions.get(key(task.keywordId, task.device)) ?? null,
+ answered: currentPositions.has(key(task.keywordId, task.device)),
+ knownPosition: known.length > 0 ? Math.min(...known) : null,
+ };
+ return needsRetry(pair) ? [pair] : [];
+ });
+}
+
+/**
+ * Save any position that beats a pair's saved one, plus the first answer for
+ * a keyword that never ranked, and return each pair updated.
+ */
+async function saveRetryResults(
+ runId: string,
+ pairs: RetryPair[],
+ collected: RankCheckResultWithDevice[],
+): Promise<RetryPair[]> {
+ const results = new Map(
+ collected.map((result) => [key(result.keywordId, result.device), result]),
+ );
+ const toSave: RankCheckResultWithDevice[] = [];
+ const updated = pairs.map((pair) => {
+ const result = results.get(key(pair.keywordId, pair.device));
+ if (!result) return pair;
+ const answered = { ...pair, answered: true };
+ const isBetter =
+ result.position !== null &&
+ (pair.position === null || result.position < pair.position);
+ const isFirstForNewKeyword = !pair.answered && pair.knownPosition === null;
+ if (!isBetter && !isFirstForNewKeyword) return answered;
+ toSave.push(result);
+ return { ...answered, position: result.position };
+ });
+ if (toSave.length > 0) {
+ await RankTrackingRepository.upsertSnapshots(
+ mapResultsToSnapshotRows(runId, toSave),
);
- return stats;
}
- stats.fallbackTasks = stragglers.length;
+ return updated;
+}
- console.log(
- `[rank-check] ${ctx.runId} live fallback for ${stragglers.length} task(s)`,
+/**
+ * Retry each keyword/device pair whose check errored or reads far worse than
+ * its known position, up to RETRY_ROUNDS more times through the task queue
+ * (queue price, for manual runs too), stopping once a retry settles it. A
+ * keyword that ranked before is never saved as not found: if no try found it,
+ * its miss is removed, so it reads as not checked and keeps its previous
+ * position.
+ */
+export async function retryRankChecks(
+ step: WorkflowStep,
+ ctx: CheckContext,
+ configId: string,
+): Promise<void> {
+ let pairs = await pgStep(step, "find-retries", COLLECT_STEP_CONFIG, () =>
+ findRetryPairs(ctx, configId),
);
+ if (pairs.length === 0) return;
- for (let i = 0; i < stragglers.length; i += KEYWORDS_PER_BATCH) {
- const batch = stragglers.slice(i, i + KEYWORDS_PER_BATCH);
- const batchIndex = Math.floor(i / KEYWORDS_PER_BATCH);
+ console.log(`[rank-check] ${ctx.runId} retrying ${pairs.length} check(s)`);
- stats.fallbackChecked += await pgStep(
+ for (let round = 0; round < RETRY_ROUNDS && pairs.length > 0; round++) {
+ const label = `retry-${round}-`;
+ const collected = await runQueuedTasks(step, ctx, pairs, label);
+ const updated = await pgStep(
step,
- `fallback-batch-${batchIndex}`,
- SINGLE_ATTEMPT_STEP_CONFIG,
- () => checkBatchLive(ctx, batch),
+ `${label}save`,
+ COLLECT_STEP_CONFIG,
+ () => saveRetryResults(ctx.runId, pairs, collected),
);
+ pairs = updated.filter(needsRetry);
}
- return stats;
+ const unconfirmed = pairs.filter(
+ (pair) => pair.position === null && pair.knownPosition !== null,
+ );
+ if (unconfirmed.length === 0) return;
+ await pgStep(step, "drop-unconfirmed-misses", COLLECT_STEP_CONFIG, () =>
+ RankTrackingRepository.deleteNotFoundSnapshots(
+ unconfirmed.map((pair) => ({
+ runId: ctx.runId,
+ trackingKeywordId: pair.keywordId,
+ device: pair.device,
+ })),
+ ),
+ );
}
diff --git a/src/shared/rank-tracking.test.ts b/src/shared/rank-tracking.test.ts
index 8084a659..4525d530 100644
--- a/src/shared/rank-tracking.test.ts
+++ b/src/shared/rank-tracking.test.ts
@@ -8,35 +8,35 @@ describe("rank tracking cost estimates", () => {
keywordCount: 4,
devices: "desktop" as const,
depth: 10,
- costUsd: 0.01024,
- costCredits: 12,
+ costUsd: 0.01638,
+ costCredits: 20,
},
{
method: "live" as const,
keywordCount: 1000,
devices: "both" as const,
depth: 40,
- costUsd: 16.64,
- costCredits: 18_000,
+ costUsd: 26.624,
+ costCredits: 28_000,
},
{
method: "queued" as const,
keywordCount: 104,
devices: "desktop" as const,
depth: 10,
- costUsd: 0.07987,
- costCredits: 81,
+ costUsd: 0.23961,
+ costCredits: 243,
},
{
method: "queued" as const,
keywordCount: 1000,
devices: "both" as const,
depth: 40,
- costUsd: 4.992,
- costCredits: 5_000,
+ costUsd: 14.976,
+ costCredits: 15_000,
},
])(
- "matches per-call billing for $method checks",
+ "matches per-call billing for a $method check plus two queued retries",
({ keywordCount, devices, depth, method, costUsd, costCredits }) => {
expect(
estimateRankCheckCredits(
diff --git a/src/shared/rank-tracking.ts b/src/shared/rank-tracking.ts
index 24ea9d55..01740397 100644
--- a/src/shared/rank-tracking.ts
+++ b/src/shared/rank-tracking.ts
@@ -33,6 +33,12 @@ type RankCheckMethod = "live" | "queued";
/** How many keywords are checked per batch */
export const KEYWORDS_PER_BATCH = 10;
+/**
+ * Extra queued checks a rank check gives a keyword/device that errored or
+ * reads as lost or far below its known position.
+ */
+export const RETRY_ROUNDS = 2;
+
/** Approximate seconds per batch */
export const SECONDS_PER_BATCH = 6;
@@ -84,6 +90,11 @@ export function serpKeywordCostMultiplier(keyword: string) {
return SERP_OPERATOR_KEYWORD.test(keyword) ? 5 : 1;
}
+/**
+ * The most one rank check can cost: the check itself at `method` price, plus
+ * RETRY_ROUNDS queued retries of every keyword/device pair (retries go to
+ * pairs that error or read as lost, so most checks cost far less).
+ */
export function estimateRankCheckCredits(
keywords: readonly string[],
devices: RankTrackingConfig["devices"],
@@ -97,6 +108,19 @@ export function estimateRankCheckCredits(
serpKeywordCostMultiplier(keyword),
),
);
+ const check = meteredCost(checkMultipliers, depth, method);
+ const retry = meteredCost(checkMultipliers, depth, "queued");
+ return {
+ costUsd: roundUsdForBilling(check.costUsd + RETRY_ROUNDS * retry.costUsd),
+ costCredits: check.costCredits + RETRY_ROUNDS * retry.costCredits,
+ };
+}
+
+function meteredCost(
+ checkMultipliers: number[],
+ depth: number,
+ method: RankCheckMethod,
+) {
const checksPerMeteredCall = method === "queued" ? MAX_TASKS_PER_POST : 1;
let costUsd = 0;
let costCredits = 0;
@@ -117,10 +141,6 @@ export function estimateRankCheckCredits(
costUsd += applyBillingMarkupUsd(callRawUsd);
costCredits += creditsForProviderUsd(callRawUsd);
}
-
- // This is the nominal queued task_post estimate. Rejected, failed, or
- // timed-out tasks can later incur additional live-fallback spend.
- costUsd = roundUsdForBilling(costUsd);
return { costUsd, costCredits };
}