Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/test_politeness_hosts.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"""Politeness is a property of the fleet, not of one worker: per-host serialisation, delay, retries, conditionals.4243Evidence comes from the fixture site's own request log (timestamps taken when each request arrives).44"""45import asyncio46from itertools import pairwise4748import pytest4950pytestmark = pytest.mark.pg515253async def db(stack, sql, *args):54 async with stack.orch.pool.acquire() as c:55 return await c.fetch(sql, *args)565758async def val(stack, sql, *args):59 async with stack.orch.pool.acquire() as c:60 return await c.fetchval(sql, *args)616263async def submit(stack, path="/v1/crawl", **body) -> str:64 r = await stack.client.post(path, json=body)65 assert r.status_code == 202, r.text66 return r.json()["job_id"]676869def page_requests(stack):70 return [q for q in stack.site.state.requests if q.path not in ("/robots.txt",) and "sitemap" not in q.path]717273async def test_host_delay_and_single_flight_hold_with_three_workers(stack, monkeypatch):74 """3 workers x 4 slots, two concurrent jobs, one host: one request at a time, >= 200 ms apart."""75 monkeypatch.setenv("SPIDER_TEST_DELAY_MS", "200")76 for i in range(3):77 await stack.start_worker(name=f"p{i}", concurrency=4)78 # /err/slow keeps a request in flight for 400 ms: an overlapping fetch would be visible in the log79 j1 = await submit(stack, url=stack.url("/blog?page=1"), render="http", use_sitemaps=False,80 budgets={"max_depth": 3, "max_pages": 9}, policy={"include_paths": ["^/blog"]})81 j2 = await submit(stack, urls=[stack.url(f"/err/slow?ms={400 + i}") for i in range(3)] + [stack.url("/about")],82 render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 9})83 for j in (j1, j2):84 assert (await stack.wait(j, timeout=60))["status"] in ("succeeded", "partial")85 reqs = page_requests(stack)86 assert len(reqs) == 13, [q.path_qs for q in reqs]87 assert len({q.headers.get("User-Agent") for q in stack.site.state.requests}) == 188 ts = [q.timestamp for q in reqs]89 assert ts == sorted(ts)90 gaps = [b - a for a, b in pairwise(ts)]91 assert min(gaps) >= 0.195, f"two page fetches of one host only {min(gaps) * 1000:.0f} ms apart: {gaps}"92 # single flight: the request that follows a slow page starts after that page was fully served93 for a, b in pairwise(reqs):94 if a.path == "/err/slow":95 ms = int(a.query["ms"])96 assert b.timestamp - a.timestamp >= ms / 1000 + 0.195, (a.path_qs, b.path_qs, b.timestamp - a.timestamp)97 # the delay is spread over the whole fleet, and several workers really took part98 assert await val(stack, "select count(distinct worker_id) from job_attempts") >= 299 assert await val(stack, "select max(in_flight) from host_state") == 0100 assert await val(stack, "select delay_ms from host_state where host='127.0.0.1'") == 200101102103async def test_lease_never_hands_out_two_tasks_of_one_host(stack):104 """The gate is in the orchestrator: whatever the workers ask for, one host = one lease at a time."""105 urls = [stack.url(p) for p in ("/about", "/legal", "/contact", "/landing")]106 await submit(stack, urls=urls, render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 9})107 a, b = await stack.fake_worker("a"), await stack.fake_worker("b")108 try:109 got = await asyncio.gather(a.lease(8, wait=0), b.lease(8, wait=0), a.lease(8, wait=0), b.lease(8, wait=0))110 leased = [t for g in got for t in g]111 assert len(leased) == 1, f"{len(leased)} tasks of the same host were leased at once"112 assert await val(stack, "select in_flight from host_state where host='127.0.0.1'") == 1113 holder = a if leased[0] in got[0] + got[2] else b114 assert (await holder.complete(leased[0], holder.page(leased[0]["payload"]["url"]))).status_code == 200115 assert len(await b.lease(8, wait=3)) == 1116 finally:117 await a.close()118 await b.close()119120121async def test_429_honours_retry_after_and_5xx_retries_are_bounded(stack):122 """429 twice then 200: retried after >= Retry-After, succeeds. Always-500: max_attempts tries, then failed."""123 await stack.start_worker(concurrency=4)124 job_id = await submit(stack, urls=[stack.url("/err/429"), stack.url("/err/500")], render="http", use_sitemaps=False,125 budgets={"max_depth": 0, "max_pages": 5})126 job = await stack.wait(job_id, timeout=90)127 assert job["status"] == "partial", job128 st = {r["url"][len(stack.site.base_url):]: r for r in await db(stack, "select * from urls where job_id=$1", job_id)}129 assert st["/err/429"]["status"] == "fetched" and st["/err/429"]["http_status"] == 200130 assert st["/err/500"]["status"] == "failed" and st["/err/500"]["reason"].startswith("http_5xx")131 hits429 = [q for q in stack.site.state.requests if q.path == "/err/429"]132 assert [q.status for q in hits429] == [429, 429, 200]133 gaps = [b.timestamp - a.timestamp for a, b in pairwise(hits429)]134 assert min(gaps) >= 1.0, f"Retry-After: 1 was not honoured: {gaps}"135 # after a 429 the whole host backs off, not just that URL136 for q in hits429[:2]:137 nxt = next(x for x in stack.site.state.requests if x.seq > q.seq and x.path != "/robots.txt")138 assert nxt.timestamp - q.timestamp >= 1.0, (nxt.path, nxt.timestamp - q.timestamp)139 assert stack.site.state.hits("/err/500") == stack.settings.max_task_attempts == 3140 att = await db(stack, "select t.payload->>'url' url, a.outcome, a.error_class from job_attempts a join tasks t on "141 "t.id=a.task_id where a.job_id=$1 order by a.id", job_id)142 by = {}143 for a in att:144 by.setdefault(a["url"][len(stack.site.base_url):], []).append((a["outcome"], a["error_class"]))145 assert by["/err/429"] == [("retry", "http_429"), ("retry", "http_429"), ("done", None)]146 assert by["/err/500"] == [("retry", "http_5xx"), ("retry", "http_5xx"), ("failed", "http_5xx")]147 snap = await stack.results(job_id)148 assert len(snap) == 1 and "RATE-LIMIT-PASSED-3382" in snap[0]["content"]["markdown"]149150151async def test_permanent_errors_are_fetched_exactly_once(stack):152 await stack.start_worker(concurrency=4)153 job_id = await submit(stack, urls=[stack.url("/err/404"), stack.url("/err/410"), stack.url("/about")], render="http",154 use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 5})155 job = await stack.wait(job_id, timeout=30)156 assert job["status"] == "partial"157 await asyncio.sleep(0.5)158 for p in ("/err/404", "/err/410", "/about"):159 assert stack.site.state.hits(p) == 1, p160 rows = {r["url"][len(stack.site.base_url):]: r for r in await db(stack, "select * from urls where job_id=$1", job_id)}161 assert rows["/err/404"]["status"] == "failed" and rows["/err/404"]["http_status"] == 404162 assert rows["/err/410"]["status"] == "failed" and rows["/err/410"]["http_status"] == 410163 assert await val(stack, "select max(attempts) from tasks where job_id=$1", job_id) == 1164 assert await val(stack, "select count(*) from job_attempts where job_id=$1", job_id) == 3165166167async def test_robots_fetched_once_per_host_and_every_request_names_the_bot(stack):168 await stack.start_worker(concurrency=4)169 job_id = await submit(stack, url=stack.url("/blog?page=1"), render="http", use_sitemaps=True,170 budgets={"max_depth": 2, "max_pages": 12}, policy={"include_paths": ["^/blog"]})171 await stack.wait(job_id, timeout=60)172 assert len(page_requests(stack)) >= 10173 assert stack.site.state.hits("/robots.txt") == 1, "robots.txt must be cached per host, not fetched per URL"174 uas = {q.headers.get("User-Agent", "") for q in stack.site.state.requests}175 assert len(uas) == 1 and next(iter(uas)).startswith("SpiderBot/"), uas176 assert all(q.method == "GET" for q in stack.site.state.requests)177178179async def test_crawl_delay_from_robots_raises_the_host_delay(stack, monkeypatch):180 """Crawl-delay reported by a worker becomes the host delay (the test override is removed for this case)."""181 monkeypatch.delenv("SPIDER_TEST_DELAY_MS")182 urls = [stack.url("/about"), stack.url("/legal")]183 await submit(stack, urls=urls, render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 5},184 policy={"min_delay_ms": 300})185 fw = await stack.fake_worker()186 try:187 (t,) = await fw.lease()188 assert (await fw.complete(t, fw.page(t["payload"]["url"]) | {"crawl_delay_s": 2.5})).status_code == 200189 hs = (await db(stack, "select delay_ms, next_allowed_at - now() as wait from host_state where host='127.0.0.1'"))[0]190 assert hs["delay_ms"] == 2500 and 2.0 < hs["wait"].total_seconds() <= 2.5191 assert await fw.lease(wait=1.0) == [], "second URL leased before the crawl delay elapsed"192 (t2,) = await fw.lease(wait=4)193 # without Crawl-delay the job's own minimum applies194 assert (await fw.complete(t2, fw.page(t2["payload"]["url"]))).status_code == 200195 assert await val(stack, "select delay_ms from host_state where host='127.0.0.1'") == 300196 finally:197 await fw.close()198199200async def test_operator_policy_min_delay_overrides_a_smaller_job_delay(stack, monkeypatch):201 monkeypatch.delenv("SPIDER_TEST_DELAY_MS")202 r = await stack.client.put("/v1/policies", json={"domain": "127.0.0.1", "min_delay_ms": 4000})203 assert r.status_code in (200, 201), r.text204 await submit(stack, "/v1/scrape", url=stack.url("/about"), render="http", policy={"min_delay_ms": 250})205 fw = await stack.fake_worker()206 try:207 (t,) = await fw.lease()208 assert (await fw.complete(t, fw.page(t["payload"]["url"]))).status_code == 200209 assert await val(stack, "select delay_ms from host_state where host='127.0.0.1'") == 4000210 finally:211 await fw.close()212