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
feat(api): gate FirePDF async rollout (#4017)
Abimael Martellc9aa1419a825
diff --git a/apps/api/src/__tests__/snips/v2/parsers-fire-pdf-async.test.ts b/apps/api/src/__tests__/snips/v2/parsers-fire-pdf-async.test.tsindex d753c8572..34da0ceb2 100644--- a/apps/api/src/__tests__/snips/v2/parsers-fire-pdf-async.test.ts+++ b/apps/api/src/__tests__/snips/v2/parsers-fire-pdf-async.test.ts@@ -20,16 +20,15 @@ beforeAll(async () => {// CI) AND a fire-pdf base URL β the async client is only reached when// `useFirePDF` is true in the call site, which gates on FIRE_PDF_BASE_URL.//-// Behavior: the async client falls back to sync /ocr on any failure (including-// 404 when /jobs isn't deployed), so this test asserts the user-visible-// contract (markdown comes back), not which underlying engine served it.-// That keeps the test stable in environments where fire-pdf staging hasn't-// flipped /jobs on yet, while still verifying the flag is wired all the way-// through.+// Request-level async opt-in is disabled by default; this suite runs only in+// environments that intentionally allow the override. The outer PDF engine+// may still fall back to MinerU when async FirePDF is unavailable, so this+// asserts the user-visible contract rather than the serving engine.const SHOULD_RUN =ALLOW_TEST_SUITE_WEBSITE &&!process.env.TEST_SUITE_SELF_HOSTED &&- !!config.FIRE_PDF_BASE_URL;+ !!config.FIRE_PDF_BASE_URL &&+ config.FIRE_PDF_ASYNC_ALLOW_REQUEST_OVERRIDE;describeIf(SHOULD_RUN)("fire-pdf async parser flag", () => {const pdfUrl = `${TEST_SUITE_WEBSITE}/example.pdf`;diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex 112608208..a68d34af8 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -244,6 +244,12 @@ const configSchema = z.object({FIRE_PDF_PERCENT: z.coerce.number().min(0).max(100).default(10),FIRE_PDF_BASE_URL: z.string().optional(),FIRE_PDF_API_KEY: z.string().optional(),+ // Async /jobs rollout is a separate, server-controlled cohort inside+ // traffic already selected for FirePDF. It is disabled by default.+ FIRE_PDF_ASYNC_PERCENT: z.coerce.number().min(0).max(100).default(0),+ FIRE_PDF_ASYNC_FORCE_TEAM_IDS: z.string().optional(),+ FIRE_PDF_ASYNC_DISABLE_TEAM_IDS: z.string().optional(),+ FIRE_PDF_ASYNC_ALLOW_REQUEST_OVERRIDE: z.stringbool().default(false),// RunPodRUNPOD_MU_API_KEY: z.string().optional(),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 44405eafc..90c2224b2 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@@ -83,15 +83,19 @@ function makeMeta(overrides: Record<string, unknown> = {}) {function makeFetchFromSequence(matchers: Array<{matchUrl: RegExp;- matchMethod?: "GET" | "POST";+ matchMethod?: "DELETE" | "GET" | "POST";response: FakeResponse | (() => FakeResponse);}>,) {- const calls: Array<{ url: string; method: string }> = [];+ const calls: Array<{+ url: string;+ method: string;+ headers: Record<string, string> | undefined;+ }> = [];const cursor = { idx: 0 };const fetchImpl: any = async (url: string, init: any) => {const method = (init?.method ?? "GET").toUpperCase();- calls.push({ url, method });+ calls.push({ url, method, headers: init?.headers });const matcher = matchers[cursor.idx++];if (!matcher) {throw new Error(@@ -122,6 +126,59 @@ const noopSleep = async () => {};// ββ Tests ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdescribe("scrapePDFWithFirePDFAsync", () => {+ it("keeps ZDR on the synchronous FirePDF path", async () => {+ const fetchImpl = vi.fn();+ const fallback = vi.fn(async () => ({+ markdown: "zdr result",+ html: "<p>zdr result</p>",+ }));+ const meta = makeMeta({+ internalOptions: {+ zeroDataRetention: true,+ teamId: "team-x",+ crawlId: undefined,+ },+ });++ const result = await scrapePDFWithFirePDFAsync(+ meta,+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl: fetchImpl as any, fallbackImpl: fallback as any },+ );++ expect(result.markdown).toBe("zdr result");+ expect(fallback).toHaveBeenCalledOnce();+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it("rejects a deadline that cannot safely enter the queue", async () => {+ const fetchImpl = vi.fn();+ const fallback = vi.fn();+ const meta = makeMeta({+ abort: {+ throwIfAborted: vi.fn(),+ asSignal: vi.fn(() => new AbortController().signal),+ scrapeTimeout: vi.fn(() => 10_000),+ },+ });++ const error = await scrapePDFWithFirePDFAsync(+ meta,+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl: fetchImpl as any, fallbackImpl: fallback },+ ).catch(error => error);++ expect(error).toBeInstanceOf(FirePdfAsyncFailure);+ expect(error.reason).toBe("deadline_too_close");+ expect(fetchImpl).not.toHaveBeenCalled();+ });+it("happy path: POST 202 queued β poll done β result returns markdown", async () => {const { fetchImpl, calls } = makeFetchFromSequence([{@@ -186,6 +243,64 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(calls).toHaveLength(4);});+ it("cancels accepted work when polling is abandoned", async () => {+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 202,+ body: {+ scrape_id: "scrape-id-test",+ status: "queued",+ lane: "standard",+ },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "GET",+ response: () => {+ throw new Error("poll transport failed");+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "DELETE",+ response: { status: 200, body: { status: "cancelled" } },+ },+ ]);++ const error = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ ).catch(error => error);++ expect(error).toBeInstanceOf(FirePdfAsyncFailure);+ expect(error.reason).toBe("network_error");+ expect(calls).toEqual([+ {+ url: "http://fire-pdf.test/jobs",+ method: "POST",+ headers: expect.any(Object),+ },+ {+ url: "http://fire-pdf.test/jobs/scrape-id-test",+ method: "GET",+ headers: expect.any(Object),+ },+ {+ url: "http://fire-pdf.test/jobs/scrape-id-test",+ method: "DELETE",+ headers: expect.any(Object),+ },+ ]);+ });+it("idempotent replay: POST 200 done skips polling and fetches result", async () => {const { fetchImpl, calls } = makeFetchFromSequence([{@@ -193,7 +308,10 @@ describe("scrapePDFWithFirePDFAsync", () => {matchMethod: "POST",response: {status: 200,- body: { scrape_id: "scrape-id-test", status: "done" },+ body: {+ scrape_id: "scrape-id-test",+ status: "done",+ },},},{@@ -222,15 +340,18 @@ 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"],])("throws FirePdfAsyncFailure when POST /jobs returns %s",async (_, status, reason) => {- const { fetchImpl } = makeFetchFromSequence([+ const { fetchImpl, calls } = makeFetchFromSequence([{matchUrl: /\/jobs$/,matchMethod: "POST",@@ -251,12 +372,20 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(err).toBeInstanceOf(FirePdfAsyncFailure);expect(err.reason).toBe(reason);expect(fallback).not.toHaveBeenCalled();+ expect(calls).toHaveLength(1);+ expect(calls[0]).toMatchObject({ method: "POST" });},);- it("throws FirePdfAsyncFailure when POST /jobs throws a network error", async () => {- const fetchImpl: any = async () => {- throw new Error("connect ECONNREFUSED");+ it("cancels when POST /jobs has an ambiguous network failure", async () => {+ const calls: Array<{ method: string; url: string }> = [];+ const fetchImpl: any = async (url: string, init: any) => {+ const method = (init?.method ?? "GET").toUpperCase();+ calls.push({ method, url });+ if (method === "DELETE") {+ return jsonResp({ status: 404, body: {} });+ }+ throw new Error("connection reset after request write");};const fallback = vi.fn();@@ -272,6 +401,44 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(err).toBeInstanceOf(FirePdfAsyncFailure);expect(err.reason).toBe("network_error");expect(fallback).not.toHaveBeenCalled();+ expect(calls).toEqual([+ { method: "POST", url: "http://fire-pdf.test/jobs" },+ {+ method: "DELETE",+ url: "http://fire-pdf.test/jobs/scrape-id-test",+ },+ ]);+ });++ it("cancels a 2xx submit with an incompatible response body", async () => {+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 202,+ body: { scrape_id: "scrape-id-test", unexpected: true },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "DELETE",+ response: { status: 200, body: { status: "cancelled" } },+ },+ ]);++ const err = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ ).catch(error => error);++ expect(err).toBeInstanceOf(FirePdfAsyncFailure);+ expect(err.reason).toBe("http_5xx");+ expect(calls.map(call => call.method)).toEqual(["POST", "DELETE"]);});it("throws on POST 409 scrape_id conflict (fatal, no fallback)", async () => {@@ -301,16 +468,18 @@ describe("scrapePDFWithFirePDFAsync", () => {});it("throws FirePdfAsyncFailure when polling returns terminal failed (502)", async () => {- const { fetchImpl } = makeFetchFromSequence([+ const { fetchImpl, calls } = makeFetchFromSequence([{matchUrl: /\/jobs$/,+ matchMethod: "POST",response: {status: 202,- body: { scrape_id: "x", status: "queued" },+ body: { scrape_id: "x", status: "queued", lane: "fast" },},},{matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "GET",response: {status: 502,body: {@@ -336,19 +505,22 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(err).toBeInstanceOf(FirePdfAsyncFailure);expect(err.reason).toBe("terminal_failed");expect(fallback).not.toHaveBeenCalled();+ expect(calls.map(call => call.method)).toEqual(["POST", "GET"]);});it("throws FirePdfAsyncFailure when polling returns 410 (expired)", async () => {- const { fetchImpl } = makeFetchFromSequence([+ const { fetchImpl, calls } = makeFetchFromSequence([{matchUrl: /\/jobs$/,+ matchMethod: "POST",response: {status: 202,- body: { scrape_id: "x", status: "queued" },+ body: { scrape_id: "x", status: "queued", lane: "fast" },},},{matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "GET",response: {status: 410,body: { scrape_id: "x", status: "expired" },@@ -369,6 +541,41 @@ describe("scrapePDFWithFirePDFAsync", () => {expect(err).toBeInstanceOf(FirePdfAsyncFailure);expect(err.reason).toBe("terminal_expired");expect(fallback).not.toHaveBeenCalled();+ expect(calls.map(call => call.method)).toEqual(["POST", "GET"]);+ });++ it("does not cancel a job already reported as terminal cancelled", async () => {+ const { fetchImpl, calls } = makeFetchFromSequence([+ {+ matchUrl: /\/jobs$/,+ matchMethod: "POST",+ response: {+ status: 202,+ body: { scrape_id: "x", status: "queued", lane: "fast" },+ },+ },+ {+ matchUrl: /\/jobs\/scrape-id-test$/,+ matchMethod: "GET",+ response: {+ status: 410,+ body: { scrape_id: "x", status: "cancelled" },+ },+ },+ ]);++ const err = await scrapePDFWithFirePDFAsync(+ makeMeta(),+ "BASE64",+ undefined,+ undefined,+ undefined,+ { fetchImpl, fallbackImpl: vi.fn(), sleepImpl: noopSleep },+ ).catch(error => error);++ expect(err).toBeInstanceOf(FirePdfAsyncFailure);+ expect(err.reason).toBe("terminal_cancelled");+ expect(calls.map(call => call.method)).toEqual(["POST", "GET"]);});it("throws FirePdfAsyncFailure when polling exceeds deadline + buffer", async () => {@@ -385,6 +592,7 @@ describe("scrapePDFWithFirePDFAsync", () => {body: {scrape_id: "x",status: "queued",+ lane: "fast",retry_after_ms: 1000,},},@@ -398,13 +606,13 @@ describe("scrapePDFWithFirePDFAsync", () => {]);const fallback = vi.fn();- // 5s scrape budget β deadline 5s, polling deadline = submit + 5s + 30s = 35s.+ // 15s scrape budget β polling deadline = submit + 15s + 30s = 45s.// 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(() => 5_000),+ scrapeTimeout: vi.fn(() => 15_000),},});@@ -433,7 +641,7 @@ describe("scrapePDFWithFirePDFAsync", () => {matchUrl: /\/jobs$/,response: {status: 202,- body: { scrape_id: "x", status: "queued" },+ body: { scrape_id: "x", status: "queued", lane: "fast" },},},{@@ -471,7 +679,7 @@ describe("scrapePDFWithFirePDFAsync", () => {matchMethod: "POST",response: {status: 202,- body: { scrape_id: "x", status: "queued" },+ body: { scrape_id: "x", status: "queued", lane: "fast" },},},{@@ -519,7 +727,7 @@ describe("scrapePDFWithFirePDFAsync", () => {submittedBody = JSON.parse(init.body as string);return jsonResp({status: 202,- body: { scrape_id: "x", status: "queued" },+ body: { scrape_id: "x", status: "queued", lane: "fast" },});}if (/\/jobs\/scrape-id-test$/.test(url)) {diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncRouting.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncRouting.test.tsnew file mode 100644index 000000000..9a24b0627--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/firePDFAsyncRouting.test.ts@@ -0,0 +1,112 @@+import { config } from "../../../../../config";+import {+ decideFirePdfAsyncRoute,+ deterministicPercentage,+ FIRE_PDF_ASYNC_MIN_REMAINING_MS,+} from "../fire-pdf/routing";+import {+ computeDeadlineMs,+ firePdfHeaders,+ nextPollDelay,+} from "../fire-pdf/utils";++const baseInput = {+ scrapeId: "scrape-1",+ teamId: "team-1",+ zeroDataRetention: false,+ remainingMs: 60_000,+ requestOptIn: false,+ percentage: 0,+ allowRequestOverride: false,+};++describe("FirePDF async routing", () => {+ it("is traffic-neutral by default", () => {+ expect(decideFirePdfAsyncRoute(baseInput)).toEqual({+ enabled: false,+ reason: "percentage_disabled",+ });+ });++ it("never routes ZDR or short-deadline work", () => {+ expect(+ decideFirePdfAsyncRoute({+ ...baseInput,+ zeroDataRetention: true,+ forceTeamIds: "team-1",+ }),+ ).toEqual({ enabled: false, reason: "zdr" });+ expect(+ decideFirePdfAsyncRoute({+ ...baseInput,+ remainingMs: FIRE_PDF_ASYNC_MIN_REMAINING_MS - 1,+ forceTeamIds: "team-1",+ }),+ ).toEqual({ enabled: false, reason: "deadline_too_close" });+ });++ it("lets a denylist override a forced team", () => {+ expect(+ decideFirePdfAsyncRoute({+ ...baseInput,+ forceTeamIds: "team-1",+ disableTeamIds: "team-1",+ }),+ ).toEqual({ enabled: false, reason: "team_disabled" });+ });++ it("supports team canaries and a separately gated request override", () => {+ expect(+ decideFirePdfAsyncRoute({ ...baseInput, forceTeamIds: " team-1 " }),+ ).toEqual({ enabled: true, reason: "team_forced" });+ expect(+ decideFirePdfAsyncRoute({ ...baseInput, requestOptIn: true }),+ ).toEqual({ enabled: false, reason: "percentage_disabled" });+ expect(+ decideFirePdfAsyncRoute({+ ...baseInput,+ requestOptIn: true,+ allowRequestOverride: true,+ }),+ ).toEqual({ enabled: true, reason: "request_override" });+ });++ it("uses a stable request-level percentage cohort", () => {+ expect(deterministicPercentage("same-id")).toBe(+ deterministicPercentage("same-id"),+ );+ expect(decideFirePdfAsyncRoute({ ...baseInput, percentage: 100 })).toEqual({+ enabled: true,+ reason: "percentage",+ });+ });+});++describe("FirePDF async transport helpers", () => {+ it("uses the server hint as a floor while backing off with jitter", () => {+ expect(nextPollDelay(1_000, 4_500, () => 0)).toBe(4_500);+ expect(nextPollDelay(2_000, 1_000, () => 0)).toBe(4_000);+ expect(nextPollDelay(1_000, undefined, () => 0.5)).toBe(2_200);+ expect(nextPollDelay(4_000, undefined, () => 1)).toBe(5_000);+ });++ it("does not inflate a caller deadline", () => {+ expect(computeDeadlineMs(4_000)).toBe(4_000);+ });++ it("adds the shared FirePDF bearer credential when configured", () => {+ const mutableConfig = config as typeof config & {+ FIRE_PDF_API_KEY?: string;+ };+ const original = config.FIRE_PDF_API_KEY;+ try {+ mutableConfig.FIRE_PDF_API_KEY = "shared-secret";+ expect(firePdfHeaders(true)).toEqual({+ "Content-Type": "application/json",+ Authorization: "Bearer shared-secret",+ });+ } finally {+ mutableConfig.FIRE_PDF_API_KEY = original;+ }+ });+});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 7c4f6c0b9..cbe06c1e4 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@@ -1,25 +1,33 @@-import { Meta } from "../../..";+import type { Meta } from "../../..";+import type { PDFMode } from "../../../../../controllers/v2/types";import { config } from "../../../../../config";import { fetch as undiciFetch } from "undici";import type { PDFProcessorResult } from "../types";-import type { PDFMode } from "../../../../../controllers/v2/types";import { safeMarkdownToHtml } from "../markdownToHtml";import { scrapePDFWithFirePDF } from "../firePDF";-import { firePdfAsyncTotalDurationSeconds } from "./metrics";-import { POLL_FLOOR_MS, POLL_TIMEOUT_BUFFER_MS } from "./schema";-import { defaultSleep, computeDeadlineMs } from "./utils";+import { cancelJob } from "./cancel";import { tryGetCached, maybeSaveResult } from "./cache";-import { submitJob } from "./submit";+import { firePdfAsyncTotalDurationSeconds } from "./metrics";import { pollUntilTerminal } from "./poll";import { fetchResult } from "./result";+import { FIRE_PDF_ASYNC_MIN_REMAINING_MS } from "./routing";+import { POLL_FLOOR_MS, POLL_TIMEOUT_BUFFER_MS } from "./schema";+import { submitJob, SubmitJobMayHaveBeenAcceptedError } from "./submit";+import {+ computeDeadlineMs,+ defaultSleep,+ failAsync,+ FirePdfAsyncFailure,+} from "./utils";-export { FirePdfAsyncFailure } from "./utils";+export { FirePdfAsyncFailure };type FirePdfAsyncDeps = {fetchImpl?: typeof undiciFetch;fallbackImpl?: typeof scrapePDFWithFirePDF;sleepImpl?: (ms: number, signal?: AbortSignal) => Promise<void>;nowImpl?: () => number;+ randomImpl?: () => number;};export async function scrapePDFWithFirePDFAsync(@@ -34,6 +42,13 @@ export async function scrapePDFWithFirePDFAsync(const fallbackImpl = deps.fallbackImpl ?? scrapePDFWithFirePDF;const sleep = deps.sleepImpl ?? defaultSleep;const now = deps.nowImpl ?? Date.now;+ const random = deps.randomImpl ?? Math.random;++ // Async persists inputs and queue state, so ZDR is excluded until that+ // lifecycle has an explicit delete-on-completion contract.+ if (meta.internalOptions.zeroDataRetention) {+ return fallbackImpl(meta, base64Content, maxPages, pagesProcessed, mode);+ }const cached = await tryGetCached(meta,@@ -46,6 +61,14 @@ export async function scrapePDFWithFirePDFAsync(meta.abort.throwIfAborted();+ const remainingMs = meta.abort.scrapeTimeout();+ if (+ remainingMs !== undefined &&+ remainingMs < FIRE_PDF_ASYNC_MIN_REMAINING_MS+ ) {+ failAsync(meta, "deadline_too_close", { remainingMs });+ }+const baseUrl = config.FIRE_PDF_BASE_URL;if (!baseUrl) {// Should be unreachable β call site checks this β but fall back rather@@ -55,47 +78,73 @@ export async function scrapePDFWithFirePDFAsync(const overallStartedAt = now();const submitTime = now();- const deadlineFromNow = computeDeadlineMs(meta.abort.scrapeTimeout());+ const deadlineFromNow = computeDeadlineMs(remainingMs);const deadlineAt = new Date(submitTime + deadlineFromNow).toISOString();const pollingDeadline = submitTime + deadlineFromNow + POLL_TIMEOUT_BUFFER_MS;// ββ Step 1: POST /jobs ββββββββββββββββββββββββββββββββββββββββββββββββ- const submit = await submitJob({- meta,- baseUrl,- base64Content,- maxPages,- pagesProcessed,- mode,- deadlineAt,- fetchImpl,- });+ let submissionAccepted = false;+ let terminalReached = false;+ let polled: Awaited<ReturnType<typeof pollUntilTerminal>>;+ let fetched: Awaited<ReturnType<typeof fetchResult>>;+ try {+ const submit = await submitJob({+ meta,+ baseUrl,+ base64Content,+ maxPages,+ pagesProcessed,+ mode,+ deadlineAt,+ fetchImpl,+ });+ submissionAccepted = true;+ terminalReached = submit.alreadyDone;- // ββ Step 2: poll until terminal (skip on idempotent-replay done) ββββββ- const polled = submit.alreadyDone- ? {- poll: { scrape_id: meta.id, status: "done" as const },- pollCount: 0,- }- : await pollUntilTerminal({- baseUrl,- scrapeId: meta.id,- initialDelay: submit.retryAfterMs ?? POLL_FLOOR_MS,- pollingDeadline,- meta,- fetchImpl,- sleep,- now,- });-- // ββ Step 3: GET /jobs/:id/result ββββββββββββββββββββββββββββββββββββββ- const fetched = await fetchResult({- baseUrl,- scrapeId: meta.id,- meta,- fetchImpl,- sleep,- });+ // ββ Step 2: poll until terminal (skip on idempotent-replay done) ββββββ+ polled = submit.alreadyDone+ ? {+ poll: { scrape_id: meta.id, status: "done" as const },+ pollCount: 0,+ }+ : await pollUntilTerminal({+ baseUrl,+ scrapeId: meta.id,+ initialDelay: submit.retryAfterMs ?? POLL_FLOOR_MS,+ pollingDeadline,+ meta,+ fetchImpl,+ sleep,+ now,+ random,+ });+ terminalReached = true;++ // ββ Step 3: GET /jobs/:id/result ββββββββββββββββββββββββββββββββββββ+ fetched = await fetchResult({+ baseUrl,+ scrapeId: meta.id,+ meta,+ fetchImpl,+ sleep,+ });+ } catch (error) {+ const submitMayHaveBeenAccepted =+ error instanceof SubmitJobMayHaveBeenAcceptedError;+ const jobAlreadyTerminal =+ error instanceof FirePdfAsyncFailure &&+ (error.reason === "terminal_failed" ||+ error.reason === "terminal_expired" ||+ error.reason === "terminal_cancelled");+ if (+ (submissionAccepted || submitMayHaveBeenAccepted) &&+ !terminalReached &&+ !jobAlreadyTerminal+ ) {+ await cancelJob({ baseUrl, scrapeId: meta.id, meta, fetchImpl });+ }+ throw submitMayHaveBeenAccepted ? error.originalError : error;+ }// ββ Assemble + cache save βββββββββββββββββββββββββββββββββββββββββββββconst pages =diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cache.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cache.tsindex 4a49f2c88..c53dd93ab 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cache.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cache.ts@@ -10,7 +10,10 @@ import {// entries. `fast` mode bypasses entirely (hard cost ceiling β must fail on// scanned PDFs, not serve a cached OCR result), as does any call with// `maxPages` (the cached entry may have been written with a different cap).-function cacheKeyShape(mode: PDFMode | undefined, maxPages: number | undefined) {+function cacheKeyShape(+ mode: PDFMode | undefined,+ maxPages: number | undefined,+) {const cacheable = mode !== "fast" && !maxPages;const ownVariant: string | undefined = mode === "ocr" ? "ocr" : undefined;const lookupVariants: (string | undefined)[] =@@ -25,6 +28,7 @@ export async function tryGetCached(maxPages: number | undefined,pagesProcessed: number | undefined,): Promise<PDFProcessorResult | null> {+ if (meta.internalOptions.zeroDataRetention) return null;const { cacheable, lookupVariants } = cacheKeyShape(mode, maxPages);if (!cacheable) return null;@@ -64,6 +68,7 @@ export async function maybeSaveResult(args: {result: PDFProcessorResult & { markdown: string };}): Promise<void> {const { meta, base64Content, mode, maxPages, result } = args;+ if (meta.internalOptions.zeroDataRetention) return;const { cacheable, ownVariant } = cacheKeyShape(mode, maxPages);if (!cacheable) return;diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cancel.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cancel.tsnew file mode 100644index 000000000..b4e469591--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/cancel.ts@@ -0,0 +1,37 @@+import type { Meta } from "../../..";+import { fetch as undiciFetch } from "undici";+import { firePdfHeaders } from "./utils";++type CancelJobArgs = {+ baseUrl: string;+ scrapeId: string;+ meta: Meta;+ fetchImpl: typeof undiciFetch;+};++const CANCEL_TIMEOUT_MS = 2_000;++/** Best-effort cleanup after Firecrawl abandons an accepted async job. */+export async function cancelJob(args: CancelJobArgs): Promise<void> {+ const { baseUrl, scrapeId, meta, fetchImpl } = args;+ try {+ const response = await fetchImpl(`${baseUrl}/jobs/${scrapeId}`, {+ method: "DELETE",+ headers: firePdfHeaders(),+ // Do not reuse the caller's signal: it is often already aborted.+ signal: AbortSignal.timeout(CANCEL_TIMEOUT_MS),+ });+ await response.body?.cancel();+ if (response.status !== 200 && response.status !== 404) {+ meta.logger.warn("FirePDF async cancellation was not accepted", {+ scrapeId,+ status: response.status,+ });+ }+ } catch (error) {+ meta.logger.warn("FirePDF async cancellation failed", {+ scrapeId,+ error: String(error),+ });+ }+}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 73ae7eb35..410e05ee8 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@@ -14,7 +14,7 @@ export const firePdfAsyncCompletedTotal = new Counter({export const firePdfAsyncFallbackTotal = new Counter({name: "firecrawl_fire_pdf_async_fallback_total",- help: "Count of fire-pdf async requests that fell back to the sync /ocr path",+ help: "Count of requests that left fire-pdf async processing",labelNames: ["reason"],});@@ -31,12 +31,16 @@ export const firePdfAsyncPollCount = new Histogram({});export type FallbackReason =+ | "http_401"| "http_404"+ | "http_410"| "http_413"+ | "http_502"| "http_503"| "http_429"| "http_5xx"| "network_error"+ | "deadline_too_close"| "terminal_failed"| "terminal_expired"| "terminal_cancelled"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 e2592792c..d3745136c 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,7 @@ import {TERMINAL_STATUSES,type PollResponse,} from "./schema";-import { failAsync, nextPollDelay } from "./utils";+import { failAsync, firePdfHeaders, nextPollDelay } from "./utils";type PollDeps = {baseUrl: string;@@ -22,22 +22,17 @@ type PollDeps = {fetchImpl: typeof undiciFetch;sleep: (ms: number, signal?: AbortSignal) => Promise<void>;now: () => number;+ random?: () => number;};type PollOk = { poll: PollResponse; pollCount: number };export async function pollUntilTerminal(deps: PollDeps): Promise<PollOk> {- const {- baseUrl,- scrapeId,- pollingDeadline,- meta,- fetchImpl,- sleep,- now,- } = deps;+ const { baseUrl, scrapeId, pollingDeadline, meta, fetchImpl, sleep, now } =+ deps;let pollCount = 0;- let lastDelay = deps.initialDelay;+ const random = deps.random ?? Math.random;+ let lastDelay = nextPollDelay(0, deps.initialDelay, random);while (true) {if (now() > pollingDeadline) {@@ -53,6 +48,7 @@ export async function pollUntilTerminal(deps: PollDeps): Promise<PollOk> {try {pollResp = await fetchImpl(`${baseUrl}/jobs/${scrapeId}`, {method: "GET",+ headers: firePdfHeaders(),signal: meta.abort.asSignal(),});} catch (error) {@@ -67,6 +63,11 @@ export async function pollUntilTerminal(deps: PollDeps): Promise<PollOk> {const pollStatus = pollResp.status;const pollBody = await pollResp.json().catch(() => ({}));+ if (pollStatus === 401) {+ firePdfAsyncPollCount.observe(pollCount);+ failAsync(meta, "http_401", { pollCount });+ }+if (pollStatus === 404) {firePdfAsyncPollCount.observe(pollCount);throw new Error(@@ -134,6 +135,6 @@ export async function pollUntilTerminal(deps: PollDeps): Promise<PollOk> {return { poll: parsed.data, pollCount };}- lastDelay = nextPollDelay(lastDelay, parsed.data.retry_after_ms);+ lastDelay = nextPollDelay(lastDelay, parsed.data.retry_after_ms, random);}}diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/result.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/result.tsindex 09a11a8c3..e98b6300c 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/result.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/result.ts@@ -6,7 +6,7 @@ import {resultResponseSchema,type ResultResponse,} from "./schema";-import { failAsync } from "./utils";+import { failAsync, firePdfHeaders } from "./utils";type ResultDeps = {baseUrl: string;@@ -25,6 +25,7 @@ export async function fetchResult(deps: ResultDeps): Promise<ResultResponse> {try {resp = await fetchImpl(`${baseUrl}/jobs/${scrapeId}/result`, {method: "GET",+ headers: firePdfHeaders(),signal: meta.abort.asSignal(),});} catch (error) {@@ -35,6 +36,10 @@ export async function fetchResult(deps: ResultDeps): Promise<ResultResponse> {const status = resp.status;const body = await resp.json().catch(() => ({}));+ if (status === 401) {+ failAsync(meta, "http_401");+ }+if (status === 503) {failAsync(meta, "result_503", { body });}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.tsnew file mode 100644index 000000000..b4ffd5342--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/fire-pdf/routing.ts@@ -0,0 +1,79 @@+import { createHash } from "node:crypto";+import { MIN_DEADLINE_MS } from "./schema";++export const FIRE_PDF_ASYNC_MIN_REMAINING_MS = MIN_DEADLINE_MS + 10_000;++type FirePdfAsyncRouteReason =+ | "zdr"+ | "deadline_too_close"+ | "team_disabled"+ | "team_forced"+ | "request_override"+ | "percentage"+ | "percentage_disabled"+ | "outside_percentage";++type FirePdfAsyncRouteDecision = {+ enabled: boolean;+ reason: FirePdfAsyncRouteReason;+};++type FirePdfAsyncRouteInput = {+ scrapeId: string;+ teamId?: string;+ zeroDataRetention: boolean;+ remainingMs?: number;+ requestOptIn: boolean;+ percentage: number;+ forceTeamIds?: string;+ disableTeamIds?: string;+ allowRequestOverride: boolean;+};++function parseTeamIds(value: string | undefined): Set<string> {+ return new Set(+ (value ?? "")+ .split(",")+ .map(id => id.trim())+ .filter(Boolean),+ );+}++export function deterministicPercentage(key: string): number {+ const prefix = createHash("sha256").update(key).digest().readUInt32BE(0);+ return (prefix / 2 ** 32) * 100;+}++export function decideFirePdfAsyncRoute(+ input: FirePdfAsyncRouteInput,+): FirePdfAsyncRouteDecision {+ if (input.zeroDataRetention) return { enabled: false, reason: "zdr" };+ if (+ input.remainingMs !== undefined &&+ input.remainingMs < FIRE_PDF_ASYNC_MIN_REMAINING_MS+ ) {+ return { enabled: false, reason: "deadline_too_close" };+ }++ const disabledTeams = parseTeamIds(input.disableTeamIds);+ if (input.teamId && disabledTeams.has(input.teamId)) {+ return { enabled: false, reason: "team_disabled" };+ }++ const forcedTeams = parseTeamIds(input.forceTeamIds);+ if (input.teamId && forcedTeams.has(input.teamId)) {+ return { enabled: true, reason: "team_forced" };+ }++ if (input.requestOptIn && input.allowRequestOverride) {+ return { enabled: true, reason: "request_override" };+ }++ if (input.percentage <= 0) {+ return { enabled: false, reason: "percentage_disabled" };+ }+ if (deterministicPercentage(input.scrapeId) < input.percentage) {+ return { enabled: true, reason: "percentage" };+ }+ return { enabled: false, reason: "outside_percentage" };+}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 9d19f1056..d99b8f1fe 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@@ -21,7 +21,10 @@ export const TERMINAL_STATUSES = new Set([export const submitResponseSchema = z.object({scrape_id: z.string(),status: z.enum(["queued", "published", "running", "done"]),- lane: z.string().optional(),+ lane: z+ .enum(["fast", "standard", "heavy", "xl", "unknown"])+ .optional()+ .default("unknown"),retry_after_ms: z.number().optional(),});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 220b6d769..e348889df 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@@ -4,7 +4,7 @@ import { fetch as undiciFetch } from "undici";import { AbortManagerThrownError } from "../../../lib/abortManager";import { firePdfAsyncSubmittedTotal } from "./metrics";import { submitResponseSchema } from "./schema";-import { failAsync } from "./utils";+import { failAsync, firePdfHeaders } from "./utils";type SubmitOutcome = {lane: string | undefined;@@ -23,6 +23,30 @@ type SubmitArgs = {fetchImpl: typeof undiciFetch;};+/**+ * The submit request may have reached FirePDF even though Firecrawl could not+ * observe a valid success response. The caller should best-effort DELETE the+ * idempotent scrape_id before falling back, then rethrow `originalError`.+ */+export class SubmitJobMayHaveBeenAcceptedError extends Error {+ constructor(public readonly originalError: unknown) {+ super("FirePDF submit may have been accepted");+ this.name = "SubmitJobMayHaveBeenAcceptedError";+ }+}++function failPossiblyAccepted(+ meta: Meta,+ reason: Parameters<typeof failAsync>[1],+ extra: Record<string, unknown> = {},+): never {+ try {+ failAsync(meta, reason, extra);+ } catch (error) {+ throw new SubmitJobMayHaveBeenAcceptedError(error);+ }+}+export async function submitJob(args: SubmitArgs): Promise<SubmitOutcome> {const {meta,@@ -60,37 +84,48 @@ export async function submitJob(args: SubmitArgs): Promise<SubmitOutcome> {try {const resp = await fetchImpl(`${baseUrl}/jobs`, {method: "POST",- headers: { "Content-Type": "application/json" },+ 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 error;- failAsync(meta, "network_error", { error: String(error) });+ if (error instanceof AbortManagerThrownError) {+ throw new SubmitJobMayHaveBeenAcceptedError(error);+ }+ failPossiblyAccepted(meta, "network_error", { error: String(error) });}+ if (status === 401) failAsync(meta, "http_401");if (status === 404) failAsync(meta, "http_404");+ if (status === 410) failAsync(meta, "http_410", { body: json });if (status === 413) failAsync(meta, "http_413");if (status === 429) failAsync(meta, "http_429");+ if (status === 502) failAsync(meta, "http_502", { body: json });if (status === 503) failAsync(meta, "http_503");if (status === 409) {- meta.logger.error("FirePDF async POST /jobs returned 409 scrape_id_conflict", {- scrapeId,- body: json,- });+ meta.logger.error(+ "FirePDF async POST /jobs returned 409 scrape_id_conflict",+ {+ scrapeId,+ body: json,+ },+ );throw new Error("fire-pdf async POST /jobs conflict: scrape_id reused with different inputs",);}if (status === 400) {- meta.logger.error("FirePDF async POST /jobs returned 400 validation error", {- scrapeId,- body: json,- });+ meta.logger.error(+ "FirePDF async POST /jobs returned 400 validation error",+ {+ scrapeId,+ body: json,+ },+ );throw new Error("fire-pdf async POST /jobs validation error");}@@ -100,7 +135,10 @@ export async function submitJob(args: SubmitArgs): Promise<SubmitOutcome> {const parsed = submitResponseSchema.safeParse(json);if (!parsed.success) {- failAsync(meta, "http_5xx", {+ // A 2xx response means the server accepted this scrape_id even when the+ // response body is incompatible. Mark it cancellation-worthy before+ // surfacing the existing fallback reason.+ failPossiblyAccepted(meta, "http_5xx", {error: String(parsed.error),body: json,status,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 f263c35d8..594856a1b 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,19 +1,9 @@import type { Meta } from "../../..";-import {- MIN_DEADLINE_MS,- MAX_DEADLINE_MS,- POLL_FLOOR_MS,- POLL_CAP_MS,-} from "./schema";-import {- firePdfAsyncFallbackTotal,- type FallbackReason,-} from "./metrics";+import { config } from "../../../../../config";+import { MAX_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> {+export function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {return new Promise((resolve, reject) => {const handle = setTimeout(() => {signal?.removeEventListener("abort", onAbort);@@ -29,9 +19,7 @@ export function defaultSleep(if (signal.aborted) {clearTimeout(handle);reject(- signal.reason instanceof Error- ? signal.reason- : new Error("Aborted"),+ signal.reason instanceof Error ? signal.reason : new Error("Aborted"),);return;}@@ -43,17 +31,29 @@ export function defaultSleep(export function nextPollDelay(prev: number,retryAfterMs: number | undefined,+ random: () => number = Math.random,): number {- const candidate = retryAfterMs ?? Math.max(prev * 2, POLL_FLOOR_MS);- return Math.min(POLL_CAP_MS, Math.max(POLL_FLOOR_MS, candidate));+ const candidate = Math.max(prev * 2, retryAfterMs ?? 0, POLL_FLOOR_MS);+ const jittered = Math.round(candidate * (1 + random() * 0.2));+ return Math.min(POLL_CAP_MS, jittered);}export function computeDeadlineMs(scrapeTimeoutMs: number | undefined): number {- // 5min default when there's no scrape budget (CLI/tests). Anything outside- // [5s, 30min] is clamped to satisfy the /jobs contract.+ // 5min default when there's no scrape budget (CLI/tests). Routing rejects+ // budgets that are too short; only cap the upper bound here so we never+ // advertise more time to FirePDF than the caller actually has.const fallback = 5 * 60 * 1_000;const candidate = scrapeTimeoutMs ?? fallback;- return Math.min(MAX_DEADLINE_MS, Math.max(MIN_DEADLINE_MS, candidate));+ return Math.min(MAX_DEADLINE_MS, candidate);+}++export function firePdfHeaders(includeJson = false): Record<string, string> {+ return {+ ...(includeJson && { "Content-Type": "application/json" }),+ ...(config.FIRE_PDF_API_KEY && {+ Authorization: `Bearer ${config.FIRE_PDF_API_KEY}`,+ }),+ };}export class FirePdfAsyncFailure extends Error {diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/index.tsindex dec5be080..4ebf2bbfe 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts@@ -37,6 +37,7 @@ import { withSpan, setSpanAttributes } from "../../../../lib/otel-tracer";import { scrapePDFWithRunPodMU } from "./runpodMU";import { reconcilePageCountWithFirePdf, scrapePDFWithFirePDF } from "./firePDF";import { scrapePDFWithFirePDFAsync } from "./fire-pdf/async";+import { decideFirePdfAsyncRoute } from "./fire-pdf/routing";import { scrapePDFWithParsePDF } from "./pdfParse";import { captureExceptionWithZdrCheck } from "../../../../services/sentry";import { isPdfBuffer, PDF_SNIFF_WINDOW } from "./pdfUtils";@@ -409,10 +410,30 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {Math.random() * 100 < config.FIRE_PDF_PERCENT);if (useFirePDF) {- // Per-request opt-in to async fire-pdf pipeline. Async client falls- // back to sync on any failure, so behaviour stays bounded by the- // sync path.- const useAsync = getFirePdfAsync(meta.options.parsers);+ // Async is a server-controlled cohort within traffic already selected+ // for FirePDF. ZDR and short-deadline requests are always kept out.+ const asyncDecision = decideFirePdfAsyncRoute({+ scrapeId: meta.id,+ teamId: meta.internalOptions.teamId,+ zeroDataRetention: meta.internalOptions.zeroDataRetention ?? false,+ remainingMs: meta.abort.scrapeTimeout(),+ requestOptIn: getFirePdfAsync(meta.options.parsers),+ percentage: config.FIRE_PDF_ASYNC_PERCENT,+ forceTeamIds: config.FIRE_PDF_ASYNC_FORCE_TEAM_IDS,+ disableTeamIds: config.FIRE_PDF_ASYNC_DISABLE_TEAM_IDS,+ allowRequestOverride: config.FIRE_PDF_ASYNC_ALLOW_REQUEST_OVERRIDE,+ });+ const useAsync = asyncDecision.enabled;+ if (useAsync) {+ meta.logger.info("Routing FirePDF request to async jobs", {+ method: "scrapePDF",+ event: "fire_pdf_async_routed",+ reason: asyncDecision.reason,+ percentage: config.FIRE_PDF_ASYNC_PERCENT,+ scrape_id: meta.id,+ team_id: meta.internalOptions.teamId,+ });+ }try {result = await (useAsync ? scrapePDFWithFirePDFAsync : scrapePDFWithFirePDF