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_leases.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"""Resilience of the control plane: at-least-once delivery, fencing, dead letters, drain, restart.4243Time is accelerated where the property does not depend on it (a lease is expired by moving its44`lease_expires_at` into the past); one test waits for a real 6 s lease to run out.45"""46import asyncio4748import httpx49import pytest5051pytestmark = pytest.mark.pg52TERMINAL_URL = {"fetched", "duplicate", "not_modified", "failed", "blocked", "skipped"}535455async def db(stack, sql, *args):56 async with stack.orch.pool.acquire() as c:57 return await c.fetch(sql, *args)585960async def val(stack, sql, *args):61 async with stack.orch.pool.acquire() as c:62 return await c.fetchval(sql, *args)636465async def until(cond, timeout=20.0, step=0.05, what="condition"):66 t0 = asyncio.get_running_loop().time()67 while True:68 v = await cond()69 if v:70 return v71 if asyncio.get_running_loop().time() - t0 > timeout:72 raise AssertionError(f"timed out waiting for {what}")73 await asyncio.sleep(step)747576async def submit(stack, path="/v1/crawl", **body) -> str:77 r = await stack.client.post(path, json=body)78 assert r.status_code == 202, r.text79 return r.json()["job_id"]808182async def expire_and_reap(stack, task_id) -> int:83 await db(stack, "update tasks set lease_expires_at = now() - interval '1 second' where id=$1 and status='leased'",84 task_id)85 return await stack.maint.reap_leases()868788async def assert_no_logical_duplicates(stack, job_id):89 dups = await db(stack, "select url_id, engine, profile, count(*) n from snapshots where job_id=$1 "90 "group by 1,2,3 having count(*) > 1", job_id)91 assert dups == [], f"a URL has two snapshots for the same engine/profile: {dups}"92 recs = await db(stack, "select url, count(*) n from snapshots where job_id=$1 group by 1 having count(*) > 1", job_id)93 assert recs == [], recs949596async def test_worker_crash_mid_task_is_recovered_by_another_worker(stack):97 """(a) hard kill with a lease held: after expiry the task is re-issued, nothing is lost or doubled."""98 slow = stack.url("/err/slow?ms=4000")99 urls = [slow, stack.url("/about"), stack.url("/legal"), stack.url("/contact")]100 job_id = await submit(stack, urls=urls, render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 10})101 w1, t1 = await stack.start_worker(name="victim", concurrency=4)102 # wait until the slow URL is leased and really in flight on the site103 await until(lambda: val(stack, "select 1 from tasks where job_id=$1 and status='leased' and payload->>'url'=$2",104 job_id, slow), what="slow task leased")105 await until(lambda: asyncio.sleep(0, stack.site.state.hits("/err/slow") >= 1), what="slow request in flight")106 await stack.stop_worker(w1, t1, hard=True)107 await w1.close()108 leased = await db(stack, "select id, fencing_token, attempts from tasks where job_id=$1 and status='leased'", job_id)109 assert len(leased) == 1, "the crashed worker must leave its lease behind (no abandon)"110 tok1 = leased[0]["fencing_token"]111 # nothing may progress on that URL while the lease is still valid112 await stack.start_worker(name="rescuer", concurrency=4)113 await asyncio.sleep(1.0)114 assert await val(stack, "select status from tasks where id=$1", leased[0]["id"]) == "leased"115 await asyncio.sleep(stack.settings.lease_seconds) # the real lease runs out116 await stack.maint.tick()117 job = await stack.wait(job_id, timeout=60)118 assert job["status"] == "succeeded", job119 rows = await db(stack, "select url, status from urls where job_id=$1", job_id)120 assert len(rows) == len(urls)121 assert all(r["status"] in TERMINAL_URL for r in rows) and not [r for r in rows if r["status"] == "queued"], rows122 assert {r["url"]: r["status"] for r in rows}[slow] == "fetched"123 await assert_no_logical_duplicates(stack, job_id)124 att = await db(stack, "select a.outcome, a.error_class, a.fencing_token, w.name from job_attempts a join workers w "125 "on w.id=a.worker_id where a.task_id=$1 order by a.id", leased[0]["id"])126 assert [(a["outcome"], a["name"]) for a in att] == [("expired", "victim"), ("done", "rescuer")], att127 assert att[0]["error_class"] == "worker_lost" and att[1]["fencing_token"] > tok1128 assert stack.site.state.hits("/err/slow") == 2 # at-least-once: fetched again, stored once129 assert await val(stack, "select count(*) from tasks where job_id=$1 and status in ('pending','leased')", job_id) == 0130131132async def test_stale_fencing_token_is_refused_and_completion_is_idempotent(stack):133 """(b) a worker fenced out by a re-issued lease cannot write; the valid result is applied once."""134 url = stack.url("/about")135 job_id = await submit(stack, "/v1/scrape", url=url, render="http")136 old, new = await stack.fake_worker("old"), await stack.fake_worker("new")137 try:138 (t_old,) = await old.lease()139 assert await expire_and_reap(stack, t_old["task_id"]) == 1140 # reaped but not yet re-leased: the old token is already useless141 r = await old.complete(t_old, old.page(url, "written by the stale worker"))142 assert r.status_code == 409 and r.json()["error"]["code"] == "stale_lease", r.text143 (t_new,) = await new.lease()144 assert t_new["task_id"] == t_old["task_id"] and t_new["fencing_token"] > t_old["fencing_token"]145 assert t_new["attempt"] == 2146 for attempt in (old.complete(t_old, old.page(url, "written by the stale worker")), # old token147 old.complete(t_old, old.page(url, "stolen token"), token=t_new["fencing_token"]), # not owner148 new.complete(t_new, new.page(url, "old token"), token=t_old["fencing_token"])):149 r = await attempt150 assert r.status_code == 409 and r.json()["error"]["code"] == "stale_lease", r.text151 assert await val(stack, "select count(*) from snapshots where job_id=$1", job_id) == 0152 assert await val(stack, "select status from urls where job_id=$1", job_id) == "queued"153 assert await val(stack, "select bytes_used from jobs where id=$1", job_id) == 0154 r = await new.complete(t_new, new.page(url, "written by the lease holder", nbytes=321))155 assert r.status_code == 200 and r.json() == {"status": "done"}, r.text156 before = await db(stack, "select id, content_hash from snapshots where job_id=$1", job_id)157 r = await new.complete(t_new, new.page(url, "a different replay", nbytes=321))158 assert r.status_code == 200 and r.json() == {"status": "done", "duplicate": True}, r.text159 r = await old.complete(t_old, old.page(url, "written by the stale worker"))160 assert r.status_code == 409161 after = await db(stack, "select id, content_hash from snapshots where job_id=$1", job_id)162 assert before == after and len(after) == 1163 assert await val(stack, "select bytes_used from jobs where id=$1", job_id) == 321164 assert await val(stack, "select count(*) from search_documents") == 1165 job = await stack.wait(job_id)166 assert job["status"] == "succeeded" and job["progress"]["urls"] == {"fetched": 1}167 out = [a["outcome"] for a in await db(stack, "select outcome from job_attempts where task_id=$1 order by id",168 t_old["task_id"])]169 assert out == ["expired", "done"]170 finally:171 await old.close()172 await new.close()173174175async def test_heartbeat_extends_only_owned_leases_and_reports_lost_ones(stack):176 url = stack.url("/about")177 await submit(stack, "/v1/scrape", url=url, render="http")178 a, b = await stack.fake_worker("a"), await stack.fake_worker("b")179 try:180 (t,) = await a.lease()181 exp0 = await val(stack, "select lease_expires_at from tasks where id=$1", t["task_id"])182 await asyncio.sleep(0.3)183 assert (await a.heartbeat([t["task_id"]]))["abandon"] == []184 assert await val(stack, "select lease_expires_at from tasks where id=$1", t["task_id"]) > exp0185 assert (await b.heartbeat([t["task_id"]]))["abandon"] == [t["task_id"]] # not b's lease186 await expire_and_reap(stack, t["task_id"])187 assert (await a.heartbeat([t["task_id"]]))["abandon"] == [t["task_id"]] # a must stop working on it188 finally:189 await a.close()190 await b.close()191192193async def test_coordinator_restart_mid_crawl_resumes_without_loss(stack, monkeypatch):194 """(c) the gateway process is replaced while a crawl runs: state lives in PostgreSQL, the job completes."""195 monkeypatch.setenv("SPIDER_TEST_DELAY_MS", "120")196 job_id = await submit(stack, url=stack.url("/blog?page=1"), render="http", use_sitemaps=False,197 budgets={"max_depth": 6, "max_pages": 18}, policy={"include_paths": ["^/blog"]})198 await stack.start_worker(name="survivor", concurrency=4)199 await until(lambda: val(stack, "select count(*) >= 4 from urls where job_id=$1 and status='fetched'", job_id),200 what="crawl under way")201 old_app = stack.app202 await stack.stop_gateway()203 with pytest.raises(httpx.TransportError): # the gateway really is down204 await stack.client.get(f"/v1/jobs/{job_id}")205 await asyncio.sleep(1.0)206 await stack.start_gateway()207 assert stack.app is not old_app208 mid = (await stack.client.get(f"/v1/jobs/{job_id}")).json()209 assert mid["status"] in ("running", "queued"), mid210 job = await stack.wait(job_id, timeout=90)211 assert job["status"] == "partial" and job["progress"]["budgets_hit"] == ["max_pages"], job212 rows = await db(stack, "select url, status from urls where job_id=$1", job_id)213 assert len(rows) == 18 and all(r["status"] == "fetched" for r in rows), rows214 await assert_no_logical_duplicates(stack, job_id)215 assert await val(stack, "select count(*) from snapshots where job_id=$1", job_id) == 18216 assert await val(stack, "select count(*) from tasks where job_id=$1 and status <> 'done'", job_id) == 0217 assert stack.site.state.side_effects == []218219220async def test_exhausted_attempts_go_to_dead_letter_and_job_ends_partial(stack):221 """(d) a task whose every lease is lost is dead-lettered: URL failed (worker_lost), job partial, not stuck."""222 urls = [stack.url("/about"), stack.url("/legal")]223 job_id = await submit(stack, urls=urls, render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 5})224 fw = await stack.fake_worker()225 try:226 victim = None227 for _ in range(12):228 leased = await fw.lease(wait=3)229 if not leased:230 break231 (t,) = leased232 victim = victim or t["task_id"]233 if t["task_id"] == victim:234 await expire_and_reap(stack, t["task_id"])235 else:236 assert (await fw.complete(t, fw.page(t["payload"]["url"]))).status_code == 200237 row = (await db(stack, "select status, attempts, max_attempts, last_error, payload->>'url' url from tasks "238 "where id=$1", victim))[0]239 assert row["status"] == "dead" and row["attempts"] == row["max_attempts"] == stack.settings.max_task_attempts240 assert row["last_error"]["class"] == "worker_lost"241 q = (await stack.client.get("/v1/queue")).json()242 assert [d["task_id"] for d in q["dead_letter"]] == [victim] and q["dead_letter"][0]["url"] == row["url"]243 u = (await db(stack, "select status, reason from urls where job_id=$1 and url=$2", job_id, row["url"]))[0]244 assert u["status"] == "failed" and u["reason"].startswith("worker_lost"), dict(u)245 job = await stack.wait(job_id, timeout=15)246 assert job["status"] == "partial", job247 assert job["progress"]["urls"] == {"fetched": 1, "failed": 1}248 att = await db(stack, "select outcome, error_class from job_attempts where task_id=$1", victim)249 assert [(a["outcome"], a["error_class"]) for a in att] == [("expired", "worker_lost")] * 3250 assert await fw.lease(wait=0.5) == [] # a dead task is never leased again251 finally:252 await fw.close()253254255async def test_draining_worker_gets_no_new_lease_finishes_current_task_and_resumes(stack):256 """(e) drain: the current task is finished and acknowledged, nothing new is leased until resume."""257 urls = [stack.url(f"/err/slow?ms={1500 + i}") for i in range(3)]258 job_id = await submit(stack, urls=urls, render="http", use_sitemaps=False, budgets={"max_depth": 0, "max_pages": 5})259 w, _ = await stack.start_worker(name="drained", concurrency=2)260 first = await until(lambda: val(stack, "select id from tasks where job_id=$1 and status='leased'", job_id),261 what="first lease")262 r = await stack.client.post(f"/v1/workers/{w.worker_id}/drain")263 assert r.status_code == 200 and r.json()["state"] == "draining"264 await until(lambda: val(stack, "select status = 'done' from tasks where id=$1", first), what="current task done")265 await asyncio.sleep(2.0)266 st = {r["status"]: r["n"] for r in await db(stack, "select status, count(*) n from tasks where job_id=$1 group by 1",267 job_id)}268 assert st == {"done": 1, "pending": 2}, st269 assert stack.site.state.hits("/err/slow") == 1270 listed = {x["worker_id"]: x for x in (await stack.client.get("/v1/workers")).json()["items"]}271 assert listed[w.worker_id]["state"] == "draining" and listed[w.worker_id]["leased"] == 0272 assert (await stack.client.get(f"/v1/jobs/{job_id}")).json()["status"] == "running"273 r = await stack.client.post(f"/v1/workers/{w.worker_id}/drain", params={"resume": "true"})274 assert r.json()["state"] == "active"275 job = await stack.wait(job_id, timeout=30)276 assert job["status"] == "succeeded" and job["progress"]["urls"] == {"fetched": 3}, job277