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): make a sync scrape's terminal state readable before it answers (#4697)
Gergő Móricz4361ad35270e
diff --git a/apps/api/src/services/logging/log_job.test.ts b/apps/api/src/services/logging/log_job.test.tsindex dcff85ef3..91e6516ec 100644--- a/apps/api/src/services/logging/log_job.test.ts+++ b/apps/api/src/services/logging/log_job.test.ts@@ -319,6 +319,122 @@ describe("operational job state logging", () => {);});+ it("reports the state written before the PostgreSQL insert starts", async () => {+ const id = "019e6f45-7778-727d-adf0-0abe9d5062b8";+ const stateWrite = deferred<boolean>();+ writeScrapeJobState.mockReturnValueOnce(stateWrite.promise);+ let insertsWhenStateWritten = -1;+ const onStateWritten = vi.fn(() => {+ insertsWhenStateWritten = values.mock.calls.length;+ });++ const logging = logScrape(+ {+ id,+ request_id: id,+ url: "https://example.com",+ is_successful: true,+ time_taken: 1,+ team_id: "team-id",+ options: { formats: ["markdown"] } as any,+ credits_cost: 1,+ skipNuq: true,+ zeroDataRetention: false,+ },+ false,+ { onStateWritten },+ );+ await Promise.resolve();++ expect(writeScrapeJobState).toHaveBeenCalledTimes(1);+ expect(onStateWritten).not.toHaveBeenCalled();+ expect(values).not.toHaveBeenCalled();++ stateWrite.resolve(true);+ await logging;++ expect(onStateWritten).toHaveBeenCalledWith("written");+ expect(insertsWhenStateWritten).toBe(0);+ expect(values).toHaveBeenCalledTimes(1);+ });++ it("reports a failed state write and keeps logging", async () => {+ const id = "019e6f45-7778-727d-adf0-0abe9d5062b9";+ writeScrapeJobState.mockRejectedValueOnce(new Error("bigtable down"));+ const onStateWritten = vi.fn();++ await logScrape(+ {+ id,+ request_id: id,+ url: "https://example.com",+ is_successful: true,+ time_taken: 1,+ team_id: "team-id",+ options: { formats: ["markdown"] } as any,+ credits_cost: 1,+ skipNuq: true,+ zeroDataRetention: false,+ },+ false,+ { onStateWritten },+ );++ expect(onStateWritten).toHaveBeenCalledWith("failed");+ expect(values).toHaveBeenCalledTimes(1);+ });++ it("reports a skipped state write for a parse, which stores none", async () => {+ const id = "019e6f45-7778-727d-adf0-0abe9d5062ba";+ const onStateWritten = vi.fn();++ await logScrape(+ {+ id,+ request_id: id,+ url: "https://example.com/file.pdf",+ is_successful: true,+ time_taken: 1,+ team_id: "team-id",+ options: { formats: ["markdown"] } as any,+ credits_cost: 1,+ skipNuq: true,+ zeroDataRetention: false,+ is_parse: true,+ },+ false,+ { onStateWritten },+ );++ expect(writeScrapeJobState).not.toHaveBeenCalled();+ expect(onStateWritten).toHaveBeenCalledWith("skipped");+ });++ it("reports a skipped state write when no state table is configured", async () => {+ const id = "019e6f45-7778-727d-adf0-0abe9d5062bb";+ writeScrapeJobState.mockResolvedValueOnce(false);+ const onStateWritten = vi.fn();++ await logScrape(+ {+ id,+ request_id: id,+ url: "https://example.com",+ is_successful: true,+ time_taken: 1,+ team_id: "team-id",+ options: { formats: ["markdown"] } as any,+ credits_cost: 1,+ skipNuq: true,+ zeroDataRetention: false,+ },+ false,+ { onStateWritten },+ );++ expect(onStateWritten).toHaveBeenCalledWith("skipped");+ });+it("writes job access and terminal state for a crawl child", async () => {const id = "019e6f45-7778-727d-adf0-0abe9d5062b7";const crawlId = "019e6f45-7778-727d-adf0-0abe9d5062b6";diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.tsindex c7f4ec227..17979ba15 100644--- a/apps/api/src/services/logging/log_job.ts+++ b/apps/api/src/services/logging/log_job.ts@@ -667,7 +667,28 @@ export type LoggedScrape = {jobAccess?: boolean;};-export async function logScrape(scrape: LoggedScrape, force: boolean = false) {+export type ScrapeStateOutcome =+ /** The terminal state is readable from Bigtable. */+ | "written"+ /** Nothing to write: a parse job, or no state table configured. */+ | "skipped"+ /** The Bigtable write threw; the error is logged here. */+ | "failed";++type LogScrapeHooks = {+ /**+ * Called once the terminal state write has settled, before anything else+ * is logged. The sync scrape path waits on this before answering, so an+ * interact call that follows the response finds its replay context.+ */+ onStateWritten?: (outcome: ScrapeStateOutcome) => void;+};++export async function logScrape(+ scrape: LoggedScrape,+ force: boolean = false,+ hooks?: LogScrapeHooks,+) {return withLogSpan({operation: scrape.is_parse ? "parse" : "scrape",@@ -677,11 +698,15 @@ export async function logScrape(scrape: LoggedScrape, force: boolean = false) {force,zeroDataRetention: scrape.zeroDataRetention,},- () => logScrapeInternal(scrape, force),+ () => logScrapeInternal(scrape, force, hooks),);}-async function logScrapeInternal(scrape: LoggedScrape, force: boolean = false) {+async function logScrapeInternal(+ scrape: LoggedScrape,+ force: boolean = false,+ hooks?: LogScrapeHooks,+) {const logger = _logger.child({module: "log_job",method: "logScrape",@@ -698,6 +723,47 @@ async function logScrapeInternal(scrape: LoggedScrape, force: boolean = false) {? previewTeamId: scrape.team_id);+ // Terminal state for every scrape job, standalone or child, so status reads+ // never need the PostgreSQL row. It goes first: the sync scrape response+ // waits for it, and nothing else here has to be readable that early.+ let stateOutcome: ScrapeStateOutcome = "skipped";+ try {+ if (!scrape.is_parse) {+ const replay = scrape.zeroDataRetention+ ? undefined+ : buildReplayContextFromScrape({+ id: scrape.id,+ team_id: storedTeamId,+ url: scrape.url,+ options: scrape.options,+ }).context;+ const written = await writeScrapeJobState(scrape.id, {+ status: scrape.is_successful ? "completed" : "failed",+ requestId: scrape.request_id,+ completedAtMs: Date.now(),+ creditsBilled: scrape.credits_cost,+ ...(scrape.zeroDataRetention+ ? {}+ : {+ ...(scrape.error ? { error: scrape.error } : {}),+ ...(replay ? { replay } : {}),+ ...(scrape.options.profile+ ? { profile: scrape.options.profile }+ : {}),+ ...(typeof (scrape.options as any).origin === "string"+ ? { origin: (scrape.options as any).origin }+ : {}),+ }),+ });+ stateOutcome = written ? "written" : "skipped";+ }+ } catch (error) {+ stateOutcome = "failed";+ logger.error("Failed to write scrape state to Bigtable", { error });+ } finally {+ hooks?.onStateWritten?.(stateOutcome);+ }+const feedbackJob = {jobId: scrape.id,requestId: scrape.request_id,@@ -775,41 +841,6 @@ async function logScrapeInternal(scrape: LoggedScrape, force: boolean = false) {}}- // Terminal state for every scrape job, standalone or child, so status reads- // never need the PostgreSQL row.- if (!scrape.is_parse) {- try {- const replay = scrape.zeroDataRetention- ? undefined- : buildReplayContextFromScrape({- id: scrape.id,- team_id: storedTeamId,- url: scrape.url,- options: scrape.options,- }).context;- await writeScrapeJobState(scrape.id, {- status: scrape.is_successful ? "completed" : "failed",- requestId: scrape.request_id,- completedAtMs: Date.now(),- creditsBilled: scrape.credits_cost,- ...(scrape.zeroDataRetention- ? {}- : {- ...(scrape.error ? { error: scrape.error } : {}),- ...(replay ? { replay } : {}),- ...(scrape.options.profile- ? { profile: scrape.options.profile }- : {}),- ...(typeof (scrape.options as any).origin === "string"- ? { origin: (scrape.options as any).origin }- : {}),- }),- });- } catch (error) {- logger.error("Failed to write scrape state to Bigtable", { error });- }- }-if (!scrape.is_parse &&scrape.doc &&diff --git a/apps/api/src/services/worker/scrape-worker.ts b/apps/api/src/services/worker/scrape-worker.tsindex 295f9ed54..9817cf47c 100644--- a/apps/api/src/services/worker/scrape-worker.ts+++ b/apps/api/src/services/worker/scrape-worker.ts@@ -98,7 +98,7 @@ import {setSpanAttributes,} from "../../lib/otel-tracer";import { ScrapeUrlResponse } from "../../scraper/scrapeURL";-import { logScrape } from "../logging/log_job";+import { logScrape, type ScrapeStateOutcome } from "../logging/log_job";import { FeatureFlag } from "../../scraper/scrapeURL/engines";import {recordMonitorScrapeFailure,@@ -113,6 +113,12 @@ import { emitScrapeActivityEvent } from "../../lib/siem-logging";configDotenv();+/**+ * How long a sync scrape waits for its Bigtable terminal state to be written+ * before answering anyway. A write normally takes a few milliseconds.+ */+const SCRAPE_STATE_BARRIER_MS = 2_000;+const jobLockExtendInterval = config.JOB_LOCK_EXTEND_INTERVAL;const jobLockExtensionTime = config.JOB_LOCK_EXTENSION_TIME;@@ -931,6 +937,10 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {doc.metadata.creditsUsed = credits_billed ?? undefined;+ let stateWritten: (outcome: ScrapeStateOutcome) => void = () => {};+ const scrapeStateWritten = new Promise<ScrapeStateOutcome>(resolve => {+ stateWritten = resolve;+ });const logScrapePromise = logScrape({id: job.id,@@ -952,6 +962,12 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {monitor_check_id: job.data.monitoring?.checkId,},false,+ { onStateWritten: stateWritten },+ );+ // Release the barrier if logging dies before the state write settles.+ logScrapePromise.then(+ () => stateWritten("failed"),+ () => stateWritten("failed"),);trackScrape({@@ -972,10 +988,34 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {);if (job.data.skipNuq) {- // doesn't use GCS for result retrieval, safe to not await+ // doesn't use GCS for result retrieval, safe to not await the restlogScrapePromise.catch(err =>logger.warn("Background scrape log failed", { error: err }),);+ // ...but the terminal state must be readable before the sync response+ // goes out: an interact call right after a fast scrape reads it for+ // its replay context, and there is no NuQ job to fall back on. The+ // wait is bounded so a Bigtable stall cannot hold every sync scrape.+ let barrier: NodeJS.Timeout | undefined;+ const outcome = await Promise.race([+ scrapeStateWritten,+ new Promise<"timed_out">(resolve => {+ barrier = setTimeout(+ () => resolve("timed_out"),+ SCRAPE_STATE_BARRIER_MS,+ );+ }),+ ]);+ if (barrier !== undefined) clearTimeout(barrier);+ if (outcome === "failed" || outcome === "timed_out") {+ logger.warn(+ "Sync scrape answered without a readable terminal state",+ {+ outcome,+ barrierMs: SCRAPE_STATE_BARRIER_MS,+ },+ );+ }} else {// v0 - must await because waitForJob reads from GCSawait logScrapePromise;