Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Keep jobs starting and AI checks finishing through Workflows engine failures (#1065)
Ben Senescu525b0780d428
diff --git a/.agents/skills/observability-triage/SKILL.md b/.agents/skills/observability-triage/SKILL.mdindex 03271923..e59ca6bc 100644--- a/.agents/skills/observability-triage/SKILL.md+++ b/.agents/skills/observability-triage/SKILL.md@@ -56,6 +56,13 @@ Query Cloudflare Workers Observability for prod errors, count them correctly, an- **Message prefixes fragment groups.** Logs with leading timestamps (better-auth's format) split one error into N single-count groups; grouped-by-message counts badly understate them. Sample events and merge client-side.- **Prod deploys are manual** — main being fixed doesn't mean prod runs the fix. Check `$workers.scriptVersion` and the scripts' `modified_on` before concluding a fix didn't work.+## Workflow failures++- **An Error logged as an argument loses its message.** `console.error("x failed:", error)` lands in Workers Logs as `x failed: at async …` (frames only, no `Error: message` line), and an Error inside a logged object serializes to `{remote: true}` or `{}`. Grep the stack for the call site, then read the real message from `describeError(error)` in the newer log lines (`src/server/lib/errors.ts`) or from the Workflows instance below.+- **The engine records why a step attempt failed.** `GET /accounts/{account_id}/workflows/{workflow_name}/instances?status=errored&date_start=<iso>` lists errored instances (workflow names are in `wrangler.jsonc`: `ai-visibility-workflow`, `rank-check-workflow`, `site-audit-workflow` on the audit worker, `local-rank-workflow`); `GET …/instances/{id}` returns `error` plus every step with its attempts and each attempt's `error.name`/`error.message`. This is the only place the message of a step failure survives.+- **`WorkflowInternalError: Attempt failed due to internal workflows error`** on an attempt is the engine's own failure, not app code: the invocation running the step is reported `canceled` about 30 s later. It comes in bursts that line up with Cloudflare status incidents (Workflows, Durable Objects, or a network incident in the Ashburn region that hosts prod). The same bursts make the binding's `create()` reject (`at async WorkflowImpl.create (cloudflare-internal:workflows-api…)`). Check `cloudflarestatus.com/history` for the window before reading code.+- **`canceled` is normal for workflow invocations.** The engine cancels an invocation after its steps finished or while it sleeps (hundreds a day per workflow with no errored instance behind them), so count errored *instances*, not canceled invocations.+## Profiling (CPU and heap flamegraphs)Cloudflare captures an on-demand CPU or allocation profile from a live production isolate (shipped 2026-10-09). Reach for it only when the question is "where does the CPU or memory go", which logs and invocation metrics cannot answer; routine error triage never needs it. A capture only samples one already-running isolate for the requested window; keep windows at 10 to 15 s.diff --git a/src/middleware/errorHandling.ts b/src/middleware/errorHandling.tsindex 0934aa71..94c89dda 100644--- a/src/middleware/errorHandling.ts+++ b/src/middleware/errorHandling.ts@@ -3,7 +3,12 @@ import { getRequest } from "@tanstack/react-start/server";import { waitUntil } from "cloudflare:workers";import { shouldCaptureAppErrorCode } from "@/shared/error-codes";import { getAuth } from "@/lib/auth";-import { AppError, asAppError, toClientError } from "@/server/lib/errors";+import {+ AppError,+ asAppError,+ toClientError,+ describeError,+} from "@/server/lib/errors";import { captureServerError } from "@/server/lib/posthog";import { isHostedServerAuthMode } from "@/server/lib/runtime-env";@@ -71,7 +76,11 @@ export const errorHandlingMiddleware = createMiddleware({// Details can quote customer content (a DataForSEO response body), so// they stay in this log line and never reach error tracking.- console.error("server.function error:", error, appError?.details ?? "");+ console.error(+ `server.function error: ${describeError(error)}`,+ error,+ appError?.details ?? "",+ );const properties = {errorCode: appError?.code ?? "INTERNAL_ERROR",method: request.method,diff --git a/src/server/features/ai-visibility/services/aiResearchKeywords.ts b/src/server/features/ai-visibility/services/aiResearchKeywords.tsindex 74bcb6bc..72910559 100644--- a/src/server/features/ai-visibility/services/aiResearchKeywords.ts+++ b/src/server/features/ai-visibility/services/aiResearchKeywords.ts@@ -24,6 +24,7 @@ import {prepareWebsiteTracking,startWebsiteTrackingRun,} from "./websiteTrackingSetup";+import { startWorkflow } from "@/server/lib/startWorkflow";/*** Prompt Research needs saved keywords. Website setup writes them; a@@ -123,20 +124,24 @@ export async function startAiResearchSetup(const { instance } = await readSetupRun(input.projectId);if (instance) await instance.restart();else- await env.AI_VISIBILITY_WORKFLOW.create({- id: setupInstanceId(input.projectId),- // Only the billing fields: the request context is not serializable.- params: {- setupProjectId: input.projectId,- runSeededTracking,- customer: {- organizationId: customer.organizationId,- userId: customer.userId,- userEmail: customer.userEmail,- projectId: input.projectId,+ await startWorkflow(+ env.AI_VISIBILITY_WORKFLOW,+ {+ id: setupInstanceId(input.projectId),+ // Only the billing fields: the request context is not serializable.+ params: {+ setupProjectId: input.projectId,+ runSeededTracking,+ customer: {+ organizationId: customer.organizationId,+ userId: customer.userId,+ userEmail: customer.userEmail,+ projectId: input.projectId,+ },},},- });+ "AI research setup",+ );return { ...setup, status: "running" as const, failure: null };}diff --git a/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts b/src/server/features/ai-visibility/services/aiVisibilityCollection.test.tsindex c19507d8..2e51ffb0 100644--- a/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts@@ -26,6 +26,9 @@ const { testDb, dataforseo } = await vi.hoisted(async () => {};});vi.mock("cloudflare:workers", () => ({ env: { DATABASE_PROVIDER: "d1" } }));+vi.mock("cloudflare:workflows", () => ({+ NonRetryableError: class extends Error {},+}));vi.mock("@/db", () => ({ db: testDb.db }));vi.mock("@/db/runBatch", () => ({ runBatch: testDb.runBatch }));vi.mock("@/server/lib/runtime-env", () => ({@@ -425,4 +428,15 @@ describe("AI answer collection", () => {error: "No answer arrived within the collection window.",});});++ it("tells the tracker the check could not collect answers when none arrived", async () => {+ await finalizeAiRun(runId);++ expect(await repo.getRunInternal(runId)).toMatchObject({+ status: "failed",+ });+ expect((await repo.getTracker("project"))?.lastSkipReason).toBe(+ "The last check could not collect answers.",+ );+ });});diff --git a/src/server/features/ai-visibility/services/aiVisibilityCollection.ts b/src/server/features/ai-visibility/services/aiVisibilityCollection.tsindex 952502da..26c35e84 100644--- a/src/server/features/ai-visibility/services/aiVisibilityCollection.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityCollection.ts@@ -1,3 +1,4 @@+import { NonRetryableError } from "cloudflare:workflows";import type { BillingCustomerContext } from "@/server/billing/subscription";import {createDataforseoClient,@@ -89,8 +90,9 @@ export async function prepareAiRun()> {const run = await repo.getRunInternal(runId);+ // Stale-run cleanup failed it already; a retry would find the same.if (!run || (run.status !== "queued" && run.status !== "running"))- throw new AppError("NOT_FOUND", `Run ${runId} is no longer active.`);+ throw new NonRetryableError(`Run ${runId} is no longer active.`);const pending = (await repo.getObservations([runId])).filter((row) => row.status === "pending",);@@ -434,8 +436,9 @@ export async function finalizeAiRun(runId: string) {status,completedAt: new Date().toISOString(),});- if (status !== "failed")- await repo.updateTracker(run.trackerId, { lastSkipReason: null });+ await repo.updateTracker(run.trackerId, {+ lastSkipReason: status === "failed" ? AI_ANSWER_FAILURES.runFailed : null,+ });}/** The workflow's failure path: fail the run and say why on the tracker. */diff --git a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts b/src/server/features/ai-visibility/services/aiVisibilityRuns.tsindex 821b36cc..46d0d78c 100644--- a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityRuns.ts@@ -23,6 +23,7 @@ import { requireConfiguration } from "./aiVisibilityMutation";import { aiPromptIsBranded } from "./aiVisibilityMatching";import { aiRunView } from "./aiVisibilityResults";import { aiCostForAnswers } from "./aiVisibilityCost";+import { startWorkflow } from "@/server/lib/startWorkflow";const ACTIVE_WORKFLOW_STATUSES = new Set(["queued",@@ -162,19 +163,23 @@ export async function startRun();}try {- await env.AI_VISIBILITY_WORKFLOW.create({- id,- // Only the billing fields: the request context is not serializable.- params: {- runId: id,- customer: {- organizationId: billing.organizationId,- userId: billing.userId,- userEmail: billing.userEmail,- projectId: project.id,+ await startWorkflow(+ env.AI_VISIBILITY_WORKFLOW,+ {+ id,+ // Only the billing fields: the request context is not serializable.+ params: {+ runId: id,+ customer: {+ organizationId: billing.organizationId,+ userId: billing.userId,+ userEmail: billing.userEmail,+ projectId: project.id,+ },},},- });+ "AI visibility check",+ );} catch (error) {await failAiRun(id, AI_ANSWER_FAILURES.notStarted);throw error;diff --git a/src/server/features/ai-visibility/services/scheduledAiVisibility.ts b/src/server/features/ai-visibility/services/scheduledAiVisibility.tsindex 4d89c62f..010fd97f 100644--- a/src/server/features/ai-visibility/services/scheduledAiVisibility.ts+++ b/src/server/features/ai-visibility/services/scheduledAiVisibility.ts@@ -1,4 +1,4 @@-import { AppError } from "@/server/lib/errors";+import { AppError, describeError } from "@/server/lib/errors";import { pruneAiVisibility } from "./aiVisibilityRetention";import { AiVisibilityRepository as repo } from "../repositories/AiVisibilityRepository";import { AiVisibilityError } from "./aiVisibilityErrors";@@ -68,7 +68,7 @@ export async function runScheduledAiVisibility() {if (!(error instanceof AiVisibilityError))console.error("[ai-visibility] scheduled check failed to start", {trackerId: tracker.id,- error,+ error: describeError(error),});await repo.updateTracker(tracker.id, {diff --git a/src/server/features/audit/services/AuditService.ts b/src/server/features/audit/services/AuditService.tsindex 366c2bc4..ea3c6544 100644--- a/src/server/features/audit/services/AuditService.ts+++ b/src/server/features/audit/services/AuditService.ts@@ -31,6 +31,7 @@ import {import { normalizeAndValidateStartUrl } from "@/server/lib/audit/url-policy";import { reconcileRunningAudit } from "@/server/features/audit/services/auditReconciler";import { isHostedServerAuthMode } from "@/server/lib/runtime-env";+import { startWorkflow } from "@/server/lib/startWorkflow";// Free accounts keep bounded audit capacity; rendering reserves usage credits.async function resolveAuditLimitTier(@@ -133,23 +134,27 @@ async function startAudit(input: {});}- await env.SITE_AUDIT_WORKFLOW.create({- id: auditId,- params: {- auditId,- billingCustomer: {- userId: input.billingCustomer.userId,- userEmail: input.billingCustomer.userEmail,- organizationId: input.billingCustomer.organizationId,- projectId: input.billingCustomer.projectId,+ await startWorkflow(+ env.SITE_AUDIT_WORKFLOW,+ {+ id: auditId,+ params: {+ auditId,+ billingCustomer: {+ userId: input.billingCustomer.userId,+ userEmail: input.billingCustomer.userEmail,+ organizationId: input.billingCustomer.organizationId,+ projectId: input.billingCustomer.projectId,+ },+ projectId: input.projectId,+ startUrl,+ config,+ access: credential?.sealed,+ renderLocks,},- projectId: input.projectId,- startUrl,- config,- access: credential?.sealed,- renderLocks,},- });+ "site audit",+ );} catch (error) {try {const instance = await env.SITE_AUDIT_WORKFLOW.get(auditId);diff --git a/src/server/features/dashboard/services/DashboardFirstAuditService.ts b/src/server/features/dashboard/services/DashboardFirstAuditService.tsindex 0ca569f5..3d7f222f 100644--- a/src/server/features/dashboard/services/DashboardFirstAuditService.ts+++ b/src/server/features/dashboard/services/DashboardFirstAuditService.ts@@ -4,7 +4,7 @@ import { AuditService } from "@/server/features/audit/services/AuditService";import { AuditRepository } from "@/server/features/audit/repositories/AuditRepository";import { DataRefreshClaimRepository } from "../repositories/DataRefreshClaimRepository";import { buildCacheKey } from "@/server/lib/r2-cache";-import { asAppError } from "@/server/lib/errors";+import { asAppError, describeError } from "@/server/lib/errors";import { captureServerEvent } from "@/server/lib/posthog";import type { BillingCustomerContext } from "@/server/billing/subscription";@@ -79,7 +79,7 @@ async function start(if (shouldCaptureAppErrorCode(code))console.error("dashboard:first-audit startup failed",- { projectId, code },+ { projectId, code, error: describeError(error) },error,);elsediff --git a/src/server/features/local-seo/services/LocalSeoService.ts b/src/server/features/local-seo/services/LocalSeoService.tsindex a7abf5ba..ea145313 100644--- a/src/server/features/local-seo/services/LocalSeoService.ts+++ b/src/server/features/local-seo/services/LocalSeoService.ts@@ -31,6 +31,7 @@ import {type LocalTrackerRow,} from "../repositories/LocalSeoRepository";import { finalizeLocalCheck, localPointSearch } from "./localSeoCollection";+import { startWorkflow } from "@/server/lib/startWorkflow";const profileSchema = z.object({title: z.string(),@@ -294,13 +295,13 @@ async function startCheck(throw error;}try {- await env.LOCAL_RANK_WORKFLOW.create({- id: check.id,- params: { checkId: check.id, customer },- });+ await startWorkflow(+ env.LOCAL_RANK_WORKFLOW,+ { id: check.id, params: { checkId: check.id, customer } },+ "local rank check",+ );} catch (error) {- // A lost create response is ambiguous. Do not start another workflow or- // post paid tasks here; reconciliation checks the same instance later.+ // Nothing paid is posted here; reconciliation fails the check later.console.error("[local-seo] workflow start failed:", error);}return check;diff --git a/src/server/features/rank-tracking/services/rankCheckRunGuards.ts b/src/server/features/rank-tracking/services/rankCheckRunGuards.tsindex 19bd3ec8..e485d6d2 100644--- a/src/server/features/rank-tracking/services/rankCheckRunGuards.ts+++ b/src/server/features/rank-tracking/services/rankCheckRunGuards.ts@@ -5,6 +5,7 @@ import type {RankCheckTriggerResult,RankTrackingConfig,} from "@/types/schemas/rank-tracking";+import { startWorkflow } from "@/server/lib/startWorkflow";type RunRow = Awaited<ReturnType<typeof RankTrackingRepository.getRunById>>;@@ -161,24 +162,28 @@ export async function beginRankCheckRun(input: {if (created) {try {- await input.workflow.create({- id: runId,- params: {- runId,- configId: input.config.id,- billingCustomer: input.billingCustomer,- projectId: input.projectId,- domain: input.config.domain,- locationCode: input.config.locationCode,- languageCode: input.config.languageCode,- locationName: input.config.locationName ?? undefined,- devices: input.config.devices,- serpDepth: input.config.serpDepth,- trigger: input.trigger,- keywordIds: input.keywordIds,- maxCostCredits: input.maxCostCredits,+ await startWorkflow(+ input.workflow,+ {+ id: runId,+ params: {+ runId,+ configId: input.config.id,+ billingCustomer: input.billingCustomer,+ projectId: input.projectId,+ domain: input.config.domain,+ locationCode: input.config.locationCode,+ languageCode: input.config.languageCode,+ locationName: input.config.locationName ?? undefined,+ devices: input.config.devices,+ serpDepth: input.config.serpDepth,+ trigger: input.trigger,+ keywordIds: input.keywordIds,+ maxCostCredits: input.maxCostCredits,+ },},- });+ "rank check",+ );} catch (error) {// Workflow couldn't start — flip the run to failed so the// partial-index slot is released. Best-effort cleanup of anydiff --git a/src/server/features/rank-tracking/services/scheduledRankChecks.ts b/src/server/features/rank-tracking/services/scheduledRankChecks.tsindex 6d467f00..baa919c7 100644--- a/src/server/features/rank-tracking/services/scheduledRankChecks.ts+++ b/src/server/features/rank-tracking/services/scheduledRankChecks.ts@@ -7,6 +7,7 @@ import {devicesCount,isScheduledRankTrackingInterval,} from "@/shared/rank-tracking";+import { describeError } from "@/server/lib/errors";// Work admitted per tick, in task units (keywords × devices). Admission// control, not a hard rate limit: the first start of a tick is always@@ -186,7 +187,7 @@ export async function runScheduledRankChecks(env: Env) {// make hundreds of configs due again on the next tick.workflowStartErrors++;console.error(- `[cron] Failed to start scheduled rank check for config ${config.id} (${config.domain}):`,+ `[cron] Failed to start scheduled rank check for config ${config.id} (${config.domain}): ${describeError(err)}`,err,);continue;diff --git a/src/server/lib/errors.ts b/src/server/lib/errors.tsindex 89af1f84..73330bff 100644--- a/src/server/lib/errors.ts+++ b/src/server/lib/errors.ts@@ -25,3 +25,20 @@ export function asAppError(error: unknown): AppError | null {export function toClientError(error: unknown): Error {return new Error(asAppError(error)?.code ?? "INTERNAL_ERROR");}++/**+ * The error's name, message and code, then its causes, for a log line.+ * Workers Logs render an Error passed to `console.error` as its stack frames+ * alone, so a log keeps the message only when it is written out like this.+ * An error the Workflows engine threw over RPC is marked remote.+ */+export function describeError(error: unknown, depth = 0): string {+ if (!(error instanceof Error)) return String(error);+ const code = asAppError(error)?.code;+ const parts = [`${error.name}: ${error.message}`];+ if (code && code !== error.message) parts.push(`(${code})`);+ if ("remote" in error && error.remote === true) parts.push("(remote)");+ if (error.cause !== undefined && depth < 4)+ parts.push(`<- ${describeError(error.cause, depth + 1)}`);+ return parts.join(" ");+}diff --git a/src/server/lib/startWorkflow.test.ts b/src/server/lib/startWorkflow.test.tsnew file mode 100644index 00000000..b8d64043--- /dev/null+++ b/src/server/lib/startWorkflow.test.ts@@ -0,0 +1,46 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { startWorkflow } from "./startWorkflow";++const workflow = { create: vi.fn(), get: vi.fn() };+// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only create and get run+const binding = workflow as unknown as Workflow<{ runId: string }>;+const options = { id: "instance", params: { runId: "run" } };++beforeEach(() => {+ vi.useFakeTimers();+ workflow.create.mockResolvedValue({});+ workflow.get.mockRejectedValue(new Error("instance.not_found"));+});+afterEach(() => {+ vi.useRealTimers();+});++describe("startWorkflow", () => {+ it("creates the instance again after the engine refuses once", async () => {+ workflow.create.mockRejectedValueOnce(new Error("internal error"));+ const started = startWorkflow(binding, options, "test");+ await vi.advanceTimersByTimeAsync(10_000);+ await started;+ expect(workflow.create).toHaveBeenCalledTimes(2);+ expect(workflow.create).toHaveBeenLastCalledWith(options);+ });++ it("counts a refused create whose instance exists as started", async () => {+ workflow.create.mockRejectedValue(new Error("reply lost"));+ workflow.get.mockResolvedValue({+ status: async () => ({ status: "running" }),+ });+ await startWorkflow(binding, options, "test");+ expect(workflow.create).toHaveBeenCalledOnce();+ });++ it("throws once every attempt is refused", async () => {+ workflow.create.mockRejectedValue(new Error("internal error"));+ const outcome = startWorkflow(binding, options, "test").catch(+ (error: unknown) => error,+ );+ await vi.advanceTimersByTimeAsync(10_000);+ expect(await outcome).toEqual(new Error("internal error"));+ expect(workflow.create).toHaveBeenCalledTimes(3);+ });+});diff --git a/src/server/lib/startWorkflow.ts b/src/server/lib/startWorkflow.tsnew file mode 100644index 00000000..cd185817--- /dev/null+++ b/src/server/lib/startWorkflow.ts@@ -0,0 +1,53 @@+import { describeError } from "@/server/lib/errors";++/** Waits before the second and third create, so a short engine blip can pass. */+const RETRY_DELAYS_MS = [500, 2_000];++/**+ * `workflow.create` with the engine's passing failures absorbed. The engine+ * refuses a create now and then, during a network incident or on an internal+ * error, and the job would otherwise fail the moment it was asked for. A+ * refused create whose instance exists all the same went through and only+ * its reply was lost, so that instance counts as started rather than being+ * created twice. The last failure is thrown for the caller to roll back on.+ */+export async function startWorkflow<P>(+ workflow: Workflow<P>,+ options: WorkflowInstanceCreateOptions<P> & { id: string },+ label: string,+): Promise<void> {+ for (let attempt = 0; ; attempt++) {+ try {+ await workflow.create(options);+ return;+ } catch (error) {+ console.warn(+ `[workflow] ${label} ${options.id} create attempt ${attempt + 1} failed: ${describeError(error)}`,+ );+ if (await instanceExists(workflow, options.id)) return;+ const delay = RETRY_DELAYS_MS[attempt];+ if (delay === undefined) throw error;+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }+}++/**+ * `get` throws for an unknown id. Only an instance still in flight counts: a+ * finished one under the same id (the research setup reuses its id) was not+ * started by this call.+ */+async function instanceExists<P>(workflow: Workflow<P>, id: string) {+ try {+ const { status } = await (await workflow.get(id)).status();+ return [+ "queued",+ "running",+ "waiting",+ "waitingForPause",+ "paused",+ ].includes(status);+ } catch {+ return false;+ }+}diff --git a/src/server/mcp/instrumentation.ts b/src/server/mcp/instrumentation.tsindex 6994acea..2e581063 100644--- a/src/server/mcp/instrumentation.ts+++ b/src/server/mcp/instrumentation.ts@@ -1,7 +1,7 @@import { waitUntil } from "cloudflare:workers";import type { CallToolResult } from "@modelcontextprotocol/server";import type { z } from "zod";-import { AppError, asAppError } from "@/server/lib/errors";+import { AppError, asAppError, describeError } from "@/server/lib/errors";import { recordExternalMcpToolCall } from "@/server/features/activation/mcpActivation";import { captureServerError, captureServerEvent } from "@/server/lib/posthog";import { shouldCaptureAppErrorCode } from "@/shared/error-codes";@@ -186,7 +186,10 @@ export function instrumentMcpToolHandler<TArgs>(durationMs: Math.round(performance.now() - startedAt),});if (shouldCaptureAppErrorCode(appError?.code)) {- console.error(`mcp.tool error (${toolName}):`, error);+ console.error(+ `mcp.tool error (${toolName}): ${describeError(error)}`,+ error,+ );waitUntil(captureServerError(error,diff --git a/src/server/workflows/AiVisibilityWorkflow.test.ts b/src/server/workflows/AiVisibilityWorkflow.test.tsindex 0260ac45..3f443096 100644--- a/src/server/workflows/AiVisibilityWorkflow.test.ts+++ b/src/server/workflows/AiVisibilityWorkflow.test.ts@@ -152,12 +152,39 @@ describe("AI visibility workflow", () => {);});+ it("keeps collecting when a live batch's step fails, and finalizes what arrived", async () => {+ mocks.prepare.mockResolvedValue({+ market: { locationCode: 2840, languageCode: "en" },+ modelBatches: [],+ live: true,+ batches: [[], []],+ });+ mocks.live.mockRejectedValueOnce(new Error("internal workflows error"));+ await execute();+ expect(mocks.live).toHaveBeenCalledTimes(2);+ expect(mocks.finalize).toHaveBeenCalledExactlyOnceWith("run");+ expect(mocks.markFailed).not.toHaveBeenCalled();+ });++ it("gives the free bookkeeping steps retries", async () => {+ await execute();+ for (const name of ["prepare", "finalize"])+ expect(mocks.steps).toHaveBeenCalledWith(name, {+ retries: { limit: 2, delay: "10 seconds" },+ timeout: "2 minutes",+ });+ });+it("fails the run when preparation fails", async () => {const error = new Error();mocks.prepare.mockRejectedValue(error);await expect(execute()).rejects.toThrow(error);expect(mocks.post).not.toHaveBeenCalled();expect(mocks.markFailed).toHaveBeenCalledExactlyOnceWith("run");+ expect(mocks.steps).toHaveBeenCalledWith("mark-failed", {+ retries: { limit: 2, delay: "10 seconds" },+ timeout: "2 minutes",+ });});it("does not log a rejected poll sleep as a failure, but still marks the run failed", async () => {diff --git a/src/server/workflows/AiVisibilityWorkflow.ts b/src/server/workflows/AiVisibilityWorkflow.tsindex 5e7995dc..b82df67a 100644--- a/src/server/workflows/AiVisibilityWorkflow.ts+++ b/src/server/workflows/AiVisibilityWorkflow.ts@@ -16,6 +16,7 @@ import {} from "@/server/features/ai-visibility/services/aiVisibilityCollection";import { runAiResearchSetup } from "@/server/features/ai-visibility/services/aiResearchKeywords";import type { BillingCustomerContext } from "@/server/billing/subscription";+import { describeError } from "@/server/lib/errors";// One binding serves answer collection runs and the one-time research setup,// so setup needs no new workflow infrastructure.@@ -31,6 +32,12 @@ const SINGLE_ATTEMPT = {retries: { limit: 0, delay: "1 second" as const },timeout: "2 minutes" as const,};+// Steps that only read and write our own rows are free and safe to repeat, so+// an engine failure on one attempt does not fail the run.+const FREE_STEP = {+ retries: { limit: 2, delay: "10 seconds" as const },+ timeout: "2 minutes" as const,+};// task_get is free and saving an answer replaces its evidence, so collect// steps can retry.const COLLECT_STEP = {@@ -78,13 +85,16 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<);const { runId, customer } = payload;const markFailed = async (error: unknown) => {- await pgStep(step, "mark-failed", SINGLE_ATTEMPT, () =>+ await pgStep(step, "mark-failed", FREE_STEP, () =>markAiRunFailed(runId),);throw error;};const failRun = (error: unknown) => {- console.error(`[ai-visibility] ${runId} failed:`, error);+ console.error(+ `[ai-visibility] ${runId} failed: ${describeError(error)}`,+ error,+ );return markFailed(error);};let pending: AiPendingTask[] = [];@@ -102,7 +112,9 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<);} catch (error) {// Posted tasks are already paid for; keep polling them next round.- console.warn(`[ai-visibility] ${runId} read-${name}:`, error);+ console.warn(+ `[ai-visibility] ${runId} read-${name}: ${describeError(error)}`,+ );return;}pending = round.pending;@@ -118,31 +130,48 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<);} catch (error) {// Its answers fail at finalize.- console.warn(`[ai-visibility] ${runId} repost-${name}:`, error);+ console.warn(+ `[ai-visibility] ${runId} repost-${name}: ${describeError(error)}`,+ );}}};try {- plan = await pgStep(step, "prepare", SINGLE_ATTEMPT, () =>+ plan = await pgStep(step, "prepare", FREE_STEP, () =>prepareAiRun(runId),);+ } catch (error) {+ return failRun(error);+ }+ // A batch whose step fails, on the engine's own error or a timeout, leaves+ // its answers pending for finalize to fail. The other batches still run,+ // so the run keeps every answer it got.+ if (plan.live)// Live runs save each live batch as it returns, so nothing is left// pending to poll.- if (plan.live)- for (const [index, tasks] of plan.batches.entries())+ for (const [index, tasks] of plan.batches.entries())+ try {await pgStep(step, `live-${index}`, LIVE_STEP, () =>collectAiLiveBatch(runId, customer, plan.market, tasks),);- else- for (const [index, batch] of plan.batches.entries())+ } catch (error) {+ console.warn(+ `[ai-visibility] ${runId} live-${index}: ${describeError(error)}`,+ );+ }+ else+ for (const [index, batch] of plan.batches.entries())+ try {pending.push(...(await pgStep(step, `post-${index}`, SINGLE_ATTEMPT, () =>postAiBatch(runId, customer, plan.market, batch),)),);- } catch (error) {- return failRun(error);- }+ } catch (error) {+ console.warn(+ `[ai-visibility] ${runId} post-${index}: ${describeError(error)}`,+ );+ }// Claude and Perplexity answers come from the model API on every run.// Queued answers process meanwhile, and each model batch is followed by// one free read of them.@@ -153,7 +182,9 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<);} catch (error) {// Its unsaved answers fail at finalize; the other batches continue.- console.warn(`[ai-visibility] ${runId} model-${index}:`, error);+ console.warn(+ `[ai-visibility] ${runId} model-${index}: ${describeError(error)}`,+ );}if (pending.length) await collect(`model-${index}`, true);}@@ -175,9 +206,7 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<await collect(`${round}`, round < POLL_INTERVALS.length - 1);}try {- await pgStep(step, "finalize", SINGLE_ATTEMPT, () =>- finalizeAiRun(runId),- );+ await pgStep(step, "finalize", FREE_STEP, () => finalizeAiRun(runId));} catch (error) {return failRun(error);}diff --git a/src/server/workflows/LocalRankWorkflow.ts b/src/server/workflows/LocalRankWorkflow.tsindex de059dad..35632c93 100644--- a/src/server/workflows/LocalRankWorkflow.ts+++ b/src/server/workflows/LocalRankWorkflow.ts@@ -11,6 +11,7 @@ import {searchLocalPoints,} from "@/server/features/local-seo/services/localSeoCollection";import { pgStep } from "./pgStep";+import { describeError } from "@/server/lib/errors";type LocalRankPayload = {checkId: string;@@ -64,7 +65,10 @@ export class LocalRankWorkflow extends WorkflowEntrypoint<finalizeLocalCheck(projectId, checkId),);} catch (error) {- console.error(`[local-seo] check ${checkId} failed:`, error);+ console.error(+ `[local-seo] check ${checkId} failed: ${describeError(error)}`,+ error,+ );await pgStep(step, "fail", undefined, () =>finalizeLocalCheck(projectId,diff --git a/src/server/workflows/RankCheckWorkflow.test.ts b/src/server/workflows/RankCheckWorkflow.test.tsindex 034008d3..f321bb6c 100644--- a/src/server/workflows/RankCheckWorkflow.test.ts+++ b/src/server/workflows/RankCheckWorkflow.test.ts@@ -37,12 +37,22 @@ vi.mock("@/server/workflows/rankCheckPaths", () => ({retryRankChecks: vi.fn(),}));vi.mock("@/server/workflows/pgStep", () => ({- pgStep: (+ // Like the engine, run() gets a rebuilt Error, never the thrown object.+ pgStep: async (_step: unknown,_name: string,_config: unknown,fn: () => unknown,- ) => fn(),+ ) => {+ try {+ return await fn();+ } catch (error) {+ throw new Error(+ error instanceof Error ? `${error.name}: ${error.message}` : "",+ { cause: error },+ );+ }+ },}));vi.mock("@/server/lib/dataforseo", () => ({createDataforseoClient: mocks.createDataforseoClient,@@ -56,6 +66,9 @@ vi.mock("@/server/billing/autumn", () => ({vi.mock("@/server/lib/runtime-env", () => ({isHostedServerAuthMode: mocks.isHostedServerAuthMode,}));+vi.mock("@/server/email/onboarding-drip", () => ({+ sendCreditsExhaustedEvent: vi.fn(),+}));const billingCustomer = {userId: "user_1",@@ -118,15 +131,28 @@ 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: 20 })).rejects.toMatchObject({- code: "VALIDATION_ERROR",- });+ await expect(runWorkflow({ maxCostCredits: 20 })).rejects.toThrow();expect(mocks.autumnCheck).not.toHaveBeenCalled();expect(mocks.createDataforseoClient).not.toHaveBeenCalled();expect(mocks.runLiveCheck).not.toHaveBeenCalled();});+ it("keeps a credits refusal as the bare code, so the credits card shows", async () => {+ mocks.getKeywordsForConfig.mockResolvedValue(keywords(5));+ mocks.autumnCheck.mockResolvedValue({ balance: { remaining: 0 } });++ await expect(runWorkflow({})).rejects.toThrow("INSUFFICIENT_CREDITS");++ expect(mocks.failRunIfActive).toHaveBeenCalledWith(+ "run_1",+ "INSUFFICIENT_CREDITS",+ );+ expect(mocks.updateConfig).toHaveBeenCalledWith("config_1", "project_1", {+ lastSkipReason: "insufficient_credits",+ });+ });+// Exactly at the ceiling is approved (the guard is strictly greater), and// callers without a ceiling — every scheduled check — must not be treated// as approving zero credits.diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.tsindex 05614af1..7331ecdb 100644--- a/src/server/workflows/RankCheckWorkflow.ts+++ b/src/server/workflows/RankCheckWorkflow.ts@@ -17,7 +17,7 @@ import { pgStep } from "@/server/workflows/pgStep";import { createDataforseoClient } from "@/server/lib/dataforseo";import { captureServerEvent } from "@/server/lib/posthog";import { sendCreditsExhaustedEvent } from "@/server/email/onboarding-drip";-import { AppError } from "@/server/lib/errors";+import { describeError } from "@/server/lib/errors";import { autumn } from "@/server/billing/autumn";import {AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,@@ -28,9 +28,14 @@ import {rankCheckCostApprovalError,} from "@/shared/rank-tracking";import { isHostedServerAuthMode } from "@/server/lib/runtime-env";--const SINGLE_ATTEMPT_STEP_CONFIG = {- retries: { limit: 0, delay: "1 second" as const },+import { isErrorCode } from "@/shared/error-codes";++// These steps cost nothing and are safe to repeat: they touch our own rows,+// prepare's Autumn calls only read balances, and its credits email is sent+// once a day. So an engine failure on one attempt does not fail the run. The+// paid batch steps live in rankCheckPaths and run once.+const FREE_STEP_CONFIG = {+ retries: { limit: 2, delay: "10 seconds" as const },timeout: "2 minutes" as const,};@@ -82,8 +87,10 @@ async function prepareRankCheckKeywords(input: {trackingKeywords = trackingKeywords.filter((kw) => idSet.has(kw.id));}+ // Refusals are not retried: a retry would only repeat them, and send the+ // credits email again.if (trackingKeywords.length === 0) {- throw new AppError("INTERNAL_ERROR", "No keywords to track");+ throw new NonRetryableError("No keywords to track");}const { costCredits } = estimateRankCheckCredits(@@ -93,8 +100,7 @@ async function prepareRankCheckKeywords(input: {input.trigger === "scheduled" ? "queued" : "live",);if (input.maxCostCredits != null && costCredits > input.maxCostCredits) {- throw new AppError(- "VALIDATION_ERROR",+ throw new NonRetryableError(rankCheckCostApprovalError(costCredits, input.maxCostCredits),);}@@ -120,7 +126,7 @@ async function prepareRankCheckKeywords(input: {if (available < costCredits) {await sendCreditsExhaustedEvent(input.billingCustomer);// The code alone, so the run's saved error shows the credits card.- throw new AppError("INSUFFICIENT_CREDITS");+ throw new NonRetryableError("INSUFFICIENT_CREDITS");}}@@ -247,15 +253,17 @@ async function markRankCheckRunFailed(input: {billingCustomer: BillingCustomerContext;error: unknown;}) {- const errorMessage =+ // run() catches the error the engine rebuilt from the failed step, never+ // the thrown object, with the message prefixed by the error's name. A+ // refusal's bare code under that prefix is what the run keeps, so the+ // credits card shows and the config can say why the check was skipped.+ const message =input.error instanceof Error ? input.error.message : "Unknown error";- await failRunIfActive(input.runId, errorMessage);+ const bare = message.replace(/^\w+: /, "");+ const refusal = isErrorCode(bare) ? bare : null;+ await failRunIfActive(input.runId, refusal ?? message);- // Flag the config so the UI can show why the scheduled check was skipped- const isInsufficientCredits =- input.error instanceof AppError &&- input.error.code === "INSUFFICIENT_CREDITS";- if (isInsufficientCredits) {+ if (refusal === "INSUFFICIENT_CREDITS") {await RankTrackingRepository.updateConfig(input.configId, input.projectId, {lastSkipReason: "insufficient_credits",});@@ -269,8 +277,7 @@ async function markRankCheckRunFailed(input: {project_id: input.projectId,status: "failed",// A code, not the message: provider errors can quote keywords or domains.- error_code:- input.error instanceof AppError ? input.error.code : "INTERNAL_ERROR",+ error_code: refusal ?? "INTERNAL_ERROR",},});}@@ -310,7 +317,7 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<const configCheck = await pgStep(step,"check-active",- { retries: { limit: 0, delay: "1 second" } },+ FREE_STEP_CONFIG,async () => {const cfg = await RankTrackingRepository.getConfigById({configId,@@ -332,7 +339,7 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<const prepareResult = await pgStep(step,"prepare",- { retries: { limit: 0, delay: "1 second" } },+ FREE_STEP_CONFIG,async () =>prepareRankCheckKeywords({runId,@@ -381,7 +388,7 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<console.warn(`[rank-check] ${runId} partial failure: ${batchError}`);}- await pgStep(step, "finalize", SINGLE_ATTEMPT_STEP_CONFIG, async () =>+ await pgStep(step, "finalize", FREE_STEP_CONFIG, async () =>finalizeRankCheckRun({runId,configId,@@ -393,8 +400,13 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<}),);} catch (error) {- console.error(`Rank check ${runId} failed:`, error);- await pgStep(step, "mark-failed", SINGLE_ATTEMPT_STEP_CONFIG, async () =>+ console.error(+ `Rank check ${runId} failed: ${describeError(error)}`,+ error,+ );+ // A retry after the body finished (an engine storage failure) sends the+ // failed event again; harmless.+ await pgStep(step, "mark-failed", FREE_STEP_CONFIG, async () =>markRankCheckRunFailed({runId,configId,diff --git a/src/server/workflows/SiteAuditWorkflow.ts b/src/server/workflows/SiteAuditWorkflow.tsindex 041b5491..fe31c543 100644--- a/src/server/workflows/SiteAuditWorkflow.ts+++ b/src/server/workflows/SiteAuditWorkflow.ts@@ -32,6 +32,7 @@ import {START_URL_STEP,} from "@/server/workflows/auditStepConfigs";import type { RenderUsage } from "@/shared/audit-rendering";+import { describeError } from "@/server/lib/errors";interface AuditParams {auditId: string;@@ -117,7 +118,7 @@ export class SiteAuditWorkflow extends WorkflowEntrypoint<Env, AuditParams> {renderUsage,});} catch (error) {- console.error(`Audit ${auditId} failed:`, error);+ console.error(`Audit ${auditId} failed: ${describeError(error)}`, error);// Deploy-time resets are expected churn, not actionable errors.const isDeployReset =error instanceof Error &&