Skip to content

fix(web): give page fetches and downloads an overall deadline - #5384

Merged
kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:claude/rel-j-fetch-deadline
Oct 19, 2026
Merged

kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:claude/rel-j-fetch-deadline

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Fetching a web page or downloading a file had no overall deadline. A server that sent one byte at a time, each just inside the 30 s read timeout, kept the fetch, and the chat turn behind it, running for hours or days. Now a page fetch is stopped after 120 s and a download after 30 minutes, with an error saying the server is too slow. The limit covers every redirect, the connection, the headers and the body, including through a proxy. A normal fetch is unaffected.

Reproduced by tests/unit/test_web_client_fetch_deadline.py, which runs against local servers that trickle bytes; it fails on main and passes here.

🔍 Technical details
  • A _Deadline timer runs for each WebClient._request and download. When it fires, it shuts down the socket the calling thread is blocked on. The adapter's urllib3 connection classes register that socket when it is created and while headers are read. The response's own socket is registered once headers arrive. Without the shutdown, a chunk read waits for a full 8 KB, which at a byte per read timeout takes hours.
  • A socket or response that appears after the deadline fired (it passed during DNS or connect) is aborted as soon as it arrives.
  • Each hop's read timeout is capped by the time left, and so is a caller's timeout, whether a number or a pair. A read that fails within 250 ms of the deadline counts as the deadline: the capped timeout often beats the timer thread by a few ms, especially on a loaded machine. A test pins this tolerance, and another pins that the rate-limit wait stays outside the deadline.
  • proxy_manager_for gives proxy managers tracked pools built from their own pool classes, so a SOCKS proxy keeps its SOCKS pools, and its deadline (tested through a local SOCKS5 relay, which needs PySocks and is skipped without it).
  • FetchDeadlineExceeded subclasses requests.exceptions.Timeout. The browser tools show its message through their generic error handler. Only transport failures (requests, OSError, http.client, urllib3) are relabelled as the deadline, so a blocked address or a bug still reports itself.
  • fetch_deadline / download_deadline are constructor options. A redirect to a new domain waits up to rate_limit (1 s) inside the deadline.
  • Charset detection (apparent_encoding) now runs after the body read, because it reads response.content and would otherwise pull the body outside the deadline. A test pins the read order.
  • The tests cover:
    • a timer running 300 ms late;
    • a deadline passing during DNS;
    • a proxy that trickles one header byte at a time;
    • a trickled TLS handshake;
    • a timer that fires after its fetch ended and must leave the next request's socket alone.

Test plan

  • python -m pytest tests/unit/test_web_client_fetch_deadline.py tests/unit/test_web_client_edge_cases.py tests/unit/test_web_client_ip_pinning.py tests/unit/test_browser_tools.py tests/unit/test_chat_inline_web_ssrf.py tests/unit/test_skill_capture.py tests/unit/test_tavily_wrapper.py tests/unit/eval/test_tiers_skills_web_fixtures.py: 302 passed and 2 skipped (SOCKS, without PySocks), three runs in a row; with PySocks on the path the SOCKS tests pass too
  • Against the previous head, the late-timer, DNS and proxy tests fail on the symptom (a raw ConnectionError, or a fetch still running after 20 s), and so do the SOCKS tests (TypeError on _socks_options) and the blocked-address test (reported as a slow server)
  • docs/spec/browser-tools.mdx lists the read timeout and both deadlines
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes
  • tests/integration/test_web_client_live_sni.py in CI (live HTTPS through the changed pool classes)

The request timeout bounds each socket read, so a server that sent a byte
just inside it, again and again, kept a page fetch or a download running
indefinitely and held the tool call, and the turn, with it.

A page fetch now has 120 s overall, across every redirect hop and the body,
and a download 1800 s; both are constructor options. Each hop's read timeout
is capped by what is left, and a timer unblocks a body read that is stuck
waiting for a chunk when the deadline passes. The error, FetchDeadlineExceeded,
is a requests Timeout, so existing handlers show it. Charset detection now
runs after the body read so it cannot pull the body outside that read.
The first version only bounded the body: a server that trickled its
headers still held a fetch for days, and a caller's own timeout replaced
the cap. One deadline timer now covers the whole fetch or download. The
adapter's connections register their socket while reading headers, so the
timer can unblock that read too, and a caller timeout, number or pair, is
capped by the time left.
…uest

Timer.cancel() cannot stop a callback that has already started, so a
deadline expiring just as its fetch finished could shut down the socket of
the same thread's next request. Exit now marks the deadline done under the
registry lock and the callback checks it. A urllib3 Timeout passed as the
caller's timeout is passed through rather than raising TypeError.
… mixin

pylint could not resolve the mixin's self.sock and super().getresponse.
@github-actions github-actions Bot added the tests Test changes label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

A web server that sends data very slowly can no longer keep a page fetch or download, and the chat turn waiting on it, running for hours. Page fetches now stop after 120 s and downloads after 30 minutes, with a clear "server too slow" error. The deadline covers redirects, slow headers and slow bodies, and the new tests run against a real local server that sends a byte at a time. I found no blocking issues.

Worth knowing before merge:

  • The timing tests may be flaky. The test plan mentions one failure in about 20 runs that couldn't be explained. A flaky test in the unit lane is worth pinning down now, while the change is fresh.
  • Fetches through a proxy only get part of the fix, as the PR says. A body that arrives slowly is still bounded, but a slow header phase isn't. That's fine to defer; a follow-up issue would keep it from being forgotten.

Real-world evidence

N/A: this changes the internal web client behind the agent's fetch and download tools. No CLI, REST or UI surface changed, and no evidence bundle was produced. The verdict rests on reading the code plus the PR's local-server tests. I couldn't run those tests here because pytest isn't installed on this runner.

🔍 Technical details

Issues found

🟢 Timing-sensitive tests; a 1-in-20 failure is unexplained (tests/unit/test_web_client_fetch_deadline.py)
The tests depend on wall-clock timing (fetch_deadline=1, a 50 ms trickle, elapsed < 8/10). One race could explain the failure. If the timer fires after send() returns but before deadline.watch(response), the header socket is already unregistered and no response is attached yet, so _fire shuts down nothing. The read then ends only when the capped read timeout expires or the next chunk arrives. That's still bounded, but on a slow CI box it could push past the test's elapsed limits or end without the expected error. Worth reproducing with pytest --count (or a loop) before merge.

🟢 The no-deadline branch in _consume_body_capped is dead code (src/gaia/web/client.py:749-777)
Both production callers now pass deadline. The only other caller is test_web_client_edge_cases.py:780, which reaches it through get() and so also has a deadline. Making deadline required and dropping the iter_content branch would remove a path that skips the deadline and that a future caller could hit by mistake.

🟢 Proxy gap (PinnedIPAdapter.init_poolmanager)
proxy_manager_for builds stock pools, so headers that arrive slowly through a proxy are bounded per read only. The PR documents this. A tracking issue would make sure it gets followed up.

Checked and fine

  • FetchDeadlineExceeded subclasses requests.exceptions.Timeout. The browser tool's generic except Exception (browser_tools.py:185) shows its message, and the existing Timeout handlers (cli.py:679, tui_mcp.py:343) catch it as a timeout.
  • _done is checked under _HEADER_READS_LOCK, so a callback that is already running can't shut down the next request's socket. There's a test for this.
  • A shut-down socket doesn't go back into the pool: urllib3 closes the connection after an error in getresponse, and response.close() closes the body path.
  • Moving apparent_encoding to after _consume_body_capped is correct. Otherwise response.content would read the body outside the deadline.
  • A download's .part file is removed when it hits the deadline (tested).

Strengths

  • The tests run against a real local server that sends a byte at a time, not mocks. They cover slow headers, a silent body, redirects and a caller-supplied timeout.
  • The per-hop read timeout is capped by the time left, and the timer is a backstop for reads that never return. Both bounds are needed, and the comments explain why.
  • The rate-limit wait is excluded from the deadline, so the deadline only measures time spent waiting on the server.

…or behind a proxy

Review follow-ups.

- A read whose timeout was cut to the time left often failed a few ms
  before the timer thread ran, so the user got a raw ReadTimeout wrapped in
  ConnectionError instead of the deadline error. A failure within 250 ms of
  the deadline now counts as the deadline.
- A deadline that passed before any socket existed (slow DNS, or connect)
  never stopped the reads that came after it. A socket registered, or a
  response watched, after the deadline fired is now aborted on arrival, and
  sockets are tracked from creation, not only while headers are read.
- Requests sent through a proxy used stock pools, so slow headers there
  were bounded per read only. The adapter's proxy managers now use the
  tracked pools too.
- Tests cover a timer running 300 ms late, a deadline passing during DNS,
  a proxy trickling one header byte at a time, a trickled TLS handshake,
  and the read order of the body.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 Fetches through a SOCKS proxy would now skip the proxy and connect directly. The latest push gives proxied requests the deadline-tracked connection pools, but it does this by replacing the proxy manager's pool classes. For an HTTP proxy that's harmless. A SOCKS proxy (for example ALL_PROXY=socks5://…, which requests picks up from the environment) does its proxying inside those pool classes, so swapping them out sends every fetch straight to the target site. That breaks fetches on networks that only allow traffic through the proxy, and it exposes the user's real IP when they rely on the proxy for privacy. Please leave SOCKS managers alone, or give them tracked SOCKS pool subclasses, and add a test that a SOCKS proxy is still used.

🔍 Technical details

src/gaia/web/client.py, PinnedIPAdapter.proxy_manager_for: manager.pool_classes_by_scheme = dict(_TRACKED_POOLS) is applied to whatever super().proxy_manager_for() returns. For socks* proxies, requests builds a urllib3.contrib.socks.SOCKSProxyManager. Its pool_classes_by_scheme is {SOCKSHTTPConnectionPool, SOCKSHTTPSConnectionPool}, and those classes' SOCKSConnection._new_conn performs the SOCKS handshake. Replacing them with _TrackedHTTP(S)ConnectionPool means _new_conn opens a plain TCP socket to the destination.

Minimal fix: only override when the manager is not a SOCKS manager.

def proxy_manager_for(self, proxy, **proxy_kwargs):
    manager = super().proxy_manager_for(proxy, **proxy_kwargs)
    if not proxy.lower().startswith("socks"):
        manager.pool_classes_by_scheme = dict(_TRACKED_POOLS)
    return manager

That leaves SOCKS headers bounded only per read, the same gap HTTP proxies had before this push. Tracked subclasses of the SOCKS pools would close it fully.

kovtcharov-amd and others added 2 commits October 18, 2026 23:20
pypi.org/simple/ is a ~47 MB page. The live test passed before only because
charset detection read the whole body ahead of the 10 MB cap; now that the
capped read runs first, the fetch is correctly rejected. One project's index
still proves the SNI handshake with PyPI's CDN.
…s a deadline

Round-2 review follow-ups.

- Replacing the pool classes on every proxy manager broke SOCKS: the SOCKS
  manager's pools take options the plain pools reject, so every fetch
  through a SOCKS proxy failed with a TypeError. Tracked pools are now built
  from whichever pool classes the manager uses, so SOCKS keeps working and
  keeps the deadline. Tested through a local SOCKS5 relay (needs PySocks,
  skipped without it).
- Any exception after the deadline was relabelled "server too slow",
  including a blocked address or a bug. Only transport failures (requests,
  OSError, http.client, urllib3) are; a closed-file error counts only while
  a body was being read and the timer had fired.
- Tests pin the 250 ms tolerance and that the rate-limit wait stays outside
  the deadline.
- docs/spec/browser-tools.mdx lists the read timeout, fetch deadline and
  download deadline.
@github-actions github-actions Bot added the documentation Documentation changes label Oct 19, 2026
Both callers pass one, so the branch that read without a deadline was dead
and a future caller could have used it by mistake.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 3906fa0 Oct 19, 2026
32 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-j-fetch-deadline branch October 19, 2026 16:36
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

<details>
<summary>🔍 Technical details</summary>

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants