Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(api): FirePDF async inline jobs get a deadline margin, aligned polling, and one submit retry (#4566)
Abimael Martell2343d7b7b93c
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsync.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsync.test.tsindex 436e1674e..5dc1a0293 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsync.test.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsync.test.ts@@ -17,6 +17,12 @@ import {savePdfResultToCache,} from "../../../../../lib/gcs-pdf-cache";import { config } from "../../../../../config";+import {+ jsonResp,+ makeFetchFromSequence,+ makeMeta,+ noopSleep,+} from "./firePDFAsyncFixtures";// ββ Fixtures βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -39,104 +45,6 @@ afterAll(() => {}});-type FakeResponse = {- status: number;- body: unknown;-};--function jsonResp({ status, body }: FakeResponse) {- return {- status,- json: async () => body,- } as any;-}--function makeMeta(overrides: Record<string, unknown> = {}) {- const noopLogger: any = {- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- debug: vi.fn(),- child: vi.fn(function child() {- return noopLogger;- }),- };-- return {- id: "scrape-id-test",- url: "https://example.com/doc.pdf",- rewrittenUrl: undefined,- logger: noopLogger,- mock: null,- abort: {- throwIfAborted: vi.fn(),- asSignal: vi.fn(() => new AbortController().signal),- scrapeTimeout: vi.fn(() => 60_000),- },- internalOptions: {- zeroDataRetention: false,- teamId: "team-x",- teamConcurrency: 12,- crawlId: undefined,- },- options: {- parsers: [{ type: "pdf", __firePdfAsync: true }],- },- largePdfProcessing: {},- ...overrides,- } as any;-}--function makeFetchFromSequence(- matchers: Array<{- matchUrl: RegExp;- matchMethod?: "DELETE" | "GET" | "POST";- response: FakeResponse | (() => FakeResponse);- }>,-) {- const calls: Array<{- url: string;- method: string;- headers: Record<string, string> | undefined;- body: unknown;- }> = [];- const cursor = { idx: 0 };- const fetchImpl: any = async (url: string, init: any) => {- const method = (init?.method ?? "GET").toUpperCase();- let body: unknown;- try {- body = init?.body ? JSON.parse(init.body) : undefined;- } catch {- body = init?.body;- }- calls.push({ url, method, headers: init?.headers, body });- const matcher = matchers[cursor.idx++];- if (!matcher) {- throw new Error(- `unexpected request #${cursor.idx} to ${method} ${url} (no matcher left)`,- );- }- if (!matcher.matchUrl.test(url)) {- throw new Error(- `request ${cursor.idx} url mismatch: got ${url}, expected ${matcher.matchUrl}`,- );- }- if (matcher.matchMethod && matcher.matchMethod !== method) {- throw new Error(- `request ${cursor.idx} method mismatch: got ${method}, expected ${matcher.matchMethod}`,- );- }- const r =- typeof matcher.response === "function"- ? matcher.response()- : matcher.response;- return jsonResp(r);- };- return { fetchImpl, calls };-}--const noopSleep = async () => {};-// ββ Tests ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdescribe("scrapePDFWithFirePDFAsync", () => {@@ -724,22 +632,24 @@ describe("scrapePDFWithFirePDFAsync", () => {});it.each([- ["401", 401, "http_401"],- ["404", 404, "http_404"],- ["410", 410, "http_410"],- ["413", 413, "http_413"],- ["429", 429, "http_429"],- ["502", 502, "http_502"],- ["503", 503, "http_503"],- ["generic 5xx", 500, "http_5xx"],+ ["401", 401, "http_401", { error: "x" }],+ ["404", 404, "http_404", { error: "x" }],+ ["410", 410, "http_410", { error: "x" }],+ ["413", 413, "http_413", { error: "x" }],+ ["429", 429, "http_429", { error: "x" }],+ ["502", 502, "http_502", { error: "x" }],+ // A 503 is only fire-pdf's own when it carries one of its documented+ // codes; any other 503 body is retried once (firePDFAsyncDeadline.test).+ ["503", 503, "http_503", { error: "admission_unavailable" }],+ ["generic 5xx", 500, "http_5xx", { error: "x" }],])("throws FirePdfAsyncFailure when POST /jobs returns %s",- async (_, status, reason) => {+ async (_, status, reason, body) => {const { fetchImpl, calls } = makeFetchFromSequence([{matchUrl: /\/jobs$/,matchMethod: "POST",- response: { status, body: { error: "x" } },+ response: { status, body },},]);const fallback = vi.fn();@@ -785,7 +695,10 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(err).toBeInstanceOf(FirePdfAsyncFailure);expect(err.reason).toBe("network_error");expect(fallback).not.toHaveBeenCalled();+ // One retry on a fresh connection, then the ambiguous failure is+ // treated as possibly accepted and the scrape_id is cancelled.expect(calls.map(({ url, method }) => ({ url, method }))).toEqual([+ { method: "POST", url: "http://fire-pdf.test/jobs" },{ method: "POST", url: "http://fire-pdf.test/jobs" },{method: "DELETE",@@ -990,13 +903,13 @@ describe("scrapePDFWithFirePDFAsync", () => {]);const fallback = vi.fn();- // 15s scrape budget β polling deadline = submit + 15s + 30s = 45s.+ // 25s scrape budget β polling deadline = submit + 25s + 30s = 55s.// Each sleep advances time by 60s, blowing past the polling deadline.const meta = makeMeta({abort: {throwIfAborted: vi.fn(),asSignal: vi.fn(() => new AbortController().signal),- scrapeTimeout: vi.fn(() => 15_000),+ scrapeTimeout: vi.fn(() => 25_000),},});diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncDeadline.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncDeadline.test.tsnew file mode 100644index 000000000..be11af646--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncDeadline.test.ts@@ -0,0 +1,316 @@+// Stub the GCS cache so unit tests never reach real cloud storage β same+// setup as firePDFAsync.test.ts, which covers the orchestration end to end.+vi.mock("../../../../../lib/gcs-pdf-cache", () => ({+ createPdfCacheKey: (s: string) => `sha-${s.length}`,+ getPdfResultFromCache: vi.fn(async () => null),+ savePdfResultToCache: vi.fn(async () => null),+}));++import {+ FirePdfAsyncFailure,+ scrapePDFWithFirePDFAsync,+} from "../fire-pdf/async";+import {+ firePdfAsyncAbandonedTotal,+ firePdfAsyncSubmitRetriesTotal,+} from "../fire-pdf/metrics";+import { AbortManagerThrownError } from "../../../lib/abortManager";+import { config } from "../../../../../config";+import {+ counterValue,+ jsonResp,+ makeFetchFromSequence,+ makeMeta,+ noopSleep,+} from "./firePDFAsyncFixtures";++const BASE_URL_ENV = "FIRE_PDF_BASE_URL";+const ORIGINAL_BASE_URL = process.env[BASE_URL_ENV];++beforeAll(() => {+ process.env[BASE_URL_ENV] = "http://fire-pdf.test";+ (config as { FIRE_PDF_BASE_URL?: string }).FIRE_PDF_BASE_URL =+ "http://fire-pdf.test";+});++afterAll(() => {+ if (ORIGINAL_BASE_URL === undefined) {+ delete process.env[BASE_URL_ENV];+ } else {+ process.env[BASE_URL_ENV] = ORIGINAL_BASE_URL;+ }+});++// How an inline async attempt behaves around the caller's window: the job+// deadline it advertises, how polling tracks that deadline, the one submit+// retry for a request that never reached fire-pdf, and what is counted when+// the caller's window closes first.+describe("scrapePDFWithFirePDFAsync β deadline and submit lifecycle", () => {+ it("advertises an inline job deadline with a margin inside the caller window", async () => {+ let submittedBody: any;+ const virtualNow = 1_700_000_000_000;+ const fetchImpl: any = async (url: string, init: any) => {+ if (/\/jobs$/.test(url) && (init?.method ?? "GET") === "POST") {+ submittedBody = JSON.parse(init.body as string);+ return jsonResp({+ status: 200,+ body: { scrape_id: "x", status: "done", pages_processed: 1 },+ });+ }+ return jsonResp({+ status: 200,+ body: { markdown: "ok", pages_processed: 1 },+ });+ };++ // 60s caller window β 10s margin (10% is 6s, floored at 10s) β 50s job.+ await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ {+ fetchImpl,+ fallbackImpl: vi.fn(),+ sleepImpl: noopSleep,+ nowImpl: () => virtualNow,+ },+ );++ expect(submittedBody.deadline_at).toBe(+ new Date(virtualNow + 50_000).toISOString(),+ );+ });++ it("polls land just after the job deadline and at the floor thereafter", async () => {+ let virtualNow = 1_000_000;+ const sleeps: number[] = [];+ const pollTimes: number[] = [];+ let polls = 0;+ const fetchImpl: any = async (url: string, init: any) => {+ const method = (init?.method ?? "GET").toUpperCase();+ if (/\/jobs$/.test(url) && method === "POST") {+ return jsonResp({+ status: 202,+ body: {+ scrape_id: "x",+ status: "queued",+ lane: "standard",+ retry_after_ms: 1000,+ },+ });+ }+ if (/\/jobs\/scrape-id-test$/.test(url)) {+ polls++;+ pollTimes.push(virtualNow - 1_000_000);+ // Running until the poll after the job deadline; done on the next.+ return jsonResp(+ polls <= 6+ ? { status: 202, body: { scrape_id: "x", status: "running" } }+ : {+ status: 200,+ body: { scrape_id: "x", status: "done", pages_processed: 3 },+ },+ );+ }+ return jsonResp({+ status: 200,+ body: { markdown: "ok", pages_processed: 3 },+ });+ };++ // 30s caller window β 20s job deadline. Backoff without jitter runs+ // 1s, 2s, 4s, 5s, 5s (t=17s); the next 5s sleep would overshoot the+ // deadline, so it is cut to land at 21s (deadline + 1s grace); still+ // running there, so the following poll comes after the 1s floor.+ const meta = makeMeta({+ abort: {+ throwIfAborted: vi.fn(),+ asSignal: vi.fn(() => new AbortController().signal),+ scrapeTimeout: vi.fn(() => 30_000),+ },+ });+ const result = await scrapePDFWithFirePDFAsync(+ meta,+ "BASE64",+ undefined,+ undefined,+ undefined,+ {+ fetchImpl,+ fallbackImpl: vi.fn(),+ sleepImpl: async ms => {+ sleeps.push(ms);+ virtualNow += ms;+ },+ nowImpl: () => virtualNow,+ randomImpl: () => 0,+ },+ );++ expect(result.markdown).toBe("ok");+ expect(sleeps).toEqual([1000, 2000, 4000, 5000, 5000, 4000, 1000]);+ expect(pollTimes).toEqual([1000, 3000, 7000, 12000, 17000, 21000, 22000]);+ });++ it("retries the submit once when a closing api pod answers with Fastify's 503 body", async () => {+ const before = await counterValue(firePdfAsyncSubmitRetriesTotal, {+ trigger: "http_503_closing",+ });+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 503,+ body: {+ error: "Service Unavailable",+ message: "Service Unavailable",+ statusCode: 503,+ },+ },+ },+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 200,+ body: { scrape_id: "scrape-id-test", status: "done", lane: "fast" },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test\/result$/,+ matchMethod: "GET",+ response: { status: 200, body: { markdown: "ok", pages_processed: 1 } },+ },+ ]);++ const result = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ );++ expect(result.markdown).toBe("ok");+ expect(calls.filter(c => c.method === "POST")).toHaveLength(2);+ expect(+ await counterValue(firePdfAsyncSubmitRetriesTotal, {+ trigger: "http_503_closing",+ }),+ ).toBe(before + 1);+ });++ it("does not retry fire-pdf's own 503 codes", async () => {+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 503,+ body: {+ error: "admission_rejected",+ message: "queue cannot drain within the submitted deadline",+ },+ },+ },+ ]);++ const error = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ ).catch(e => e);++ expect(error).toBeInstanceOf(FirePdfAsyncFailure);+ expect(error.reason).toBe("http_503");+ expect(calls).toHaveLength(1);+ });++ it("retries the submit once on a transport failure, then proceeds", async () => {+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: () => {+ throw new Error("socket hang up");+ },+ },+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 200,+ body: { scrape_id: "scrape-id-test", status: "done", lane: "fast" },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test\/result$/,+ matchMethod: "GET",+ response: { status: 200, body: { markdown: "ok", pages_processed: 1 } },+ },+ ]);++ const result = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ );++ expect(result.markdown).toBe("ok");+ expect(calls.filter(c => c.method === "POST")).toHaveLength(2);+ });++ it("counts an attempt abandoned by the caller's abort while polling, and still cancels", async () => {+ const before = await counterValue(firePdfAsyncAbandonedTotal, {+ phase: "poll",+ });+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 202,+ body: { scrape_id: "scrape-id-test", status: "queued", lane: "fast" },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "DELETE",+ response: { status: 200, body: { status: "cancelled" } },+ },+ ]);+ const abort = new AbortManagerThrownError("scrape", new Error("timeout"));++ const error = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ {+ fetchImpl,+ fallbackImpl: vi.fn(),+ // The scrape window closes during the first poll sleep.+ sleepImpl: async () => {+ throw abort;+ },+ },+ ).catch(e => e);++ expect(error).toBe(abort);+ expect(calls.map(c => c.method)).toEqual(["POST", "DELETE"]);+ expect(+ await counterValue(firePdfAsyncAbandonedTotal, { phase: "poll" }),+ ).toBe(before + 1);+ });+});diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncFixtures.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncFixtures.tsnew file mode 100644index 000000000..a442bd55e--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncFixtures.ts@@ -0,0 +1,116 @@+import { vi } from "vitest";+import type { Counter } from "prom-client";++// Shared fixtures for the fire-pdf async client suites: a fake response+// shape, a scrape `meta` with a controllable abort/timeout surface, and a+// sequenced fetch stub that asserts each request against the next matcher.++type FakeResponse = {+ status: number;+ body: unknown;+};++export function jsonResp({ status, body }: FakeResponse) {+ return {+ status,+ json: async () => body,+ } as any;+}++export function makeMeta(overrides: Record<string, unknown> = {}) {+ const noopLogger: any = {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+ child: vi.fn(function child() {+ return noopLogger;+ }),+ };++ return {+ id: "scrape-id-test",+ url: "https://example.com/doc.pdf",+ rewrittenUrl: undefined,+ logger: noopLogger,+ mock: null,+ abort: {+ throwIfAborted: vi.fn(),+ asSignal: vi.fn(() => new AbortController().signal),+ scrapeTimeout: vi.fn(() => 60_000),+ },+ internalOptions: {+ zeroDataRetention: false,+ teamId: "team-x",+ teamConcurrency: 12,+ crawlId: undefined,+ },+ options: {+ parsers: [{ type: "pdf", __firePdfAsync: true }],+ },+ largePdfProcessing: {},+ ...overrides,+ } as any;+}++export function makeFetchFromSequence(+ matchers: Array<{+ matchUrl: RegExp;+ matchMethod?: "DELETE" | "GET" | "POST";+ response: FakeResponse | (() => FakeResponse);+ }>,+) {+ const calls: Array<{+ url: string;+ method: string;+ headers: Record<string, string> | undefined;+ body: unknown;+ }> = [];+ const cursor = { idx: 0 };+ const fetchImpl: any = async (url: string, init: any) => {+ const method = (init?.method ?? "GET").toUpperCase();+ let body: unknown;+ try {+ body = init?.body ? JSON.parse(init.body) : undefined;+ } catch {+ body = init?.body;+ }+ calls.push({ url, method, headers: init?.headers, body });+ const matcher = matchers[cursor.idx++];+ if (!matcher) {+ throw new Error(+ `unexpected request #${cursor.idx} to ${method} ${url} (no matcher left)`,+ );+ }+ if (!matcher.matchUrl.test(url)) {+ throw new Error(+ `request ${cursor.idx} url mismatch: got ${url}, expected ${matcher.matchUrl}`,+ );+ }+ if (matcher.matchMethod && matcher.matchMethod !== method) {+ throw new Error(+ `request ${cursor.idx} method mismatch: got ${method}, expected ${matcher.matchMethod}`,+ );+ }+ const r =+ typeof matcher.response === "function"+ ? matcher.response()+ : matcher.response;+ return jsonResp(r);+ };+ return { fetchImpl, calls };+}++export const noopSleep = async () => {};++/** Current value of one labelled series of a prom-client counter (0 if unseen). */+export async function counterValue(+ counter: Counter<string>,+ labels: Record<string, string>,+): Promise<number> {+ const { values } = await counter.get();+ const hit = values.find(v =>+ Object.entries(labels).every(([k, val]) => String(v.labels[k]) === val),+ );+ return hit?.value ?? 0;+}diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncPolicy.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncPolicy.test.tsnew file mode 100644index 000000000..e22ca55ac--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncPolicy.test.ts@@ -0,0 +1,81 @@+import { FIRE_PDF_ASYNC_MIN_REMAINING_MS } from "../fire-pdf/routing";+import { FIRE_PDF_SUBMIT_503_CODES } from "../fire-pdf/schema";+import { classifyTransient503 } from "../fire-pdf/submit";+import { alignPollDelay, computeInlineJobDeadlineMs } from "../fire-pdf/utils";++// Pure policy for the fire-pdf async client: deadline math, poll scheduling+// around the job deadline, and submit-503 classification. The orchestration+// suite (firePDFAsync.test.ts) covers how these compose on the wire.++describe("computeInlineJobDeadlineMs", () => {+ it("takes a 10% margin off the caller window, floored at 10s and capped at 30s", () => {+ expect(computeInlineJobDeadlineMs(30_000)).toBe(20_000);+ expect(computeInlineJobDeadlineMs(60_000)).toBe(50_000);+ expect(computeInlineJobDeadlineMs(300_000)).toBe(270_000);+ expect(computeInlineJobDeadlineMs(1_800_000)).toBe(1_770_000);+ });++ it("never advertises less than fire-pdf's 5s minimum", () => {+ expect(computeInlineJobDeadlineMs(15_000)).toBe(5_000);+ expect(computeInlineJobDeadlineMs(1_000)).toBe(5_000);+ });++ it("leaves the smallest window the router admits a deadline above the minimum", () => {+ expect(computeInlineJobDeadlineMs(FIRE_PDF_ASYNC_MIN_REMAINING_MS)).toBe(+ 10_000,+ );+ });+});++describe("alignPollDelay", () => {+ const now = 100_000;++ it("leaves backoff alone without a job deadline or with one far away", () => {+ expect(alignPollDelay(5_000, now, undefined)).toBe(5_000);+ expect(alignPollDelay(5_000, now, now + 60_000)).toBe(5_000);+ });++ it("pulls the next poll to land just after the job deadline", () => {+ expect(alignPollDelay(5_000, now, now + 2_500)).toBe(3_500);+ expect(alignPollDelay(5_000, now, now + 200)).toBe(1_200);+ });++ it("polls at the floor once the job deadline has passed", () => {+ expect(alignPollDelay(5_000, now, now - 500)).toBe(1_000);+ expect(alignPollDelay(5_000, now, now - 5_000)).toBe(1_000);+ });+});++describe("classifyTransient503", () => {+ it("names the retry trigger for a 503 that never reached fire-pdf's handler", () => {+ expect(+ classifyTransient503(503, {+ error: "Service Unavailable",+ message: "Service Unavailable",+ statusCode: 503,+ }),+ ).toBe("http_503_closing");+ expect(classifyTransient503(503, {})).toBe("http_503_unattributed");+ expect(classifyTransient503(503, null)).toBe("http_503_unattributed");+ // An intermediary's own snake_case code is not a fire-pdf code.+ expect(+ classifyTransient503(503, {+ error: "upstream_unavailable",+ message: "no healthy upstream",+ }),+ ).toBe("http_503_unattributed");+ });++ it("leaves fire-pdf's own 503 codes and other statuses alone", () => {+ for (const code of FIRE_PDF_SUBMIT_503_CODES) {+ expect(classifyTransient503(503, { error: code })).toBe(null);+ }+ expect(+ classifyTransient503(503, {+ error: "admission_unavailable",+ message: "could not safely admit async work",+ }),+ ).toBe(null);+ expect(classifyTransient503(502, {})).toBe(null);+ });+});diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/async.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/async.tsindex 06994b70e..10c802085 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/async.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/async.ts@@ -2,12 +2,17 @@ import type { Meta } from "../../..";import type { PDFMode } from "../../../../../controllers/v2/types";import { config } from "../../../../../config";import { fetch as undiciFetch } from "undici";+import { AbortManagerThrownError } from "../../../lib/abortManager";import type { PDFProcessorResult } from "../types";import { safeMarkdownToHtml } from "../markdownToHtml";import { scrapePDFWithFirePDF } from "../firePDF";import { cancelJob } from "./cancel";import { tryGetCached, maybeSaveResult } from "./cache";-import { firePdfAsyncTotalDurationSeconds } from "./metrics";+import {+ firePdfAsyncAbandonedTotal,+ firePdfAsyncTotalDurationSeconds,+ type AbandonedPhase,+} from "./metrics";import { pollUntilTerminal } from "./poll";import { fetchResult } from "./result";import type { FirePdfByReferenceInput } from "./by-reference";@@ -18,6 +23,7 @@ import { submitJob, SubmitJobMayHaveBeenAcceptedError } from "./submit";import {computeByReferenceDeadlineMs,computeDeadlineMs,+ computeInlineJobDeadlineMs,defaultSleep,failAsync,FirePdfAsyncFailure,@@ -154,18 +160,22 @@ export async function scrapePDFWithFirePDFAsync(const callerWindowMs = computeDeadlineMs(remainingMs);// The JOB deadline is decoupled from the caller for by-reference// submits: page-scaled, never below the caller window, capped at- // 30 min. An inline job's deadline stays the caller window exactly β- // when its caller dies, the job is cancelled and the work discarded, so- // advertising more time would be a lie. A by-reference job instead- // outlives its caller on purpose (cancel is skipped below): it finishes- // server-side, lands in the raw-sha cache and the content-adoption- // lookup, and the customer's retry β with a fresh scrape_id β converges- // instead of restarting a multi-minute document from zero. Callers- // wanting first-attempt success must still pass an explicit `timeout`.+ // 30 min. An inline job's deadline sits INSIDE the caller window by a+ // margin (computeInlineJobDeadlineMs): when its caller dies the job is+ // cancelled and the work discarded, so the worker must reach its own+ // deadline β and write the deadline-degraded result it produces there β+ // while the caller is still around to poll and fetch it. A by-reference+ // job instead outlives its caller on purpose (cancel is skipped below):+ // it finishes server-side, lands in the raw-sha cache and the+ // content-adoption lookup, and the customer's retry β with a fresh+ // scrape_id β converges instead of restarting a multi-minute document+ // from zero. Callers wanting first-attempt success must still pass an+ // explicit `timeout`.const deadlineFromNow = byReference? computeByReferenceDeadlineMs(remainingMs, pagesProcessed)- : callerWindowMs;- const deadlineAt = new Date(submitTime + deadlineFromNow).toISOString();+ : computeInlineJobDeadlineMs(callerWindowMs);+ const jobDeadlineAtMs = submitTime + deadlineFromNow;+ const deadlineAt = new Date(jobDeadlineAtMs).toISOString();const pollingDeadline = submitTime + callerWindowMs + POLL_TIMEOUT_BUFFER_MS;// Account context for FirePDF's per-team admission observation,@@ -181,6 +191,7 @@ export async function scrapePDFWithFirePDFAsync(// ββ Step 1: POST /jobs (skipped when adopting an existing job) ββββββββlet submissionAccepted = false;let terminalReached = false;+ let lastNonTerminalStatus: "queued" | "published" | "running" | undefined;let polled: Awaited<ReturnType<typeof pollUntilTerminal>>;let fetched: Awaited<ReturnType<typeof fetchResult>>;// What goes on the wire for step 1 β null means nothing does: an@@ -239,6 +250,7 @@ export async function scrapePDFWithFirePDFAsync(deadlineAt,teamConcurrency,fetchImpl,+ sleep,});submissionAccepted = true;alreadyDone = submit.alreadyDone;@@ -253,7 +265,7 @@ export async function scrapePDFWithFirePDFAsync(jobScrapeId,pagesEstimate: pagesProcessed,submittedAtMs: submitTime,- jobDeadlineAtMs: submitTime + deadlineFromNow,+ jobDeadlineAtMs,lastStatus: "queued",};}@@ -276,7 +288,13 @@ export async function scrapePDFWithFirePDFAsync(sleep,now,random,+ // Only a job WE submitted inline has a deadline we know and that+ // sits inside this caller's window. An adopted job's deadline is+ // its owner's; a by-reference job's lies beyond the window.+ jobDeadlineAtMs:+ wireInput?.kind === "inline" ? jobDeadlineAtMs : undefined,onNonTerminalStatus: (status, estimatedRemainingMs) => {+ lastNonTerminalStatus = status;const current = meta.largePdfProcessing?.current;if (!current) return;current.lastStatus = status;@@ -310,6 +328,37 @@ export async function scrapePDFWithFirePDFAsync(// The job is dead β a "processing continues" message would lie.meta.largePdfProcessing.current = undefined;}+ const abortError =+ error instanceof AbortManagerThrownError+ ? error+ : submitMayHaveBeenAccepted &&+ error.originalError instanceof AbortManagerThrownError+ ? error.originalError+ : undefined;+ if (abortError?.tier === "scrape") {+ // The caller's scrape window closed first β the outcome the job+ // deadline margin exists to avoid β so count where it happened.+ // Engine-tier aborts (the waterfall moving on) and external aborts+ // (the client hung up) are not that signal.+ const phase: AbandonedPhase =+ wireInput !== null && !submissionAccepted+ ? "submit"+ : terminalReached+ ? "result"+ : "poll";+ firePdfAsyncAbandonedTotal.labels(phase).inc();+ meta.logger.warn("FirePDF async abandoned by caller abort", {+ scrapeId: meta.id,+ event: "fire_pdf_async_abandoned",+ phase,+ tier: abortError.tier,+ lastStatus: lastNonTerminalStatus,+ // Only meaningful for a job this attempt submitted itself.+ jobDeadlineInMs:+ wireInput !== null ? jobDeadlineAtMs - now() : undefined,+ elapsedMs: now() - overallStartedAt,+ });+ }if (cancelOnAbandon &&(submissionAccepted || submitMayHaveBeenAccepted) &&diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/metrics.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/metrics.tsindex 410e05ee8..ecdb5acaf 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/metrics.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/metrics.ts@@ -24,12 +24,31 @@ export const firePdfAsyncTotalDurationSeconds = new Histogram({buckets: [0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600, 1200, 1800],});+export const firePdfAsyncSubmitRetriesTotal = new Counter({+ name: "firecrawl_fire_pdf_async_submit_retries_total",+ help: "Count of POST /jobs retries after a transient failure that never reached fire-pdf's handler",+ labelNames: ["trigger"],+});++export const firePdfAsyncAbandonedTotal = new Counter({+ name: "firecrawl_fire_pdf_async_abandoned_total",+ help: "Count of fire-pdf async attempts abandoned because the caller's scrape window closed first",+ labelNames: ["phase"],+});+export const firePdfAsyncPollCount = new Histogram({name: "firecrawl_fire_pdf_async_poll_count",help: "Number of GET /jobs/:id polls performed per fire-pdf async job",buckets: [1, 2, 5, 10, 20, 50, 100, 200, 500],});+export type SubmitRetryTrigger =+ | "transport_error"+ | "http_503_closing"+ | "http_503_unattributed";++export type AbandonedPhase = "submit" | "poll" | "result";+export type FallbackReason =| "http_401"| "http_404"diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/poll.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/poll.tsindex af6d93e95..5d3afdbce 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/poll.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/poll.ts@@ -11,7 +11,12 @@ import {TERMINAL_STATUSES,type PollResponse,} from "./schema";-import { failAsync, firePdfHeaders, nextPollDelay } from "./utils";+import {+ alignPollDelay,+ failAsync,+ firePdfHeaders,+ nextPollDelay,+} from "./utils";type PollDeps = {baseUrl: string;@@ -23,6 +28,10 @@ type PollDeps = {sleep: (ms: number, signal?: AbortSignal) => Promise<void>;now: () => number;random?: () => number;+ /** When the job is expected to finish (its `deadline_at`). Polls are+ * pulled forward to land just after it and run at the floor past it β+ * see alignPollDelay. Absent, plain backoff applies throughout. */+ jobDeadlineAtMs?: number;/** Observes each non-terminal status seen while polling β lets the* caller keep a live "where is this job" snapshot (used to enrich* timeout errors for by-reference jobs that outlive the scrape).@@ -49,7 +58,10 @@ export async function pollUntilTerminal(deps: PollDeps): Promise<PollOk> {}meta.abort.throwIfAborted();- await sleep(lastDelay, meta.abort.asSignal());+ await sleep(+ alignPollDelay(lastDelay, now(), deps.jobDeadlineAtMs),+ meta.abort.asSignal(),+ );pollCount++;let pollResp;diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/routing.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/routing.tsindex 958b96e04..ae4c26e23 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/routing.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/routing.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";-import { MIN_DEADLINE_MS } from "./schema";+import { MIN_ASYNC_CALLER_WINDOW_MS } from "./schema";-export const FIRE_PDF_ASYNC_MIN_REMAINING_MS = MIN_DEADLINE_MS + 10_000;+export const FIRE_PDF_ASYNC_MIN_REMAINING_MS = MIN_ASYNC_CALLER_WINDOW_MS;type FirePdfAsyncRouteReason =| "zdr"diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/schema.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/schema.tsindex db5fb594d..7054d3685 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/schema.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/schema.ts@@ -11,6 +11,38 @@ export const POLL_FLOOR_MS = 1_000;export const POLL_CAP_MS = 5_000;export const POLL_TIMEOUT_BUFFER_MS = 30_000;+// An inline job's deadline sits this far inside the caller's window. The+// caller aborts the scrape the instant its window closes, so a job that is+// still wrapping up at that instant is cancelled and every processed page is+// lost. The margin covers the worker's end-of-deadline work (degrade the+// remaining pages, assemble, upload) plus one poll interval and the result+// fetch, so the deadline-degraded result the worker produces anyway is the+// one the caller receives: 10% of the window, floored at 10s (a backoff-capped+// poll alone is ~6s with jitter) and capped at 30s.+export const INLINE_JOB_DEADLINE_MARGIN_FRACTION = 0.1;+export const INLINE_JOB_DEADLINE_MARGIN_MIN_MS = 10_000;+export const INLINE_JOB_DEADLINE_MARGIN_MAX_MS = 30_000;+// Polls are pulled forward so one lands this long after the job deadline,+// then run at POLL_FLOOR_MS until the caller window closes: the job is+// expected to finish right there, and a backoff-capped poll would miss it.+export const JOB_DEADLINE_POLL_GRACE_MS = 1_000;+// One retry on a submit that provably never reached fire-pdf's handler: a+// transport failure, or a 503 carrying Fastify's canned shutdown body+// instead of one of fire-pdf's own 503 codes. Rolling api pods leave+// kept-alive connections pointed at terminating pods; the retry opens a+// fresh connection to a live one. POST /jobs is idempotent on scrape_id, so+// a first request that did land is replayed, never duplicated.+export const SUBMIT_TRANSIENT_RETRY_DELAY_MS = 250;+// Slack for the submit round trip: fire-pdf validates `deadline_at - now`+// against MIN_DEADLINE_MS on arrival, so the advertised deadline must clear+// it by at least the request's flight time.+export const INLINE_SUBMIT_SLACK_MS = 5_000;+// The smallest caller window async accepts. Below it, the margin would push+// the inline job deadline to (or under) fire-pdf's minimum and the submit+// would be rejected on arrival; such requests take the sync path instead.+export const MIN_ASYNC_CALLER_WINDOW_MS =+ MIN_DEADLINE_MS + INLINE_JOB_DEADLINE_MARGIN_MIN_MS + INLINE_SUBMIT_SLACK_MS;+export const TERMINAL_STATUSES = new Set(["done","failed",@@ -18,6 +50,42 @@ export const TERMINAL_STATUSES = new Set(["cancelled",]);+/** The 503 codes fire-pdf's submit handlers document (api/src/http/handlers+ * handle-submit-job / handle-sharded-submit). Closed on purpose: a 503 with+ * any other body did not come from one of them, so it is retried once. If+ * fire-pdf adds a code before this list learns it, the failure mode is one+ * idempotent extra POST β never a swallowed retry. */+export const FIRE_PDF_SUBMIT_503_CODES = [+ "admission_rejected",+ "admission_unavailable",+ "submit_preflight_failed",+ "submit_txn_failed",+ "page_markdown_not_ready",+ "gcs_upload_failed",+ "gcs_head_failed",+ "lookup_failed",+ "internal",+] as const;++/** Error body a fire-pdf submit handler sends with a 503: one of its+ * documented codes plus a human message. */+export const firePdfSubmit503BodySchema = z+ .object({+ error: z.enum(FIRE_PDF_SUBMIT_503_CODES),+ message: z.string().optional(),+ })+ .passthrough();++/** Fastify's canned reply while an instance is shutting down+ * (`return503OnClosing`, sent with `Connection: close` before any route+ * handler runs): the request was never processed. */+export const fastifyClosingBodySchema = z+ .object({+ error: z.literal("Service Unavailable"),+ statusCode: z.literal(503),+ })+ .passthrough();+export const submitResponseSchema = z.object({scrape_id: z.string(),status: z.enum(["queued", "published", "running", "done"]),diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/submit.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/submit.tsindex f9c32b883..762a99af3 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/submit.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/submit.ts@@ -2,9 +2,23 @@ import type { Meta } from "../../..";import type { PDFMode } from "../../../../../controllers/v2/types";import { fetch as undiciFetch } from "undici";import { AbortManagerThrownError } from "../../../lib/abortManager";-import { firePdfAsyncSubmittedTotal } from "./metrics";-import { submitResponseSchema } from "./schema";-import { buildFirePdfJobOptions, failAsync, firePdfHeaders } from "./utils";+import {+ firePdfAsyncSubmitRetriesTotal,+ firePdfAsyncSubmittedTotal,+ type SubmitRetryTrigger,+} from "./metrics";+import {+ SUBMIT_TRANSIENT_RETRY_DELAY_MS,+ fastifyClosingBodySchema,+ firePdfSubmit503BodySchema,+ submitResponseSchema,+} from "./schema";+import {+ buildFirePdfJobOptions,+ defaultSleep,+ failAsync,+ firePdfHeaders,+} from "./utils";type SubmitOutcome = {lane: string | undefined;@@ -35,6 +49,7 @@ type SubmitArgs = {* Optional: entitlement lookup must never block or fail a scrape. */teamConcurrency: number | undefined;fetchImpl: typeof undiciFetch;+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;};/**@@ -49,6 +64,26 @@ export class SubmitJobMayHaveBeenAcceptedError extends Error {}}+/**+ * A 503 is retryable when it did not come from a fire-pdf handler: the+ * handlers answer with one of their documented codes+ * (firePdfSubmit503BodySchema), so a 503 carrying anything else was produced+ * in front of them β Fastify's shutdown reply on a terminating instance, or a+ * proxy β and the request was never processed. Returns the retry trigger, or+ * null for a real fire-pdf 503 (admission and storage failures keep their+ * existing handling).+ */+export function classifyTransient503(+ status: number,+ body: unknown,+): Extract<SubmitRetryTrigger, `http_503_${string}`> | null {+ if (status !== 503) return null;+ if (firePdfSubmit503BodySchema.safeParse(body).success) return null;+ return fastifyClosingBodySchema.safeParse(body).success+ ? "http_503_closing"+ : "http_503_unattributed";+}+function failPossiblyAccepted(meta: Meta,reason: Parameters<typeof failAsync>[1],@@ -122,22 +157,62 @@ export async function submitJob(args: SubmitArgs): Promise<SubmitOutcome> {}),};+ // The retry does reach a different instance: Fastify's shutdown 503+ // arrives with `Connection: close`, and a transport failure leaves a dead+ // socket, so undici cannot reuse either connection β the next request+ // opens a new one, which the Service routes to a pod still in its+ // endpoints. The short pause lets endpoint updates propagate.+ const sleep = args.sleep ?? defaultSleep;+ const retryAfterTransient = async (+ trigger: SubmitRetryTrigger,+ extra: Record<string, unknown>,+ ) => {+ firePdfAsyncSubmitRetriesTotal.labels(trigger).inc();+ meta.logger.info("FirePDF async POST /jobs retrying once", {+ scrapeId,+ event: "fire_pdf_async_submit_retry",+ trigger,+ ...extra,+ });+ await sleep(SUBMIT_TRANSIENT_RETRY_DELAY_MS, meta.abort.asSignal());+ };+let status: number;let json: unknown;- try {- const resp = await fetchImpl(`${baseUrl}/jobs`, {- method: "POST",- headers: firePdfHeaders(true),- body: JSON.stringify(body),- signal: meta.abort.asSignal(),- });- status = resp.status;- json = await resp.json().catch(() => ({}));- } catch (error) {- if (error instanceof AbortManagerThrownError) {- throw new SubmitJobMayHaveBeenAcceptedError(error);+ for (let attempt = 1; ; attempt++) {+ try {+ const resp = await fetchImpl(`${baseUrl}/jobs`, {+ method: "POST",+ headers: firePdfHeaders(true),+ body: JSON.stringify(body),+ signal: meta.abort.asSignal(),+ });+ status = resp.status;+ json = await resp.json().catch(() => ({}));+ } catch (error) {+ if (error instanceof AbortManagerThrownError) {+ throw new SubmitJobMayHaveBeenAcceptedError(error);+ }+ if (attempt === 1) {+ // The request may have landed (idempotent replay makes the retry+ // safe either way); an abort during the pause keeps that ambiguity.+ try {+ await retryAfterTransient("transport_error", {+ error: String(error),+ });+ } catch (pauseError) {+ throw new SubmitJobMayHaveBeenAcceptedError(pauseError);+ }+ continue;+ }+ failPossiblyAccepted(meta, "network_error", { error: String(error) });+ }+ const transient503 = attempt === 1 && classifyTransient503(status, json);+ if (transient503) {+ await retryAfterTransient(transient503, { body: json });+ continue;}- failPossiblyAccepted(meta, "network_error", { error: String(error) });+ break;}if (status === 401) failAsync(meta, "http_401");diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/utils.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/utils.tsindex 9318e0d84..661dafa79 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/utils.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/utils.ts@@ -1,7 +1,16 @@import type { Meta } from "../../..";import type { PDFMode } from "../../../../../controllers/v2/types";import { config } from "../../../../../config";-import { MAX_DEADLINE_MS, POLL_FLOOR_MS, POLL_CAP_MS } from "./schema";+import {+ INLINE_JOB_DEADLINE_MARGIN_FRACTION,+ INLINE_JOB_DEADLINE_MARGIN_MAX_MS,+ INLINE_JOB_DEADLINE_MARGIN_MIN_MS,+ JOB_DEADLINE_POLL_GRACE_MS,+ MAX_DEADLINE_MS,+ MIN_DEADLINE_MS,+ POLL_FLOOR_MS,+ POLL_CAP_MS,+} from "./schema";import { firePdfAsyncFallbackTotal, type FallbackReason } from "./metrics";export function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {@@ -39,6 +48,45 @@ export function nextPollDelay(return Math.min(POLL_CAP_MS, jittered);}+/**+ * Deadline for an INLINE job: the caller window minus a margin, never below+ * fire-pdf's 5s minimum. The worker plans its work against this deadline and+ * degrades what is left when it arrives; the margin is what lets that result+ * be written, observed by a poll, and fetched before the caller's own abort+ * fires at the end of the window. Advertising the full window instead means+ * the worker is still finishing when the caller gives up β the job is+ * cancelled and the caller sees a timeout with nothing to show for it.+ */+export function computeInlineJobDeadlineMs(callerWindowMs: number): number {+ const margin = Math.min(+ INLINE_JOB_DEADLINE_MARGIN_MAX_MS,+ Math.max(+ INLINE_JOB_DEADLINE_MARGIN_MIN_MS,+ Math.round(callerWindowMs * INLINE_JOB_DEADLINE_MARGIN_FRACTION),+ ),+ );+ return Math.max(MIN_DEADLINE_MS, callerWindowMs - margin);+}++/**+ * Cap a poll delay so a poll lands just after the job deadline, and keep+ * polling at the floor once the deadline has passed. Backoff (up to+ * POLL_CAP_MS plus jitter) is right while the job is mid-flight; around the+ * deadline it is exactly wrong, because the result appears there and the+ * caller's window closes shortly after. A job deadline beyond the caller+ * window (by-reference) leaves the delay untouched.+ */+export function alignPollDelay(+ delayMs: number,+ nowMs: number,+ jobDeadlineAtMs: number | undefined,+): number {+ if (jobDeadlineAtMs === undefined) return delayMs;+ const untilTarget = jobDeadlineAtMs + JOB_DEADLINE_POLL_GRACE_MS - nowMs;+ if (untilTarget <= 0) return Math.min(delayMs, POLL_FLOOR_MS);+ return Math.min(delayMs, Math.max(POLL_FLOOR_MS, untilTarget));+}+export function computeDeadlineMs(scrapeTimeoutMs: number | undefined): number {// 5min default when there's no scrape budget. This matches the usable// window exactly: scrapeURLLoop races every engine against