From ba849620c9de8ae081959e0c824cdc4e47d19aaf Mon Sep 17 00:00:00 2001 From: Maxi <223365242+maximilianfeix@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:28:39 +0100 Subject: [PATCH 1/4] Second chance for follow-ups that broke off in transport A proxy whose confirm or content request ended in connect_timeout, timeout, connection_closed or no_answer right after a passed basic check gets both follow-ups once more at the end of the run, at least 20 s later. Each proxy is counted once per check, as its last try ended; run.json reports how the second tries ended under checks.second_chance. --- proxyscraper/pipeline.py | 159 ++++++++++++++++++++++++++------------- tests/test_pipeline.py | 79 +++++++++++++++++++ 2 files changed, 187 insertions(+), 51 deletions(-) diff --git a/proxyscraper/pipeline.py b/proxyscraper/pipeline.py index 04dbce59f08b..a670b3404e84 100644 --- a/proxyscraper/pipeline.py +++ b/proxyscraper/pipeline.py @@ -17,7 +17,7 @@ from . import sources as srcs from .asndb import ProviderLookup from .blocklist import Blocklist -from .checker import Checker, CheckResult, other_protocols +from .checker import RETRY_REASONS, Checker, CheckResult, other_protocols from .checkstate import BASIC, CONFIRM, CONTENT, HTTPS, PASSED, SKIPPED, Check, now_iso from .compat import on_interrupt from .fetchcache import FetchCache @@ -33,6 +33,13 @@ # run.json `checks` key for the basic checks of another protocol (see run_checks: protocol fallback) FALLBACK = "fallback" +# A proxy whose confirm or content request broke off in transport (RETRY_REASONS) right after a passed basic check +# gets its follow-ups once more at the end of the run, at least this many seconds later: free proxies drop +# connections for a while and come back. Before, ~350 confirms and ~280 content checks of every hourly run ended +# that way and the proxies were lost, although they had just answered the basic check. +SECOND_CHANCE_DELAY = 20.0 +# run.json `checks` key: how the repeated follow-ups ended ("passed" = the proxy made it into the results) +SECOND_CHANCE = "second_chance" AUTO_DISCOVER_AFTER_DAYS = 1.0 # daily: found sources are kept, so every search adds to the pile # parse small lists directly – the detour through another process costs more than it saves INLINE_PARSE_BYTES = 256 * 1024 @@ -510,6 +517,94 @@ def on_country(ip: str, cc: str) -> None: geo_task = asyncio.ensure_future(geo.run()) watch_task = asyncio.ensure_future(watch.run()) if watch else None + # proxies waiting for their second chance: (when the first try ended, result, job key, listed under it) + deferred: List[Tuple[float, CheckResult, str, bool]] = [] + + def broke_off(r: CheckResult, name: str) -> bool: + check = r.checks.get(name) + return check is not None and check.state != PASSED and check.reason in RETRY_REASONS + + async def follow_up(r: CheckResult, key: str, listed: bool, last_try: bool) -> bool: + """Confirm, content and details of a proxy that passed its basic check. False: a follow-up request broke + off in transport and this wasn't the last try – nothing is recorded, the proxy waits for second_chance.""" + # second, independent request – a proxy that only answers the check request passes the first by chance. + # False only when the request ran and didn't confirm it; an unreachable confirmation target leaves + # the proxy in, marked "unavailable" (r.checks) – it's the target that failed, not the proxy + confirmed = await checker.confirm(r) + if not confirmed and not last_try and broke_off(r, CONFIRM): + return False + if not confirmed: + run.count(r, CONFIRM) + if listed: + run.checked.append(key) + stats.fakes += 1 + return True + # third request: does a known page arrive unchanged? + modified = await checker.tampers(r) + if not modified and not last_try and broke_off(r, CONTENT): + return False + run.count(r, CONFIRM) + run.count(r, CONTENT) + if modified: + if listed: + run.checked.append(key) + stats.tampered += 1 + # the proxy is dropped here, so what was measured about its page is kept as a count + changed = r.checks[CONTENT].data if CONTENT in r.checks else {} + run.changed_pages["with_script_tag" if changed.get("script_tags") else "without_script_tag"] += 1 + return True + if CONFIRM in r.checks and not r.checks[CONFIRM].ok: + stats.confirm_unavailable += 1 + if providers: + providers.annotate(r) + if blocklist: + r.blocklisted = await blocklist.lookup(r.exit_ip) + if listed: + run.checked.append(key) + run.results.append(r) + run.working.add(r.key) + by_exit_ip.setdefault(r.exit_ip, []).append(r) + r.country = geo.request(r.exit_ip) + if r.country: + stats.countries[r.country] += 1 + stats.add_working(r) + if details: + # HTTPS test only if the proxy can still pass the filters at all + if filters.may_pass(r): + await checker.enrich(r) + enriched.add(r.key) + stats.add_details(r) + else: + stats.details_saved += 1 + r.checks[HTTPS] = Check(SKIPPED, "filtered_out", at=now_iso()) + else: + r.checks[HTTPS] = Check(SKIPPED, "fast_mode", at=now_iso()) + run.count(r, HTTPS) + consider(r) + return True + + async def second_chance() -> None: + """Both follow-ups once more for the deferred proxies, each at least SECOND_CHANCE_DELAY after its first + try. This time they count whatever they end as.""" + gate = asyncio.Semaphore(max(1, opts.concurrency)) + outcomes = run.states.setdefault(SECOND_CHANCE, Counter()) + + async def one(item: Tuple[float, CheckResult, str, bool]) -> None: + at, r, key, listed = item + await asyncio.sleep(max(0.0, at + SECOND_CHANCE_DELAY - loop.time())) + async with gate: + await follow_up(r, key, listed, last_try=True) + deferred.remove(item) # what is still in `deferred` after a stop never got its second try + outcomes[PASSED if r.key in run.working else "failed"] += 1 + + tasks = [asyncio.ensure_future(one(item)) for item in list(deferred)] + try: + await asyncio.gather(*tasks) + except asyncio.CancelledError: + for task in tasks: + task.cancel() + raise + async def worker() -> None: nonlocal started_count for key in pending: @@ -539,65 +634,27 @@ async def worker() -> None: run.checked.append(key) # A hit only counts as checked once the verdict is in: a worker cancelled during the next requests # (--want reached, Ctrl+C) must not record a proxy that just worked as a failure. - # second, independent request – a proxy that only answers the check request passes the first by chance. - # False only when the request ran and didn't confirm it; an unreachable confirmation target leaves - # the proxy in, marked "unavailable" (r.checks) – it's the target that failed, not the proxy - confirmed = await checker.confirm(r) - run.count(r, CONFIRM) - if not confirmed: - if listed: - run.checked.append(key) - stats.fakes += 1 - continue - # third request: does a known page arrive unchanged? - modified = await checker.tampers(r) - run.count(r, CONTENT) - if modified: - if listed: - run.checked.append(key) - stats.tampered += 1 - # the proxy is dropped here, so what was measured about its page is kept as a count - changed = r.checks[CONTENT].data if CONTENT in r.checks else {} - run.changed_pages["with_script_tag" if changed.get("script_tags") else "without_script_tag"] += 1 - continue - if CONFIRM in r.checks and not r.checks[CONFIRM].ok: - stats.confirm_unavailable += 1 - if providers: - providers.annotate(r) - if blocklist: - r.blocklisted = await blocklist.lookup(r.exit_ip) - if listed: - run.checked.append(key) - run.results.append(r) - run.working.add(r.key) - by_exit_ip.setdefault(r.exit_ip, []).append(r) - r.country = geo.request(r.exit_ip) - if r.country: - stats.countries[r.country] += 1 - stats.add_working(r) - if details: - # HTTPS test only if the proxy can still pass the filters at all - if filters.may_pass(r): - await checker.enrich(r) - enriched.add(r.key) - stats.add_details(r) - else: - stats.details_saved += 1 - r.checks[HTTPS] = Check(SKIPPED, "filtered_out", at=now_iso()) - else: - r.checks[HTTPS] = Check(SKIPPED, "fast_mode", at=now_iso()) - run.count(r, HTTPS) - consider(r) + if not await follow_up(r, key, listed, last_try=False): + deferred.append((loop.time(), r, key, listed)) with live_factory(dashboard): workers = [asyncio.ensure_future(worker()) for _ in range(min(opts.concurrency, len(jobs)))] all_workers = asyncio.gather(*workers) # Ctrl+C stops cleanly so the results still get saved (on Windows too) - with contextlib.nullcontext() if quiet else on_interrupt(loop, all_workers.cancel): + with contextlib.nullcontext() if quiet else on_interrupt(loop, lambda: all_workers.cancel()): try: await all_workers + if deferred: + all_workers = asyncio.ensure_future(second_chance()) + await all_workers except asyncio.CancelledError: run.interrupted = not run.reached_goal + # stopped before their second chance: they did fail a follow-up, so they end as unconfirmed – the basic + # check counts (check_counts) stay complete + for *_, key, listed in deferred: + if listed: + run.checked.append(key) + stats.fakes += 1 if watch_task: watch_task.cancel() diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 3d15c49f8765..4abf10b025c7 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -443,3 +443,82 @@ def test_prioritize_history_larger_than_limit(tmp_path): history.record_ok(f"http 7.7.7.{i}:80", 100, "7.7.7.7") order = pipeline.prioritize(res, quality, history, ["http"], limit=3, rng=random.Random(5)) assert all(k.startswith("http 7.7.7.") for k in order[:5]) + + +def _second_chance_run(tmp_path, monkeypatch, confirm_plan, content_plan): + """run_checks with a checker whose confirm/content end as the plans say, one entry per try and proxy.""" + import asyncio + import contextlib + + from proxyscraper.checkstate import CONFIRM, CONTENT, FAILED, Check + from proxyscraper.geo import GeoResolver + from proxyscraper.options import RunOptions + from proxyscraper.ui import CheckDashboard, LiveStats + + monkeypatch.setattr(pipeline, "SECOND_CHANCE_DELAY", 0.0) + calls = Counter() + + def outcome(plan, r, name): + calls[(name, r.key)] += 1 + state, reason = plan[r.key][calls[(name, r.key)] - 1] + r.checks[name] = Check(state, reason) + return state + + class StubChecker: + async def check(self, key): + ptype, proxy = key.split(" ") + return CheckResult(key, ptype, proxy, 100, "9.9.9.9") + + async def confirm(self, r): + return outcome(confirm_plan, r, CONFIRM) != FAILED + + async def tampers(self, r): + return outcome(content_plan, r, CONTENT) == FAILED + + async def enrich(self, r): + r.https = True + + async def go(): + jobs = sorted(set(confirm_plan)) + stats = LiveStats({"http": len(jobs)}) + writer = output.ResultWriter(run_dir=tmp_path / "run") + dashboard = CheckDashboard(stats, writer.live_path, len(jobs), True) + run = await pipeline.run_checks(jobs, StubChecker(), RunOptions(no_geo=True), dashboard, writer, + GeoResolver(enabled=False), live_factory=lambda _: contextlib.nullcontext()) + return run, stats + + run, stats = asyncio.run(go()) + return run, stats, calls + + +def test_follow_ups_that_broke_off_get_a_second_chance(tmp_path, monkeypatch): + ok, drop, flaky, gone = "http 1.1.1.1:80", "http 2.2.2.2:80", "http 3.3.3.3:80", "http 4.4.4.4:80" + passed = ("passed", "") + confirm_plan = { + ok: [passed], + drop: [("failed", "exit_ip_mismatch")], # a real verdict: no second try + flaky: [("failed", "connect_timeout"), passed], # broke off, works a little later + gone: [passed, passed], + } + content_plan = {ok: [passed], flaky: [passed], gone: [("unavailable", "timeout"), ("unavailable", "timeout")]} + run, stats, calls = _second_chance_run(tmp_path, monkeypatch, confirm_plan, content_plan) + + assert sorted(r.key for r in run.results) == [ok, flaky, gone] + assert calls[("confirm", drop)] == 1 and calls[("confirm", flaky)] == 2 and calls[("content", gone)] == 2 + assert calls[("confirm", ok)] == 1 # nothing to repeat + # every proxy is counted once per check, as its last try ended + assert run.states["confirm"] == Counter({"passed": 3, "failed:exit_ip_mismatch": 1}) + assert run.states["content"] == Counter({"passed": 2, "unavailable:timeout": 1}) + assert run.states[pipeline.SECOND_CHANCE] == Counter({"passed": 2}) + assert stats.fakes == 1 and stats.found == 3 + assert sorted(run.checked) == sorted([ok, drop, flaky, gone]) + + +def test_second_chance_failure_counts_once(tmp_path, monkeypatch): + key = "http 5.5.5.5:80" + plan = {key: [("failed", "connect_timeout"), ("failed", "timeout")]} + run, stats, calls = _second_chance_run(tmp_path, monkeypatch, plan, {}) + assert run.results == [] and calls[("confirm", key)] == 2 + assert run.states["confirm"] == Counter({"failed:timeout": 1}) + assert run.states[pipeline.SECOND_CHANCE] == Counter({"failed": 1}) + assert stats.fakes == 1 and run.checked == [key] From 3967319e59eb6095cb7f1b770b83d55fc5be77ca Mon Sep 17 00:00:00 2001 From: Maxi <223365242+maximilianfeix@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:50:17 +0100 Subject: [PATCH 2/4] Hourly run: 10 s timeout; document the second chance A/B on 12 Nov: 768 -> 986 listed proxies with the second chance, 1,177 with both. --- .github/workflows/proxy-list.yml | 4 ++-- CHANGELOG.md | 5 +++++ docs/check-states.md | 9 ++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/workflows/proxy-list.yml b/.github/workflows/proxy-list.yml index 28c329061dd3..4eb768d5eca7 100644 --- a/.github/workflows/proxy-list.yml +++ b/.github/workflows/proxy-list.yml @@ -2,7 +2,7 @@ name: proxy list on: schedule: - - cron: "17 * * * *" # every hour – a full run takes about 3 minutes + - cron: "17 * * * *" # every hour – the checks take about 5–6 minutes workflow_dispatch: permissions: @@ -38,7 +38,7 @@ jobs: - name: Collect and check proxies env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # for the GitHub discovery - run: python proxy_scraper.py -y --limit 150000 --timeout 6 --connect-timeout 4 + run: python proxy_scraper.py -y --limit 150000 --timeout 10 --connect-timeout 4 # Google, Reddit, Amazon, Instagram, TikTok and Discord turn many free proxies away – note which got through (~2 min). # Optional: if it fails, the list is published without it. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fb8443348fc..84ef5919e179 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project are listed here. The format follows [Keep a ## [Unreleased] +### Changed +- **A proxy whose second or content request broke off in transport gets a second chance at the end of the run.** Free proxies drop connections for a while: in every hourly run about 350 confirms and 280 content checks ended in `connect_timeout`, `timeout`, `connection_closed` or `no_answer` right after the proxy had passed its basic check (and after the retry 1.5 s later), and those proxies were lost. Now they get both requests once more at the end of the run, at least 20 seconds after their try, and count with whatever those end as. `checks.second_chance` in `run.json` says how the second chances ended +- **The hourly run gives a request 10 seconds instead of 6** (`--timeout 10`; the connect stays at 4 s). Free proxies are slow – the median latency of the list is above 2 seconds – and ~10,000 candidates a run connected but answered after the 6 seconds. The check phase takes about 5–6 minutes instead of 3–5 +- Measured in A/B runs on 12 Nov 2026 (runners started at the same time, 150,000 candidates each): the hourly list grew from 768 proxies (as before) to 986 with the second chance and to 1,177 with both. A 15-second timeout gave 6 % more than 10 seconds with a slower list; six new self-checking sources found by a source search gave 3 more proxies – their proxies are in the existing lists already – and were not added. The hourly list still swings with one backconnect gateway (45.74.31.40–47, ~230,000 listed addresses): when it is up, a run lists 2,000–2,500 proxies, otherwise around 1,000–1,200. Checking all its addresses instead of 150,000 candidates gave 537 instead of 323 on 12 Nov, and a run without the 150,000 limit 1,111 instead of 1,095 – the limit isn't what holds the list back + ## [1.33.1] – 2026-11-11 ### Changed diff --git a/docs/check-states.md b/docs/check-states.md index c3ccfe2f4428..65182946cbce 100644 --- a/docs/check-states.md +++ b/docs/check-states.md @@ -99,7 +99,9 @@ A second or content request that httpbin.org's rate limit held back (`target_rat The fallback targets are asked directly once when a run starts. Without an IP address from the echo, or without a reference page from either site, there is no fallback for that check and it stays `unavailable:target_rate_limited`. A failed fallback request is checked against the fallback target asked directly, like the other later checks. Each fallback target has its own pacing of 20 requests per second per exit IP; if that is overbooked too, or the fallback answers 429 with rate-limit headers, the check stays `unavailable:target_rate_limited` (with the fallback as its `target`). Only the overflow goes there – a few hundred requests an hour in the hourly run. ipv4.icanhazip.com (Cloudflare) documents no limit; example.com is IANA's, served best effort and not meant for production use, which is why it has a reserve. In a measurement on 11 Nov 2026, 39 parallel requests through 13 proxies sharing one exit got 78 of 78 HTTP 429 from httpbin.org, and 78 of 78 correct answers from each fallback target. -The second and the content request go to a proxy that has just answered the first one, so a connection that doesn't come about there is more often a lost packet than a dead proxy. They connect with at least 6 seconds (more if `--connect-timeout` is higher); the time they get after the connect stays the same, so their whole limit grows by the difference (8 seconds instead of 6 in the hourly run, `--timeout 6 --connect-timeout 4`). A request that failed in transport – `connect_timeout`, `timeout`, `connection_closed` or `no_answer` – is tried once more after 1.5 seconds, through the same pacing and 429 handling; the check records only how the last try ended. An answer that was the problem – another exit IP, a status other than 200, a wrong or changed page – is not tried again. Worst case, a proxy's second request can now take about 28.5 seconds instead of 15 in the hourly run (three tries of 8 seconds, the pause and a `Retry-After`), plus the wait for its slot; so can the content request. +The second and the content request go to a proxy that has just answered the first one, so a connection that doesn't come about there is more often a lost packet than a dead proxy. They connect with at least 6 seconds (more if `--connect-timeout` is higher); the time they get after the connect stays the same, so their whole limit grows by the difference (12 seconds instead of 10 in the hourly run, `--timeout 10 --connect-timeout 4`). A request that failed in transport – `connect_timeout`, `timeout`, `connection_closed` or `no_answer` – is tried once more after 1.5 seconds, through the same pacing and 429 handling; the check records only how the last try ended. An answer that was the problem – another exit IP, a status other than 200, a wrong or changed page – is not tried again. Worst case, a proxy's second request can take about 40.5 seconds in the hourly run (three tries of 12 seconds, the pause and a `Retry-After`), plus the wait for its slot; so can the content request. + +**Second chance.** If the second or the content request still broke off in transport (the same four reasons), nothing is recorded yet: at the end of the run, at least 20 seconds after that try, the proxy gets both requests once more, and then counts with whatever they end as – once per check, as in any other run. Free proxies drop connections for a while and come back: in an A/B run on 12 Nov 2026 (two runners at the same time, 150,000 candidates each) 296 of 828 proxies passed on their second chance, and the list grew from 768 to 986 proxies. `checks.second_chance` in `run.json` says how the second chances ended (`passed`: the proxy is in the results). ## What a list requires @@ -127,12 +129,13 @@ Every run writes `run.json` next to its results, and the hourly list publishes i "checks": {"basic": {"failed:connect_refused": 30122, "failed:connect_timeout": 101220, "passed": 2391}, "confirm": {"failed:bad_status": 919, "failed:exit_ip_mismatch": 311, "passed": 1161}, "content": {"failed:content_mismatch": 57, "passed": 1104}, - "https": {"failed:tunnel_refused": 398, "passed": 706}}, + "https": {"failed:tunnel_refused": 398, "passed": 706}, + "second_chance": {"failed": 532, "passed": 296}}, "fallback": {"tried": 4210, "found": 52}, "changed_pages": {"with_script_tag": 21, "without_script_tag": 36}} ``` -The numbers in this example are made up to show the shape. `candidates` are the proxies the run set out to check, `checked` the ones that got a verdict, `not_checked` the rest (stopped by `--want` or Ctrl+C, or this machine ran out of sockets: `no_verdict_local`). `changed_pages` splits the content mismatches by whether the page that came back contains a ` Date: Thu, 12 Nov 2026 08:58:12 +0100 Subject: [PATCH 3/4] test: the hourly run's 10 s timeout --- tests/test_workflow_ci.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_workflow_ci.py b/tests/test_workflow_ci.py index 8159f8e409e2..df8bb661ef73 100644 --- a/tests/test_workflow_ci.py +++ b/tests/test_workflow_ci.py @@ -150,7 +150,8 @@ def test_the_hourly_run_gives_the_basic_connect_four_seconds(): steps = workflow("proxy-list.yml")["jobs"] run = next(step["run"] for job in steps.values() for step in job["steps"] if "proxy_scraper.py" in str(step.get("run", ""))) - assert "--timeout 6 --connect-timeout 4" in run + # and the whole request 10 s: ~10,000 candidates a run answered after 6 s (A/B on 12 Nov 2026) + assert "--timeout 10 --connect-timeout 4" in run def test_codeql_leaves_the_tests_out_through_its_config_file(): From 01dd46e97d7eb659e85ca9cb74c4ca8a0b1de826 Mon Sep 17 00:00:00 2001 From: Maxi <223365242+maximilianfeix@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:07:05 +0100 Subject: [PATCH 4/4] Second chance: count a stopped proxy once; recheck after a switch in phase 2 - the deferred entry leaves the list when its verdict is recorded, not after the HTTPS test: --want reached during another proxy's enrich counted that proxy as working and unconfirmed - a check target switch during the second chances requeued basic checks that no worker took anymore: workers run again until queue and deferred are empty - checks.second_chance only appears once a second chance ended --- docs/check-states.md | 2 +- proxyscraper/pipeline.py | 43 +++++++++++++++++++--------- tests/test_judges.py | 61 ++++++++++++++++++++++++++++++++++++++++ tests/test_pipeline.py | 48 +++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+), 14 deletions(-) diff --git a/docs/check-states.md b/docs/check-states.md index 65182946cbce..3008f48dc166 100644 --- a/docs/check-states.md +++ b/docs/check-states.md @@ -101,7 +101,7 @@ The fallback targets are asked directly once when a run starts. Without an IP ad The second and the content request go to a proxy that has just answered the first one, so a connection that doesn't come about there is more often a lost packet than a dead proxy. They connect with at least 6 seconds (more if `--connect-timeout` is higher); the time they get after the connect stays the same, so their whole limit grows by the difference (12 seconds instead of 10 in the hourly run, `--timeout 10 --connect-timeout 4`). A request that failed in transport – `connect_timeout`, `timeout`, `connection_closed` or `no_answer` – is tried once more after 1.5 seconds, through the same pacing and 429 handling; the check records only how the last try ended. An answer that was the problem – another exit IP, a status other than 200, a wrong or changed page – is not tried again. Worst case, a proxy's second request can take about 40.5 seconds in the hourly run (three tries of 12 seconds, the pause and a `Retry-After`), plus the wait for its slot; so can the content request. -**Second chance.** If the second or the content request still broke off in transport (the same four reasons), nothing is recorded yet: at the end of the run, at least 20 seconds after that try, the proxy gets both requests once more, and then counts with whatever they end as – once per check, as in any other run. Free proxies drop connections for a while and come back: in an A/B run on 12 Nov 2026 (two runners at the same time, 150,000 candidates each) 296 of 828 proxies passed on their second chance, and the list grew from 768 to 986 proxies. `checks.second_chance` in `run.json` says how the second chances ended (`passed`: the proxy is in the results). +**Second chance.** If the second or the content request still broke off in transport (the same four reasons), nothing is recorded yet: at the end of the run, at least 20 seconds after that try, the proxy gets both requests once more, and then counts with whatever they end as – once per check, as in any other run. Free proxies drop connections for a while and come back: in an A/B run on 12 Nov 2026 (two runners at the same time, 150,000 candidates each) 296 of 828 proxies passed on their second chance, and the list grew from 768 to 986 proxies. `checks.second_chance` in `run.json` says how the second chances ended (`passed`: the proxy is in the results). A proxy still waiting for its second chance when a run stops (`--want` reached, Ctrl+C) counts as checked and unconfirmed: it did fail a follow-up. ## What a list requires diff --git a/proxyscraper/pipeline.py b/proxyscraper/pipeline.py index a670b3404e84..a20e2f5b8050 100644 --- a/proxyscraper/pipeline.py +++ b/proxyscraper/pipeline.py @@ -40,6 +40,8 @@ SECOND_CHANCE_DELAY = 20.0 # run.json `checks` key: how the repeated follow-ups ended ("passed" = the proxy made it into the results) SECOND_CHANCE = "second_chance" +# a proxy waiting for its second chance: (when its first try ended, its result, the job key, listed under that key) +Deferred = Tuple[float, CheckResult, str, bool] AUTO_DISCOVER_AFTER_DAYS = 1.0 # daily: found sources are kept, so every search adds to the pile # parse small lists directly – the detour through another process costs more than it saves INLINE_PARSE_BYTES = 256 * 1024 @@ -517,16 +519,23 @@ def on_country(ip: str, cc: str) -> None: geo_task = asyncio.ensure_future(geo.run()) watch_task = asyncio.ensure_future(watch.run()) if watch else None - # proxies waiting for their second chance: (when the first try ended, result, job key, listed under it) - deferred: List[Tuple[float, CheckResult, str, bool]] = [] + deferred: List[Deferred] = [] # proxies waiting for their second chance def broke_off(r: CheckResult, name: str) -> bool: check = r.checks.get(name) return check is not None and check.state != PASSED and check.reason in RETRY_REASONS - async def follow_up(r: CheckResult, key: str, listed: bool, last_try: bool) -> bool: + async def follow_up(r: CheckResult, key: str, listed: bool, last_try: bool, + item: Optional[Deferred] = None) -> bool: """Confirm, content and details of a proxy that passed its basic check. False: a follow-up request broke - off in transport and this wasn't the last try – nothing is recorded, the proxy waits for second_chance.""" + off in transport and this wasn't the last try – nothing is recorded, the proxy waits for second_chance. + item: its entry in `deferred` (on the second chance), taken out as soon as the verdict is recorded – a + stop after that must not count the proxy again.""" + + def recorded() -> None: + if item is not None: + deferred.remove(item) + # second, independent request – a proxy that only answers the check request passes the first by chance. # False only when the request ran and didn't confirm it; an unreachable confirmation target leaves # the proxy in, marked "unavailable" (r.checks) – it's the target that failed, not the proxy @@ -534,6 +543,7 @@ async def follow_up(r: CheckResult, key: str, listed: bool, last_try: bool) -> b if not confirmed and not last_try and broke_off(r, CONFIRM): return False if not confirmed: + recorded() run.count(r, CONFIRM) if listed: run.checked.append(key) @@ -543,6 +553,7 @@ async def follow_up(r: CheckResult, key: str, listed: bool, last_try: bool) -> b modified = await checker.tampers(r) if not modified and not last_try and broke_off(r, CONTENT): return False + recorded() run.count(r, CONFIRM) run.count(r, CONTENT) if modified: @@ -587,15 +598,14 @@ async def second_chance() -> None: """Both follow-ups once more for the deferred proxies, each at least SECOND_CHANCE_DELAY after its first try. This time they count whatever they end as.""" gate = asyncio.Semaphore(max(1, opts.concurrency)) - outcomes = run.states.setdefault(SECOND_CHANCE, Counter()) - async def one(item: Tuple[float, CheckResult, str, bool]) -> None: + async def one(item: Deferred) -> None: at, r, key, listed = item await asyncio.sleep(max(0.0, at + SECOND_CHANCE_DELAY - loop.time())) async with gate: - await follow_up(r, key, listed, last_try=True) - deferred.remove(item) # what is still in `deferred` after a stop never got its second try - outcomes[PASSED if r.key in run.working else "failed"] += 1 + await follow_up(r, key, listed, last_try=True, item=item) + outcome = PASSED if r.key in run.working else "failed" + run.states.setdefault(SECOND_CHANCE, Counter())[outcome] += 1 tasks = [asyncio.ensure_future(one(item)) for item in list(deferred)] try: @@ -644,13 +654,20 @@ async def worker() -> None: with contextlib.nullcontext() if quiet else on_interrupt(loop, lambda: all_workers.cancel()): try: await all_workers - if deferred: - all_workers = asyncio.ensure_future(second_chance()) + # the second chances take 20 s and more: a check target switch in that time puts basic checks + # back into the queue (requeue), and nobody would take them out – so: workers again until both + # are empty + while deferred or pending.retry: + if pending.retry: + all_workers = asyncio.gather(*(asyncio.ensure_future(worker()) + for _ in range(min(opts.concurrency, len(pending.retry))))) + else: + all_workers = asyncio.ensure_future(second_chance()) await all_workers except asyncio.CancelledError: run.interrupted = not run.reached_goal - # stopped before their second chance: they did fail a follow-up, so they end as unconfirmed – the basic - # check counts (check_counts) stay complete + # stopped before their second chance was recorded: they did fail a follow-up, so they end as unconfirmed – + # the basic check counts (check_counts) stay complete for *_, key, listed in deferred: if listed: run.checked.append(key) diff --git a/tests/test_judges.py b/tests/test_judges.py index 61ff71546073..5845dd546553 100644 --- a/tests/test_judges.py +++ b/tests/test_judges.py @@ -452,3 +452,64 @@ async def go(): asyncio.run(go()) assert asked == ["1.1.1.1"] + + +def test_switch_during_the_second_chances_still_rechecks(tmp_path, monkeypatch): + """The second chances run after the workers: a check target switch then must still repeat the failures of + the outage – there is no worker left to take them from the queue unless run_checks starts one.""" + from proxyscraper.checkstate import CONFIRM, CONTENT, Check + + monkeypatch.setattr(pipeline, "SECOND_CHANCE_DELAY", 0.0) + victim, flaky = "http 1.1.1.1:80", "http 2.2.2.2:80" + + class StubWatch: + on_ok = on_switch = None + + async def run(self): + self.on_ok() + await asyncio.sleep(3600) + + watch = StubWatch() + + class Checker: + def __init__(self): + self.down = True + self.confirms = 0 + + async def check(self, key): + if key == victim and self.down: + return None # falls into the outage + ptype, proxy = key.split(" ") + return CheckResult(key, ptype, proxy, 100, "9.9.9.9") + + async def confirm(self, r): + self.confirms += 1 + if self.confirms == 1: + r.checks[CONFIRM] = Check("failed", "connect_timeout") + return False + if self.down: # during the second chance the watchdog notices the outage + self.down = False + watch.on_switch(JudgeProbe(Judge("a"), "1.1.1.1", 1), JudgeProbe(Judge("b"), "2.2.2.2", 1)) + r.checks[CONFIRM] = Check("passed", "") + return True + + async def tampers(self, r): + r.checks[CONTENT] = Check("passed", "") + return False + + async def enrich(self, r): + r.https = True + + async def go(): + jobs = [victim, flaky] + stats = LiveStats({"http": 2}) + writer = output.ResultWriter(run_dir=tmp_path / "run") + dashboard = CheckDashboard(stats, writer.live_path, 1, True) + run = await pipeline.run_checks(jobs, Checker(), RunOptions(no_geo=True, concurrency=1), dashboard, writer, + GeoResolver(enabled=False), live_factory=lambda _: contextlib.nullcontext(), + watch=watch) + return run + + run = asyncio.run(go()) + assert run.working == {victim, flaky} + assert sorted(run.checked) == [victim, flaky] and run.rechecked == 1 diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 4abf10b025c7..475ba53f6720 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -522,3 +522,51 @@ def test_second_chance_failure_counts_once(tmp_path, monkeypatch): assert run.states["confirm"] == Counter({"failed:timeout": 1}) assert run.states[pipeline.SECOND_CHANCE] == Counter({"failed": 1}) assert stats.fakes == 1 and run.checked == [key] + + +def test_goal_reached_during_second_chance_counts_every_proxy_once(tmp_path, monkeypatch): + """--want reached in one second chance while another is in its HTTPS test: the cut-off one must not end + as working and unconfirmed at once.""" + import asyncio + import contextlib + + from proxyscraper.checkstate import CONFIRM, CONTENT, Check + from proxyscraper.geo import GeoResolver + from proxyscraper.options import RunOptions + from proxyscraper.ui import CheckDashboard, LiveStats + + monkeypatch.setattr(pipeline, "SECOND_CHANCE_DELAY", 0.0) + keys = ["http 1.1.1.1:80", "http 2.2.2.2:80"] + calls = Counter() + + class StubChecker: + async def check(self, key): + ptype, proxy = key.split(" ") + return CheckResult(key, ptype, proxy, 100, "9.9.9.9") + + async def confirm(self, r): + calls[r.key] += 1 + first = calls[r.key] == 1 + r.checks[CONFIRM] = Check("failed", "connect_timeout") if first else Check("passed", "") + return not first + + async def tampers(self, r): + r.checks[CONTENT] = Check("passed", "") + return False + + async def enrich(self, r): + await asyncio.sleep(1 if r.key == keys[1] else 0.1) + r.https = True + + async def go(): + stats = LiveStats({"http": 2}) + writer = output.ResultWriter(run_dir=tmp_path / "run") + dashboard = CheckDashboard(stats, writer.live_path, 2, True) + run = await pipeline.run_checks(keys, StubChecker(), RunOptions(no_geo=True, want=1), dashboard, writer, + GeoResolver(enabled=False), live_factory=lambda _: contextlib.nullcontext()) + return run, stats + + run, stats = asyncio.run(go()) + assert run.reached_goal + assert stats.found + stats.fakes == 2 + assert sorted(run.checked) == keys