Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(api): bound the pdf-parse page walk (#5494)

Abimael Martell63a5ff35ca65
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts
index 138218220..0145efc85 100644
--- a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts
@@ -62,6 +62,7 @@ import {
} from "./fire-pdf/routing";
import { parseAlwaysFirePdf } from "./fire-pdf/request-metadata";
import { scrapePDFWithParsePDF } from "./pdfParse";
+import { reconcilePageCountWithPdfParse } from "./pageCount";
import { toPublicBlocks } from "./blocks";
import { isPdfBuffer, PDF_SNIFF_WINDOW } from "./pdfUtils";
import { comparePdfOutputs } from "./shadowComparison";
@@ -938,7 +939,20 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {
}),
},
tempFilePath,
+ maxPages ?? undefined,
);
+ // pdf-parse stops at its page cap, so a count from native detection
+ // can only come down to the pages it parsed. A failed detection stays
+ // at 0 and keeps billing the base credit.
+ effectivePageCount = reconcilePageCountWithPdfParse(
+ effectivePageCount,
+ result,
+ );
+ // When native detection could not read the page count, use the count
+ // pdf-parse saw so a truncated result still reports its total.
+ if (totalPageCount === undefined && result.pageCount !== undefined) {
+ totalPageCount = result.pageCount;
+ }
}
return {
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.test.ts
new file mode 100644
index 000000000..a8c7005fe
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.test.ts
@@ -0,0 +1,32 @@
+import { reconcilePageCountWithPdfParse } from "./pageCount";
+
+describe("reconcilePageCountWithPdfParse", () => {
+ it("keeps a failed native detection at 0, so billing stays at the base credit", () => {
+ expect(reconcilePageCountWithPdfParse(0, { pagesProcessed: 1000 })).toBe(0);
+ });
+
+ it("lowers a native count that pdf-parse truncated at its cap", () => {
+ expect(reconcilePageCountWithPdfParse(5000, { pagesProcessed: 1000 })).toBe(
+ 1000,
+ );
+ });
+
+ it("keeps a native count within the cap", () => {
+ expect(reconcilePageCountWithPdfParse(300, { pagesProcessed: 300 })).toBe(
+ 300,
+ );
+ expect(reconcilePageCountWithPdfParse(7, { pagesProcessed: 10 })).toBe(7);
+ });
+
+ it("never raises the count", () => {
+ expect(reconcilePageCountWithPdfParse(0, { pagesProcessed: 3 })).toBe(0);
+ expect(reconcilePageCountWithPdfParse(2, { pagesProcessed: 9 })).toBe(2);
+ });
+
+ it("leaves the count alone when pdf-parse reports nothing", () => {
+ expect(
+ reconcilePageCountWithPdfParse(7, { pagesProcessed: undefined }),
+ ).toBe(7);
+ expect(reconcilePageCountWithPdfParse(7, null)).toBe(7);
+ });
+});
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.ts
new file mode 100644
index 000000000..73b9c53d8
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/pageCount.ts
@@ -0,0 +1,17 @@
+/**
+ * Page count to report after the pdf-parse fallback. pdf-parse stops at its
+ * page cap, so a count from native detection can only come down to the pages
+ * it parsed. A count of 0 (native detection failed) stays 0: that path has
+ * always billed the base credit only, and a parser cap must not raise prices.
+ *
+ * Lives in its own module so tests that mock the pdf-parse module keep the
+ * real reconciliation. Pure and synchronous so it is unit-testable on its own.
+ */
+export function reconcilePageCountWithPdfParse(
+ current: number,
+ pdfParseResult: { pagesProcessed?: number } | null | undefined,
+): number {
+ const parsed = pdfParseResult?.pagesProcessed;
+ if (parsed === undefined || current <= 0) return current;
+ return Math.min(current, parsed);
+}
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.test.ts
new file mode 100644
index 000000000..cca8bbc19
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.test.ts
@@ -0,0 +1,83 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const mocks = vi.hoisted(() => ({
+ pdfParse: vi.fn(),
+}));
+
+vi.mock("pdf-parse", () => ({ default: mocks.pdfParse }));
+
+import { PDF_PARSE_MAX_PAGES, scrapePDFWithParsePDF } from "./pdfParse";
+
+function meta(): any {
+ return {
+ logger: { debug: vi.fn(), info: vi.fn(), error: vi.fn() },
+ };
+}
+
+let dir: string;
+let filePath: string;
+
+beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), "pdf-parse-test-"));
+ filePath = join(dir, "doc.pdf");
+ await writeFile(filePath, "%PDF-1.4\n");
+});
+
+afterAll(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+beforeEach(() => {
+ mocks.pdfParse.mockReset();
+ mocks.pdfParse.mockResolvedValue({ text: "hello", numpages: 3 });
+});
+
+describe("scrapePDFWithParsePDF", () => {
+ it("passes the request's maxPages to pdf-parse", async () => {
+ const result = await scrapePDFWithParsePDF(meta(), filePath, 7);
+
+ expect(result.markdown).toBe("hello");
+ expect(result.pagesProcessed).toBe(3);
+ expect(result.pageCount).toBe(3);
+ expect(mocks.pdfParse).toHaveBeenCalledTimes(1);
+ expect(mocks.pdfParse.mock.calls[0][1]).toEqual({ max: 7 });
+ });
+
+ it("caps the page walk when the request sets no maxPages", async () => {
+ await scrapePDFWithParsePDF(meta(), filePath);
+
+ expect(mocks.pdfParse.mock.calls[0][1]).toEqual({
+ max: PDF_PARSE_MAX_PAGES,
+ });
+ });
+
+ it("logs when the declared page count exceeds the cap", async () => {
+ mocks.pdfParse.mockResolvedValue({ text: "x", numpages: 5_000_000 });
+ const m = meta();
+
+ const result = await scrapePDFWithParsePDF(m, filePath, 10);
+
+ expect(result.pagesProcessed).toBe(10);
+ expect(result.pageCount).toBe(5_000_000);
+ expect(m.logger.info).toHaveBeenCalledWith(
+ "pdfParse succeeded",
+ expect.objectContaining({ numPages: 5_000_000, truncatedToPages: 10 }),
+ );
+ });
+
+ it("does not report a truncation when the declared count fits the cap", async () => {
+ mocks.pdfParse.mockResolvedValue({ text: "x", numpages: 3 });
+ const m = meta();
+
+ const result = await scrapePDFWithParsePDF(m, filePath, 10);
+
+ expect(result.pagesProcessed).toBe(3);
+ expect(result.pageCount).toBe(3);
+ expect(m.logger.info).toHaveBeenCalledWith(
+ "pdfParse succeeded",
+ expect.not.objectContaining({ truncatedToPages: expect.anything() }),
+ );
+ });
+});
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.ts
index e07324735..d0da64298 100644
--- a/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/pdfParse.ts
@@ -4,11 +4,20 @@ import PdfParse from "pdf-parse";
import { readFile } from "node:fs/promises";
import type { PDFProcessorResult } from "./types";
+// pdf-parse walks every page the file declares; a tiny file can declare
+// billions. Cap the walk when the request sets no maxPages of its own.
+export const PDF_PARSE_MAX_PAGES = 1000;
+
export async function scrapePDFWithParsePDF(
meta: Meta,
tempFilePath: string,
+ maxPages?: number,
): Promise<PDFProcessorResult> {
- meta.logger.debug("Processing PDF document with parse-pdf", { tempFilePath });
+ const max = maxPages ?? PDF_PARSE_MAX_PAGES;
+ meta.logger.debug("Processing PDF document with parse-pdf", {
+ tempFilePath,
+ maxPages: max,
+ });
try {
const startedAt = Date.now();
@@ -24,7 +33,7 @@ export async function scrapePDFWithParsePDF(
// which owns its ArrayBuffer. (@types/pdf-parse declares Buffer, but
// pdf.js accepts any Uint8Array.)
const bytes = new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
- const result = await PdfParse(bytes as Buffer);
+ const result = await PdfParse(bytes as Buffer, { max });
const durationMs = Date.now() - startedAt;
const escaped = escapeHtml(result.text);
@@ -32,11 +41,14 @@ export async function scrapePDFWithParsePDF(
durationMs,
markdownLength: escaped.length,
numPages: result.numpages,
+ ...(result.numpages > max ? { truncatedToPages: max } : {}),
});
return {
markdown: escaped,
html: escaped,
+ pagesProcessed: Math.min(result.numpages, max),
+ pageCount: result.numpages,
};
} catch (error) {
meta.logger.error("pdfParse failed", { error });
diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/types.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/types.ts
index 6c6980f32..80601a7a2 100644
--- a/apps/api/src/scraper/scrapeURL/engines/pdf/types.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/types.ts
@@ -48,6 +48,12 @@ export type PDFProcessorResult = {
* and fall back to whatever upstream metadata pass set.
*/
pagesProcessed?: number;
+ /**
+ * Page count the file declares, when the engine reports it. Currently only
+ * pdf-parse does. Used as the document total when native detection could
+ * not determine one.
+ */
+ pageCount?: number;
};
export type PdfMetadata = {