Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/test_resilience_budgets.py8# Module : Tests9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Job budgets are hard limits: pages, depth, bytes and duration, counted in the database."""42import asyncio4344import pytest4546pytestmark = pytest.mark.pg47QUIET = ["^/wall/", "^/err/", "^/trap/", "^/r/", "^/loop/", "^/dyn/", "^/spa/", "^/ui/", "^/login"]484950async def db(stack, sql, *args):51 async with stack.orch.pool.acquire() as c:52 return await c.fetch(sql, *args)535455async def val(stack, sql, *args):56 async with stack.orch.pool.acquire() as c:57 return await c.fetchval(sql, *args)585960async def submit(stack, **body) -> str:61 r = await stack.client.post("/v1/crawl", json={"render": "http", "use_sitemaps": False} | body)62 assert r.status_code == 202, r.text63 return r.json()["job_id"]646566async def test_max_pages_is_respected_exactly(stack):67 await stack.start_worker(concurrency=4)68 job_id = await submit(stack, url=stack.url("/"), budgets={"max_pages": 7, "max_depth": 5},69 policy={"exclude_paths": QUIET})70 job = await stack.wait(job_id)71 assert job["status"] == "partial" and "max_pages" in job["progress"]["budgets_hit"], job72 assert await val(stack, "select count(*) from urls where job_id=$1", job_id) == 773 assert await val(stack, "select count(*) from tasks where job_id=$1 and kind='fetch'", job_id) == 774 assert job["progress"]["pages_admitted"] == 7 and job["progress"]["skipped"]["max_pages"] > 075 pages = [q for q in stack.site.state.requests if q.path != "/robots.txt"]76 assert len(pages) == 7, [q.path_qs for q in pages]777879async def test_max_depth_is_respected_exactly(stack):80 await stack.start_worker(concurrency=4)81 job_id = await submit(stack, url=stack.url("/blog?page=1"), budgets={"max_pages": 500, "max_depth": 2},82 policy={"include_paths": ["^/blog"]})83 job = await stack.wait(job_id)84 rows = await db(stack, "select url, depth, status from urls where job_id=$1", job_id)85 depths = {r["url"][len(stack.site.base_url):]: r["depth"] for r in rows}86 assert max(depths.values()) == 2 and min(depths.values()) == 087 # page 1 (depth 0) -> its posts and page 2 (depth 1) -> page 2's posts and page 3 (depth 2); page 4 is depth 388 assert depths["/blog?page=2"] == 1 and depths["/blog?page=3"] == 289 assert "/blog?page=4" not in depths and "/blog/post-9" not in depths90 assert {f"/blog/post-{i}" for i in range(1, 9)} <= set(depths)91 assert job["progress"]["skipped"]["max_depth"] >= 192 assert stack.site.state.hits("/blog?page=4") == 0 and stack.site.state.hits("/blog/post-9") == 093 assert all(r["status"] == "fetched" for r in rows), rows949596async def test_max_bytes_stops_the_crawl(stack):97 await stack.start_worker(concurrency=4)98 job_id = await submit(stack, url=stack.url("/"), budgets={"max_pages": 200, "max_depth": 5, "max_bytes": 1000},99 policy={"exclude_paths": QUIET})100 job = await stack.wait(job_id)101 assert job["status"] == "partial" and "max_bytes" in job["progress"]["budgets_hit"], job102 assert job["progress"]["bytes_used"] > 1000103 counts = job["progress"]["urls"]104 assert counts.get("fetched") == 1 and counts.get("skipped", 0) >= 5 and "queued" not in counts, counts105 reasons = {r["reason"] for r in await db(stack, "select reason from urls where job_id=$1 and status='skipped'", job_id)}106 assert reasons == {"budget:max_bytes"}107 n = len(stack.site.state.requests)108 await asyncio.sleep(1.0)109 assert len(stack.site.state.requests) == n, "requests continued after the byte budget was exhausted"110 assert [q.path for q in stack.site.state.requests if q.path != "/robots.txt"] == ["/"]111112113async def test_max_duration_deadline_ends_an_endless_crawl_as_partial(stack, monkeypatch):114 """A trap that never ends, a 5 s deadline: the job stops by itself, partial, with the budget named."""115 monkeypatch.setenv("SPIDER_TEST_DELAY_MS", "150")116 await stack.start_worker(concurrency=4)117 t0 = asyncio.get_running_loop().time()118 job_id = await submit(stack, url=stack.url("/trap/pages?page=1"),119 budgets={"max_pages": 5000, "max_depth": 50, "max_duration_s": 5, "max_urls_per_pattern": 5000},120 policy={"include_paths": ["^/trap/pages"]})121 job = await stack.wait(job_id, timeout=40)122 took = asyncio.get_running_loop().time() - t0123 assert job["status"] == "partial" and "max_duration" in job["progress"]["budgets_hit"], job124 assert 4.5 <= took <= 20, took # deadline 5 s + one maintenance period, with slack for a loaded machine125 assert job["progress"]["urls"].get("fetched", 0) >= 5 and "queued" not in job["progress"]["urls"]126 n = len(stack.site.state.requests)127 await asyncio.sleep(1.5)128 assert len(stack.site.state.requests) == n, "the crawl went on after its deadline"129 assert await val(stack, "select count(*) from tasks where job_id=$1 and status in ('pending','leased')", job_id) == 0130131132async def test_page_finishing_after_the_deadline_admits_nothing_new(stack):133 """The task in flight when the deadline falls may finish, but its links must not restart the crawl."""134 seed = stack.url("/trap/pages?page=1")135 job_id = await submit(stack, url=seed, budgets={"max_pages": 100, "max_depth": 10, "max_duration_s": 5})136 fw = await stack.fake_worker()137 try:138 (t,) = await fw.lease()139 await db(stack, "update jobs set deadline_at = now() - interval '1 second' where id=$1", job_id)140 assert await stack.maint.enforce_deadlines() == 1141 assert (await stack.client.get(f"/v1/jobs/{job_id}")).json()["status"] == "running" # one lease still out142 r = await fw.complete(t, fw.page(seed, links=[stack.url(f"/trap/pages?page={i}") for i in range(2, 6)]))143 assert r.status_code == 200, r.text144 job = (await stack.client.get(f"/v1/jobs/{job_id}")).json()145 assert job["status"] == "partial" and job["progress"]["budgets_hit"] == ["max_duration"], job146 assert await val(stack, "select count(*) from tasks where job_id=$1 and status in ('pending','leased')", job_id) == 0147 assert await val(stack, "select count(*) from urls where job_id=$1 and status='queued'", job_id) == 0148 assert await fw.lease(wait=0.5) == []149 finally:150 await fw.close()151152153async def test_page_finishing_after_the_byte_budget_admits_nothing_new(stack):154 seed = stack.url("/trap/pages?page=1")155 job_id = await submit(stack, url=seed, budgets={"max_pages": 100, "max_depth": 10, "max_bytes": 5000})156 fw = await stack.fake_worker()157 try:158 (t,) = await fw.lease()159 links = [stack.url(f"/trap/pages?page={i}") for i in range(2, 5)]160 assert (await fw.complete(t, fw.page(seed, links=links, nbytes=6000))).status_code == 200161 job = (await stack.client.get(f"/v1/jobs/{job_id}")).json()162 assert job["status"] == "partial" and job["progress"]["budgets_hit"] == ["max_bytes"], job163 assert job["progress"]["urls"] == {"fetched": 1, "skipped": 3}164 assert await fw.lease(wait=0.5) == []165 finally:166 await fw.close()167