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): bound native PDF extraction concurrency with a semaphore
mogery92e16a2bfb16
diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex d4b399c79..f1b638337 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -273,6 +273,13 @@ const configSchema = z.object({SCRAPE_MAX_FEATURE_REMOVALS: z.coerce.number().int().positive().default(3),SCRAPE_MAX_PDF_PREFETCHES: z.coerce.number().int().positive().default(2),SCRAPE_MAX_DOCUMENT_PREFETCHES: z.coerce.number().int().positive().default(2),+ // Max concurrent native PDF extractions per process. Each extraction holds+ // the (β€50MB) PDF plus its parsed text/markdown in memory on a tokio blocking+ // thread; unbounded concurrency OOM-killed pods when several large PDFs+ // landed on one process at once. 3 keeps the worst-case transient memory+ // (~3 Γ ~0.5GB) well under the 8G limit while being far above typical demand+ // (per-pod average concurrency is ~0.02).+ PDF_EXTRACTION_CONCURRENCY: z.coerce.number().int().positive().default(3),// Search ServicesSEARXNG_ENDPOINT: z.string().optional(),@@ -487,7 +494,12 @@ const configSchema = z.object({// the same question, and trusting a negative for longer than firebill trusts// an answer turns this cache back into the stale allowlist it replaced. 0// disables caching negatives entirely.- FIREBILL_GATEWAY_NEGATIVE_TTL_SECONDS: z.coerce.number().int().min(0).max(300).default(60),+ FIREBILL_GATEWAY_NEGATIVE_TTL_SECONDS: z.coerce+ .number()+ .int()+ .min(0)+ .max(300)+ .default(60),// Sticky percentage ramp, on top of the allowlist above. The bucket is a// hash of the org id, so an org that is in at 5 is still in at 30 β a ramp// only ever adds, and never reshuffles who is on which path mid-rollout.diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/semaphore.test.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/semaphore.test.tsnew file mode 100644index 000000000..95c80efd1--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/__tests__/semaphore.test.ts@@ -0,0 +1,109 @@+import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";++// config.PDF_EXTRACTION_CONCURRENCY drives the semaphore size at module load.+// Pin it to 2 so the test exercises queueing deterministically.+// (Path is relative to this test file: __tests__ -> pdf -> engines ->+// scrapeURL -> scraper -> src.)+vi.mock("../../../../../config", () => ({+ config: { PDF_EXTRACTION_CONCURRENCY: 2 },+}));++import { pdfExtractionSemaphore, withPdfExtractionPermit } from "../semaphore";++describe("pdfExtractionSemaphore", () => {+ beforeEach(() => {+ vi.useRealTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("bounds concurrency to the configured limit and queues the rest", async () => {+ let active = 0;+ let maxActive = 0;+ const started: number[] = [];++ const work = (i: number) =>+ withPdfExtractionPermit(async () => {+ active++;+ maxActive = Math.max(maxActive, active);+ started.push(i);+ await new Promise(r => setTimeout(r, 25));+ active--;+ });++ // 6 concurrent callers on a limit of 2.+ await Promise.all([0, 1, 2, 3, 4, 5].map(work));++ expect(maxActive).toBe(2);+ // FIFO: all six started, in order.+ expect(started).toEqual([0, 1, 2, 3, 4, 5]);+ });++ it("release is idempotent and a throw still frees the permit", async () => {+ const release = await pdfExtractionSemaphore.acquire();+ release();+ release(); // double-release must not free extra permits++ // If double-release leaked a permit, this would deadlock on a limit of 2.+ await expect(+ withPdfExtractionPermit(async () => {+ throw new Error("boom");+ }),+ ).rejects.toThrow("boom");++ // And the semaphore is fully drained for subsequent callers.+ let ran = 0;+ await Promise.all([+ withPdfExtractionPermit(async () => {+ ran++;+ }),+ withPdfExtractionPermit(async () => {+ ran++;+ }),+ withPdfExtractionPermit(async () => {+ ran++;+ }),+ ]);+ expect(ran).toBe(3);+ });++ it("exposes active/waiting gauges and wait-time histogram", async () => {+ const { register } = await import("prom-client");++ // Force queueing: occupy both permits with slow work, then add a third.+ const slow = () =>+ withPdfExtractionPermit(() => new Promise(r => setTimeout(r, 60)));+ const p1 = slow();+ const p2 = slow();+ const p3 = slow();++ // Let the queue form.+ await new Promise(r => setTimeout(r, 10));+ const mid = await register.getSingleMetricAsString(+ "pdf_extraction_semaphore_waiting",+ );+ expect(mid).toContain("pdf_extraction_semaphore_waiting 1");++ await Promise.all([p1, p2, p3]);++ const activeAfter = await register.getSingleMetricAsString(+ "pdf_extraction_semaphore_active",+ );+ expect(activeAfter).toContain("pdf_extraction_semaphore_active 0");+ const waitingAfter = await register.getSingleMetricAsString(+ "pdf_extraction_semaphore_waiting",+ );+ expect(waitingAfter).toContain("pdf_extraction_semaphore_waiting 0");++ // The queued caller paid a real wait; the histogram must have observed it.+ // (Histograms expose *_bucket/*_sum/*_count as derived series, so read the+ // aggregated metrics text rather than a single-metric getter.)+ const allMetrics = await register.metrics();+ const waitCountLine = allMetrics+ .split("\n")+ .find(l => l.startsWith("pdf_extraction_semaphore_wait_seconds_count"));+ expect(waitCountLine).toBeDefined();+ expect(Number(waitCountLine!.split(" ").pop())).toBeGreaterThan(0);+ });+});diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/index.tsindex 2484f784c..798888f1a 100644--- a/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/index.ts@@ -55,6 +55,7 @@ import { toPublicBlocks } from "./blocks";import { captureExceptionWithZdrCheck } from "../../../../services/sentry";import { isPdfBuffer, PDF_SNIFF_WINDOW } from "./pdfUtils";import { comparePdfOutputs } from "./shadowComparison";+import { withPdfExtractionPermit } from "./semaphore";/** Check if the PDF is eligible for Rust extraction, returning a rejection reason or null. */function getIneligibleReason(@@ -260,7 +261,9 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {};const startedAt = Date.now();const detection = await withSpan("native.pdf.detect", async span => {- const result = await detectPdf(tempFilePath, nativeCtx);+ const result = await withPdfExtractionPermit(() =>+ detectPdf(tempFilePath, nativeCtx),+ );setSpanAttributes(span, {"native.module": "pdf","native.pdf_type": result.pdfType,@@ -309,10 +312,8 @@ export async function scrapePDF(meta: Meta): Promise<EngineScrapeResult> {};const startedAt = Date.now();const pdfResult = await withSpan("native.pdf.process", async span => {- const result = await processPdf(- tempFilePath,- maxPages ?? undefined,- nativeCtx,+ const result = await withPdfExtractionPermit(() =>+ processPdf(tempFilePath, maxPages ?? undefined, nativeCtx),);setSpanAttributes(span, {"native.module": "pdf",diff --git a/apps/api/src/scraper/scrapeURL/engines/pdf/semaphore.ts b/apps/api/src/scraper/scrapeURL/engines/pdf/semaphore.tsnew file mode 100644index 000000000..c1f5aa4f5--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/engines/pdf/semaphore.ts@@ -0,0 +1,101 @@+import { Gauge, Histogram } from "prom-client";+import { config } from "../../../../config";++/**+ * In-process semaphore bounding concurrent native PDF extractions+ * (`processPdf` / `detectPdf` via @mendable/firecrawl-rs).+ *+ * Why this exists: those calls run on tokio's blocking thread pool, which is+ * unbounded β under bursty PDF load, a single pod could have many extractions+ * in flight at once, each holding the (β€50MB) PDF plus parsed text/markdown in+ * memory. That piled up and OOM-killed app pods. This semaphore caps+ * per-process concurrency; callers queue for a permit instead of all piling+ * onto the heap at once.+ *+ * Metrics let us watch queue depth and wait time to tune the limit.+ */++const active = new Gauge({+ name: "pdf_extraction_semaphore_active",+ help: "PDF extractions currently holding a permit",+});++const waiting = new Gauge({+ name: "pdf_extraction_semaphore_waiting",+ help: "PDF extractions queued waiting for a permit",+});++const waitSeconds = new Histogram({+ name: "pdf_extraction_semaphore_wait_seconds",+ help: "Time spent queued waiting for a PDF extraction permit",+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],+});++const holdSeconds = new Histogram({+ name: "pdf_extraction_semaphore_hold_seconds",+ help: "Time a PDF extraction permit is held (β extraction duration)",+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120],+});++class PdfExtractionSemaphore {+ private inFlight = 0;+ private readonly queue: { resolve: () => void; enqueuedAt: number }[] = [];++ constructor(private readonly max: number) {}++ /** Acquire a permit; resolves to a release function (call exactly once). */+ acquire(): Promise<() => void> {+ // Fast path: free permit and nobody queued (no barging past waiters).+ if (this.inFlight < this.max && this.queue.length === 0) {+ this.inFlight++;+ active.set(this.inFlight);+ return Promise.resolve(this.makeRelease());+ }++ return new Promise<() => void>(resolve => {+ this.queue.push({+ resolve: () => resolve(this.makeRelease()),+ enqueuedAt: Date.now(),+ });+ waiting.set(this.queue.length);+ });+ }++ private makeRelease(): () => void {+ const acquiredAt = Date.now();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ holdSeconds.observe((Date.now() - acquiredAt) / 1000);++ // Hand the permit directly to the oldest waiter (FIFO), keeping+ // inFlight constant; otherwise free it.+ const next = this.queue.shift();+ if (next) {+ waiting.set(this.queue.length);+ waitSeconds.observe((Date.now() - next.enqueuedAt) / 1000);+ next.resolve();+ } else {+ this.inFlight--;+ active.set(this.inFlight);+ }+ };+ }+}++export const pdfExtractionSemaphore = new PdfExtractionSemaphore(+ config.PDF_EXTRACTION_CONCURRENCY,+);++/** Run `fn` holding a PDF extraction permit. */+export async function withPdfExtractionPermit<T>(+ fn: () => Promise<T>,+): Promise<T> {+ const release = await pdfExtractionSemaphore.acquire();+ try {+ return await fn();+ } finally {+ release();+ }+}