Repository navigation
Retry a timed-out mainland China fetch once through the proxy - #100
Conversation
Government sites in mainland China drop requests from Cloudflare's datacenter addresses but answer a residential connection abroad within a second: six URLs that timed out for the main signed-in user returned from a US home connection in 0.2-1.2 s and still time out through production. After the 10 s static timeout, signed-in requests now retry through the proxy; anonymous ones go through the daily budget and the refused-host record. The timeout message blamed fetching from outside China; it now says the site does not answer requests from cloud servers.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
website2markdown | 25c7555 | Nov 21 2026, 09:06 AM |
The pool tries each proxy with two header variants at 25 s each, so one unanswering proxy could keep a request open past a minute. The retry now has a 20 s deadline, ending the request within about 30 s. The proxy does not follow redirects, so after a redirect it asked for the entry URL instead of the page that timed out. fetchWithSafeRedirects now reports the failing hop on its error, and the retry uses it.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d67799fe30
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ? await tryDirectProxyFetch(resolvedUrl, env, fallbacks, deadline.signal, progress) | ||
| : await tryAnonymousProxy(resolvedUrl, env, fallbacks, deadline.signal, progress); |
There was a problem hiding this comment.
Record proxy deadline expirations as provider failures
When the proxy does not answer within the new 20-second deadline, passing deadline.signal through these helpers causes trackProvider to treat the timeout as a caller cancellation: src/observability/provider-attempts.ts:45–46 skips recording failures whenever its signal is aborted. Because this deadline expires before the proxy's own 25-second timeout, stalled mainland retries are systematically excluded from provider health statistics and failure-rate alerts, even though callers receive 504 responses. Distinguish the internal deadline from the caller's cancellation signal when recording provider outcomes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit: when the 20 s deadline (not the caller) ends a retry that found nothing, it is recorded as a proxy_pool failure. The deadline test checks the recorded failure.
trackProvider skips attempts whose signal was aborted, treating them as caller cancellations, so stalled mainland retries never reached the provider stats. When the 20 s deadline, not the caller, ends a retry that found nothing, record it as a proxy_pool failure.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 034701de79
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (viaProxy) { | ||
| return { | ||
| finalHtml: viaProxy, | ||
| method: "proxy+readability+turndown", |
There was a problem hiding this comment.
Preserve forced rendering after a successful proxy retry
When an authenticated caller requests force_browser=true for a mainland host and the direct fetch times out, a successful proxy retry returns here before reaching the browserAllowed && (forceBrowser || ...) rendering stage later in tryStaticFetch. The proxy only fetches HTML; it does not execute JavaScript. Consequently, a sufficiently large JavaScript shell can be accepted and converted into incomplete page content despite the explicit rendering request. Route recovered HTML through the rendering decision instead of returning immediately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit: a page recovered through the proxy now goes through the same browser decision (force_browser, needsBrowserRendering, challenge page) and keeps the proxy HTML only if the browser fails. Tests cover both outcomes.
The proxy runs no scripts, so returning its HTML right away turned a force_browser request for a JavaScript shell into near-empty output. Send the recovered page through the same browser decision as a direct fetch, and keep the proxy HTML if the browser fails.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
A render after 10 s of direct fetch and up to 20 s of proxy could run past the MCP client's 60 s limit. Only the render sees the deadline; trackProvider keeps the caller's signal, so an expiry is recorded as a browser failure. The proxy page is kept.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 459dc1da86
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| viaProxy = providerApiKeysAllowed | ||
| ? await tryDirectProxyFetch(resolvedUrl, env, fallbacks, deadline.signal, progress) | ||
| : await tryAnonymousProxy(resolvedUrl, env, fallbacks, deadline.signal, progress); |
There was a problem hiding this comment.
Enforce the retry deadline around the entire proxy operation
When the configured proxy stalls while establishing its connection, aborting deadline.signal does not necessarily settle this await. In src/proxy.ts, fetchViaProxy awaits the initial CONNECT writer.write() without a timeout or abort race, and its cleanup also awaits writer.close() without either guard. The signal only bounds selected reads and TLS operations. Consequently, a mainland request that previously returned a 504 after 10 seconds can now remain pending beyond both the advertised retry deadline and the MCP client's limit. Bound the complete proxy operation, including connection writes and cleanup, rather than relying solely on passing an abort signal.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit, in fetchViaProxy itself since every proxy caller shares it: the CONNECT and request writes now count against the proxy deadline, and cleanup no longer awaits writer.close() or reader.cancel() (socket.close() ends the connection). A new proxy test with a connection that never opens rejects at the timeout; it fails if either part is reverted.
fetchViaProxy bounded reads and TLS setup by its deadline but not the CONNECT and request writes, and its cleanup awaited writer.close() and reader.cancel(). A proxy connection that never opened could hold a request past both timeoutMs and the mainland retry deadline. Writes now count against the deadline, and cleanup no longer waits; socket.close() ends the connection.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 886d86b81a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const renderDeadline = createTimeoutSignal(MAINLAND_RENDER_DEADLINE, abortSignal); | ||
| try { | ||
| recoveredHtml = await trackProvider(env, "browser", abortSignal, () => fetchWithBrowser( |
There was a problem hiding this comment.
Bound the complete browser render by the new deadline
When the post-proxy browser launch or setup stalls, aborting renderDeadline.signal does not settle this await. In src/browser/index.ts, fetchWithBrowserAdapter awaits launchBrowser, browser.newPage, and page configuration without an abort race; the signal only bounds later navigation and extraction operations. Consequently, a request with already recovered proxy HTML can remain pending beyond the advertised 25-second rendering deadline and the MCP client's 60-second limit. Bound the complete render operation rather than relying solely on passing the signal. The new deadline test mocks a browser implementation that immediately rejects on abort, so it does not exercise these actual unbounded stages.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit: withTimeout now wraps the whole fetchWithBrowser call (launch and setup included), and the deadline signal still stops the remaining stages. The deadline test now uses a browser that ignores the signal entirely.
| )); | ||
| recoveredMethod = "browser+readability+turndown"; | ||
| browserRendered = true; |
There was a problem hiding this comment.
Keep recovered proxy HTML when the browser returns a bot wall
For a timed-out mainland page requested with force_browser=true, the proxy can recover usable content while the browser's datacenter address receives a bot-protection page. fetchWithBrowser can return that page without throwing, so this assignment discards the usable proxy HTML and marks the render successful. The downstream challenge handling in convertUrl then invokes additional providers and ultimately returns target_blocked if they cannot rescue it, despite already having the requested content. Validate the rendered HTML before replacing the recovered page, and retain the proxy result when the browser returns a challenge.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit: a rendered page that detectChallengePage flags no longer replaces the recovered proxy HTML. New test: the browser returns an Akamai denial and the proxy page is converted.
Browser launch and page setup ignore the abort signal, so the 25 s deadline did not bound them; a timeout now wraps the whole render. The browser's datacenter address can also get a challenge page the proxy got past; that page no longer replaces the recovered HTML.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
- A browser page that is a bot wall or a gov soft 404 no longer replaces the recovered proxy page, and browser stats count it as a failure. - The render opens the recovered URL, so HTML and link base match. - withTimeout bounds the proxy retry, so a stalled anonymous budget check or a deadline that fires before the proxy starts ends as 504 target_timeout instead of hanging or a 500. - tryDirectProxyFetch accepts only 2xx; the proxy does not follow redirects, so a 3xx body is not the page. - A deadline that fires during a retry backoff starts the proxy retry. - Mainland deadlines abort with a TimeoutError reason, and trackProvider records attempts such a deadline ends, so each failure is recorded once, with its real error. Amp-Thread-ID: https://ampcode.com/threads/T-01a19236-e961-759a-a320-167408397ed5 Co-authored-by: Amp <[email protected]>
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
- A rendered page replaces the recovered proxy page only when it has at least as much body text, so a blank render no longer wins. - An outer timeout bounds the browser stats write after the render. - Each proxy attempt in the mainland retry gets 9 s, so a silent proxy leaves time for the next one within the 20 s. - tryDirectProxyFetch refuses text/css, text/javascript and text/csv like the static path. - Tests route the proxy mock through acceptResult.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f8a8e652c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| viaProxy = await withTimeout( | ||
| providerApiKeysAllowed | ||
| ? tryDirectProxyFetch(resolvedUrl, env, fallbacks, deadline.signal, progress, MAINLAND_PROXY_ATTEMPT_TIMEOUT) | ||
| : tryAnonymousProxy(resolvedUrl, env, fallbacks, deadline.signal, progress, MAINLAND_PROXY_ATTEMPT_TIMEOUT), | ||
| MAINLAND_PROXY_DEADLINE, |
There was a problem hiding this comment.
Preserve recovered proxy content when its stats write stalls
When the proxy returns usable HTML but the subsequent D1 provider-statistics write stalls past the remaining retry budget, this timeout discards the recovered page and returns 504. tryDirectProxyFetch awaits trackProvider, which awaits recordProviderAttempt before returning the proxy result, so the deadline here covers telemetry as well as fetching. Unlike the browser path, no recovered HTML is retained outside that wait. Bound or decouple the statistics write so a successful proxy fetch can still be converted when telemetry is slow.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit at the source: recordProviderAttempt now gives up on its D1 write after 2 s (it was already best effort), so a slow stats write cannot hold any provider's result. The extra timeout around the post-proxy render is removed as redundant. New test: the proxy_pool stats write never answers and the recovered page is still converted.
trackProvider awaits recordProviderAttempt, whose D1 write had no limit. A slow write after a successful proxy fetch used up the mainland retry deadline, so the recovered page became a 504. The write is best effort, so it now gives up after 2 s. This covers every provider and replaces the extra timeout around the post-proxy render.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
- Count the full body text, not up to the 10,000-character billing cap. - Use the request's selector for both pages. - Treat a render whose title is a denial as a block page, as convertUrl does. - Give the proxy retry 2 s past its deadline for a late answer's stats write; the render deadline drops to 23 s so the total stays about 57 s.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b9603440f5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (!selector && isDenialHeading(title)) return false; | ||
| const chars = bodyChars(markdown); | ||
| return chars > 0 | ||
| && chars >= bodyChars(htmlToMarkdown(viaProxy, resolvedUrl, selector).markdown) |
There was a problem hiding this comment.
Handle a selector absent from the unrendered proxy page
When the requested selector is created by JavaScript and is absent from the proxy HTML, htmlToMarkdown falls back to converting the entire proxy page and skips Readability (src/converter.ts:182–195). This comparison then measures the browser's selected content against the proxy's whole page, including navigation and other unrelated text. If that surrounding text is longer, a successful render containing the requested element is rejected, and the response instead contains the unscoped proxy page—even with force_browser=true. Check whether the selector actually matches the proxy HTML before using its conversion as the minimum-length baseline.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the next commit: when the selector matches nothing in the proxy HTML (new selectorMatches helper in converter.ts), the proxy page sets no minimum, so a usable render of the scripted element wins. New test covers it.
htmlToMarkdown converts the whole page when the selector matches nothing, so a selector that scripts build compared the render's element against the proxy's whole page and could reject a good render.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…oxy (#101) * Retry a timed-out mainland China host only through a mainland-exit proxy The retry added in #100 went through the general proxy, which exits abroad. The hosts it targets answer only addresses inside mainland China: of 45 that timed out in November, 30 dropped connections from nearly every probe location abroad, and all six production retries timed out. Each failed request waited 20 seconds longer for the same 504 and an anonymous one spent proxy budget. The retry now runs only when PROXY_POOL_MAINLAND names proxies that exit in mainland China, and goes through those. Without it the request fails after the 10-second direct timeout. The error message says the site answers only visitors inside mainland China. Amp-Thread-ID: https://ampcode.com/threads/T-01a19236-e961-759a-a320-167408397ed5 Co-authored-by: Amp <[email protected]> * Keep the mainland proxy's refused hosts and redirect targets separate A host that turned the general proxy away could skip the mainland proxy for a day, because both shared one record. Each pool now keeps its own. A mainland URL that redirects to a host outside mainland China, which then times out, is no longer sent to the mainland proxy. * Retry a redirect target outside mainland China through the general proxy The pool now follows the hop that timed out: a mainland host goes to the mainland proxies only, any other redirect target keeps the general proxy and the general timeout message. An anonymous mainland retry no longer spends budget when no mainland proxy parses, a host named with its root dot counts as mainland, and /admin no longer lists the mainland pool under the general proxy's card. * Keep a failed redirect retry a timeout and count the mainland proxies apart A mainland URL that redirects abroad, times out mid retry backoff and also fails through the general proxy answered 502 target_unreadable. It is a timeout: 504 target_timeout again. Attempts through the mainland proxies are recorded as proxy_pool_mainland, so one pool's failures do not hide in the other's rate, and /admin shows them on their own card (off until PROXY_POOL_MAINLAND is set). The proxy's TLS handshake checks the certificate against the host without its root dot. * Share a refused host's record with its root-dot spelling A site that refused the proxy was tried again, and spent anonymous budget again, when the same host was written with its root dot. Amp-Thread-ID: https://ampcode.com/threads/T-01a19236-e961-759a-a320-167408397ed5 Co-authored-by: Amp <[email protected]> --------- Co-authored-by: Amp <[email protected]>
What
When a mainland China host (
.cn, or a host inMAINLAND_ONLY_HOSTS) does not answer the static fetch within 10 s, the request now retries once through the residential proxy before giving up.tryDirectProxyFetch.tryAnonymousProxy, so the shared daily budget and the refused-host record from Skip the anonymous proxy for a day on a host that refused it #99 apply.force_browser, a page that needs rendering, or a challenge page, the browser renders the recovered URL, and the rendered page replaces the proxy page only if it is not a challenge page or a gov soft 404 and has at least as much body text. The comparison uses the request's selector (when the proxy page lacks the selector, because scripts build it, the proxy page sets no minimum), counts the full text, and treats a denial title as a block page, likeconvertUrl. Otherwise the proxy page is kept, and the render counts as a browser failure. Otherwise it is returned like a static page (proxy+readability+turndown, taggeddirect_proxy_*). The browser sometimes reaches these hosts; on JS-shell sites such as kjzj.czt.zj.gov.cn it gets 10,900 chars where the static page has 28.fetchWithSafeRedirectsnow reports the failing hop on its error asurl.proxy_poolorbrowserattempt, not dropped as a cancellation: the mainland deadlines abort with aTimeoutErrorreason, andtrackProviderrecords attempts ended that way.target_timeoutas before. That includes a stalled anonymous budget check and a deadline that fires before the proxy starts.tryDirectProxyFetchnow accepts only 2xx results. The proxy does not follow redirects, so a 3xx body is a redirect stub, not the page. It also refusestext/css,text/javascriptandtext/csvlike the static path. Both apply to the existing 403 rescue path too.recordProviderAttemptnow gives up on its D1 write after 2 s. Stats are best effort, and an unbounded write after a successful proxy fetch could use up the retry deadline and turn the recovered page into a 504. This applies to every provider.text/markdownproxy response is still converted as HTML (as on every proxy path), and a render over 5 MB can still win the comparison and fail with 413.fetchViaProxynow bounds its socket writes by its deadline and no longer awaitswriter.close()/reader.cancel()in cleanup. Before, a proxy connection that never opened could hold any proxy request past its timeout, so the retry deadline above could not hold.The timeout message changes from "...refuse connections from outside China, and this service fetches from outside China" to "...do not answer requests from cloud servers." The old reason was wrong. The new text drops "within 10 seconds", since the total wait now includes the retry.
Why
The main signed-in user (a script fetching mainland government pages) got 243
fetch_timeouterrors since 11-01. Many of the hosts never succeeded once, for example sdkjxxw.cn (43), czt.zj (16), kjzx.cn (13), nmgacc.cn (12) and czj.cq (10).Six of those URLs, fetched from a US home connection, answered in 0.2–1.2 s (five 200s, one 302). The same URLs through production still time out after about 11.3 s. So these sites drop datacenter addresses, not overseas ones, and the static timeout used to end the request without trying anything else.
Not verified yet
Proxy credentials exist only in the Worker secrets, so whether the proxy's addresses reach these sites can only be checked in production after deploy. If they are dropped too, the request fails as before, at most 20 s later, and only the message fix helps.
Checks
.gov.cnhost are converted from the proxy's page; when the proxy also fails, the caller gets 504target_timeoutand the response does not mention the proxy. A redirect retries the target page, and an unanswering proxy ends the request at about 30 s. A forced request renders the recovered page in the browser, keeps the proxy page when the browser fails or returns a bot wall, a soft 404 or a blank page, returns on time when the browser or proxy stats write stalls, and stops waiting after 25 s for a browser that ignores the abort signal. A proxy connection that never opens rejects at the proxy timeout. A proxy 302 ortext/cssresponse is not converted, each proxy attempt gets 9 s, a stalled budget check ends as 504target_timeout, and a timeout during a retry backoff still retries. Each test fails without its part of the change.vitest: 945 passed. The proxy mock in these tests goes through the caller'sacceptResult, as the real pool does.tscpasses for the worker and web.