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): report crawl completedAt correctly when no page succeeds (#4899)
claude[bot]924298df58dc
diff --git a/apps/api/src/__tests__/snips/v2/crawl.test.ts b/apps/api/src/__tests__/snips/v2/crawl.test.tsindex 63e0c2d6a..66748bef0 100644--- a/apps/api/src/__tests__/snips/v2/crawl.test.ts+++ b/apps/api/src/__tests__/snips/v2/crawl.test.ts@@ -350,6 +350,43 @@ describe("Crawl tests", () => {10 * scrapeTimeout,);+ it.concurrent(+ "crawl status completedAt follows the failed jobs when no page succeeds",+ async () => {+ // The start URL cannot resolve, so the only job in the crawl fails.+ const results = await crawl(+ {+ url: `https://crawl-completed-at-${crypto.randomUUID()}.invalid/`,+ limit: 1,+ },+ identity,+ false,+ );+ const afterCrawl = Date.now();++ expect(results.success).toBe(true);+ if (!results.success) return;+ expect(results.status).not.toBe("scraping");+ expect(results.completed).toBe(0);+ expect(typeof results.createdAt).toBe("string");+ expect(typeof results.completedAt).toBe("string");++ const createdAtMs = new Date(results.createdAt!).getTime();+ const completedAtMs = new Date(results.completedAt!).getTime();++ // Before the fix, completedAt fell back to createdAt (duration 0)+ // because only successful jobs had a finish time.+ expect(completedAtMs).toBeGreaterThan(createdAtMs);+ expect(results.duration).toBeGreaterThan(0);++ // completedAt must not be later than the moment the crawl was seen as+ // done. Allow a small gap for clock differences between the test+ // runner and the worker.+ expect(completedAtMs).toBeLessThanOrEqual(afterCrawl + 1000);+ },+ 10 * scrapeTimeout,+ );+concurrentIf(ALLOW_TEST_SUITE_WEBSITE)("delay parameter works",async () => {diff --git a/apps/api/src/lib/crawl-redis.ts b/apps/api/src/lib/crawl-redis.tsindex 46b29ea74..d8c4b4c50 100644--- a/apps/api/src/lib/crawl-redis.ts+++ b/apps/api/src/lib/crawl-redis.ts@@ -229,6 +229,16 @@ export async function addCrawlJobs(}}+// Sets KEYS[1] to ARGV[1] only if the stored value is missing or smaller,+// then refreshes the TTL (ARGV[2], in seconds). Jobs can finish out of order,+// so a plain SET could replace a newer finish time with an older one.+const SET_IF_GREATER_SCRIPT = `local current = tonumber(redis.call("get", KEYS[1]))+if current == nil or tonumber(ARGV[1]) > current then+ redis.call("set", KEYS[1], ARGV[1])+end+redis.call("expire", KEYS[1], ARGV[2])+return 1`;+export async function addCrawlJobDone(id: string,job_id: string,@@ -248,16 +258,24 @@ export async function addCrawlJobDone(let lastError: unknown = null;for (let attempt = 1; attempt <= 3; attempt++) {try {+ const now = Date.now();const pipeline = redisEvictConnection.pipeline();pipeline.sadd("crawl:" + id + ":jobs_done", job_id);pipeline.expire("crawl:" + id + ":jobs_done", 24 * 60 * 60);+ // jobs_donez_ordered only holds successful jobs, so it cannot tell when+ // a crawl ended if its last jobs failed. Keep the finish time of the+ // latest job of any outcome for the crawl status completedAt.+ pipeline.eval(+ SET_IF_GREATER_SCRIPT,+ 1,+ "crawl:" + id + ":last_job_done_at",+ now,+ 24 * 60 * 60,+ );+if (success) {- pipeline.zadd(- "crawl:" + id + ":jobs_donez_ordered",- Date.now(),- job_id,- );+ pipeline.zadd("crawl:" + id + ":jobs_donez_ordered", now, job_id);} else {// in case it's already been pushed, make sure it's removedpipeline.zrem("crawl:" + id + ":jobs_donez_ordered", job_id);@@ -437,6 +455,9 @@ export async function getDoneJobsOrdered();}+/// Finish time of the latest done job in the crawl, failed jobs included.+/// Crawls that started before last_job_done_at existed only have the+/// successful-job timestamps, so take the later of the two.export async function getLastDoneJobTimestamp(id: string,): Promise<number | null> {@@ -444,15 +465,24 @@ export async function getLastDoneJobTimestamp("crawl:" + id + ":jobs_donez_ordered",24 * 60 * 60,);- const result = await redisEvictConnection.zrange(- "crawl:" + id + ":jobs_donez_ordered",- -1,- -1,- "WITHSCORES",+ await redisEvictConnection.expire(+ "crawl:" + id + ":last_job_done_at",+ 24 * 60 * 60,);- if (!result || result.length < 2) return null;- const score = parseInt(result[1], 10);- return Number.isFinite(score) ? score : null;+ const [lastAny, lastSuccess] = await Promise.all([+ redisEvictConnection.get("crawl:" + id + ":last_job_done_at"),+ redisEvictConnection.zrange(+ "crawl:" + id + ":jobs_donez_ordered",+ -1,+ -1,+ "WITHSCORES",+ ),+ ]);+ const candidates = [+ lastAny !== null ? parseInt(lastAny, 10) : NaN,+ lastSuccess && lastSuccess.length >= 2 ? parseInt(lastSuccess[1], 10) : NaN,+ ].filter(x => Number.isFinite(x));+ return candidates.length > 0 ? Math.max(...candidates) : null;}export async function getDoneJobsOrderedUntil(