Skip to content

fix(web-fetch): bound worker reaping and unify P50/P95 percentiles - #127

Merged
lanyue-llk merged 4 commits into
mainfrom
fix/webfetch-process-and-percentile-bugs
Nov 2, 2026
Merged

lanyue-llk merged 4 commits into
mainfrom
fix/webfetch-process-and-percentile-bugs

Conversation

@lanyue-llk

@lanyue-llk lanyue-llk commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Issues

Closes #94. This PR covers two confirmed items and checks one suspected item. Still open in #94:

  • Rainbond _wait_site rejects 4xx readiness responses
  • Browser Use resume and fresh runs follow different retry rules
  • Failed Browser Use attempts lose agent_run_ms/evidence_finalize_ms
  • Browser Use HAR/trace cleanup errors are swallowed
  • Public WebArena report hides ResultAuditError
  • Suspected items outside Web Fetch (_wait_cdp spin, port TOCTOU, docker client leak, id(request) keys, import-time tiktoken, runtime assert, locals().get)
  • Other percentile definitions outside the two named in the issue: src/harness/browser_use/report.py::_percentile still interpolates linearly. The trajectory-replay, resource_accounting and resource_calibration helpers already use nearest rank but do not round. The Lexbench Linux resource summaries (resource_summary.py, resource_evidence.py) use statistics.quantiles(..., method="inclusive"), and their stored hash-bound summaries are re-verified against that formula, so changing it needs a deliberate evidence re-summary.
  • Rescore the current WCXB evidence with the shared percentile. When the WCXB profile binds latency_correction_receipt_sha256 (the current profile in the evaluation checkout does), wcxb_report_check now compares the stored p95_latency_ms with the nearest-rank value, so evidence scored with linear interpolation is rejected. score_wcxb_results refuses to overwrite scores, so this needs a new evidence directory, a rebound profile and a scorer-correction receipt that discloses each method's old and new P95 (AGENTS.md treats this as a scorer correction). This PR changes only the code; it does not touch measured evidence.

Summary

There is one commit per bug.

  1. Bounded reap after a best-effort kill (fix(web-fetch): ...). terminate_owned_process_tree() intentionally leaves a worker running when it cannot observe the process tree. The headless and Moli adapters then called process.wait() with no timeout. In Moli, Popen.__exit__ made a second unbounded wait. The new await_owned_process_exit() in providers/base.py waits for at most 1 s and then raises ProcessCleanupError. The runner treats that error like a non-cancellable timeout: it quarantines the provider, leaves the remaining cases unexecuted, records non_cancellable_call_still_running in the manifest and makes no retry. A cleanup failure that arrives after the answer deadline, after fetch_with_deadline returns or whose late result is consumed as a timeout, is recorded on the answer thread before it exits. The runner checks it through call_boundary.worker_unresolved(), so quarantine does not depend on the thread still being alive. This is a separate commit that answers the OCR review. Moli replaces with process: with an explicit try/finally reap. A follow-up commit (fix(web-fetch): spend one bounded grace ...) skips the cleanup reap once the stopped-path reap has already failed, so a surviving worker costs one 1 s grace and raises one ProcessCleanupError instead of two chained ones.
  2. One P50/P95 definition (fix(reports): ...). wcxb_scoring.py, the inline copy in wcxb_report_check.py and lexbench/report.py now call lexbench_webfetch.metrics.percentile: nearest-rank P95, median P50, rounded to 2 decimals, None for an empty population (no more IndexError). The Lexbench call statistics move to the module-level call_stats() so they can be tested.

Reported values that change

  • WCXB (wcxb-score-summary.json: p95_latency_ms, success_p95_latency_ms, plus the home, interpretation and method pages that show them). P95 is now an observed call latency, not an interpolated one. In the synthetic fixture, provider beta with latencies [1.0, 3.0] goes from 2.9 to 3.0 ms. P50 is unchanged apart from 2-decimal rounding. Existing WCXB evidence scored with the old formula must be rescored before wcxb_report_check accepts it, because the check now compares the stored P95 with the nearest-rank value.
  • Lexbench/Moli report (duration_ms_*, cpu_ms_*, pss_*, fixture_tx_bytes_* P95, network RX p95_bytes, cold-start ready_ms.p95). The values move to the nearest observed sample. For example, values 1..100 give a P95 of 95 instead of 95.05.
  • Golden snapshots: no route hash changed. The WCXB pages round latency to whole milliseconds (2.9 and 3.0 both render as 3), and the Lexbench report has no golden snapshot.

Suspected item checked: web_search/review.py validate_result

Not fixed, because it is not a real leak. _validate_schema runs first and checks every field's type, enum and key set, so a reviewer result cannot reach a KeyError or TypeError. Malformed results fail with ValueError, which is already caught, and the process is killed. A different exception type, for example a RecursionError from json.loads on deeply nested output, does skip the local kill. But the process stays in active, future.result() re-raises the error at once in the main loop, and the run-level finally kills every registered process. No orphan process survives the run.

Test plan

  • ruff check --config 'include=["*.py"]' --select F,TID252 . and ruff check both pass.
  • New regression tests:
    • tests/test_headless_cancellation.py::test_unconfirmed_kill_raises_instead_of_waiting_forever checks that the call raises within 5 s and leaves the worker unreaped.
    • tests/test_headless_cancellation.py::test_surviving_worker_quarantines_the_provider checks there is no retry and no next case, and that the manifest records the reason.
    • tests/test_moli_provider.py::test_unconfirmed_kill_raises_instead_of_waiting_forever
    • Both test_unconfirmed_kill_raises_instead_of_waiting_forever tests also assert one bounded reap and no chained ProcessCleanupError. They fail without the follow-up commit and pass with it.
    • tests/test_fairness.py::test_cleanup_failure_after_the_deadline_still_quarantines covers both race paths from the review: the failure arriving after return, and the failure consumed as a late result.
    • tests/test_wcxb_contract.py::test_latency_percentiles_include_all_calls_with_the_shared_definition (replaces the linear-interpolation assertion)
    • tests/test_lexbench_report_runtime.py::test_call_statistics_use_the_shared_nearest_rank_percentiles
    • tests/test_wcxb_scoring.py expectation updated from 2.9 to 3.
  • Locally (macOS, -n 2): headless/Moli provider tests, WCXB, Lexbench, WebMainBench report, resource-summary tests and tests/test_golden_reports.py (unchanged). Two local failures:
    • test_headless.py::test_converter_shared_and_nonzero_not_converted is already on the known macOS failure list.
    • test_moli_provider.py::test_debug_logging_is_passed_and_complete_raw_stderr_is_bound failed once under parallel load (2 s subprocess budget) and passed on rerun.
  • CI (Linux) runs the full suite.

🤖 Generated with Claude Code

lanyue-llk and others added 2 commits October 30, 2026 20:15
terminate_owned_process_tree() leaves the worker running when the process
tree cannot be observed. The headless and Moli adapters then called an
unbounded process.wait() (Moli also via Popen.__exit__), so a call could
hang forever. Reap with a one-second grace and raise ProcessCleanupError
when the worker survives; the runner quarantines the provider instead of
starting the next call beside a live worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
WCXB scoring, its release check and the Lexbench report each interpolated
P95 linearly, while Web Fetch uses lexbench_webfetch.metrics.percentile
(nearest rank, 2-decimal rounding). "P95" therefore meant different things
across reports, and the WCXB copy raised IndexError on an empty population.
All three now call the upstream definition; P50 is still the median.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@lexmount-ocr lexmount-ocr Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Review complete · df526e1

This review found 2 issue(s), including 2 blocking issue(s).

Comment thread src/harness/web_fetch/call_boundary.py Outdated
Comment on lines +100 to +102
elif isinstance(late, ProcessCleanupError):
# The answer is late, but a surviving worker must quarantine the provider.
raise late

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
P2: This only preserves cleanup errors still in the queue. output.get() can receive a ProcessCleanupError whose completion timestamp exceeds the deadline (for example, when the waiting caller is descheduled around the deadline). Lines 76–78 then overwrite that exception with TimeoutError; the queue has already been consumed, so get_nowait() returns nothing and this branch never runs. With the thread finished, the runner treats the surviving subprocess as safe to retry. Preserve and re-raise an already-received ProcessCleanupError before replacing late values with a timeout, and test this consumed-late-result path.

Comment thread src/harness/web_fetch/runner.py Outdated
Comment on lines +842 to +844
stopped_provider = (isinstance(caught_exception, ProcessCleanupError)
or (result.error_type == 'timeout' and pending is not None
and pending.is_alive()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
P1: Quarantine can be lost when cleanup finishes after fetch_with_deadline returns. Both adapters allow only a 1-second join, but can perform two 1-second reap waits plus kill attempts. If the thread raises ProcessCleanupError after that join and before this check (during artifact persistence/scoring), caught_exception is still None and pending.is_alive() is now false. The subprocess is still running, yet the runner retries or executes the next case. Previously the unbounded wait kept this thread alive. Preserve an unresolved-cleanup flag at the boundary, or retain and inspect the thread's completion outcome before allowing further calls; add a regression where cleanup fails during scoring.

…eadline

Review found two races in the previous fix. A ProcessCleanupError that
arrives after fetch_with_deadline returns, or whose late result the
caller consumes as a plain timeout, left the thread finished with no
trace, so the runner retried beside a live process. The answer thread now
records the cleanup failure before it exits, and the runner checks it
through worker_unresolved() after reading thread liveness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Review complete · 673b377

No findings in this review.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 1

Reviewed head 673b377c (3 commits on 8b8aa30f). I read every changed line and the surrounding runner and call-boundary code, ran lint and the affected tests locally, and ran mutation checks on the new tests.

Findings

P2: src/harness/web_fetch/wcxb_report_check.py:393. Current WCXB evidence will fail the release check, and no follow-up tracks the fix.
When the profile has latency_correction_receipt_sha256, the check now compares the stored p95_latency_ms with the nearest-rank value at a 0.01 tolerance. The current WCXB profile in the working checkout (evaluation/wcxb/current-report.json) sets that receipt. Its stored wcxb-score-summary.json was scored with linear interpolation, so check_wcxb_report.py will reject it until it is rescored. score_wcxb_results.py refuses to overwrite scores, so a rescore needs a new evidence directory and a rebound profile. AGENTS.md treats a scorer change as a correction: keep the prior evidence, supersede the full scope and disclose the latency effect. The PR body mentions the rescore in one sentence, but the "Part of #94 / still open" list leaves it out.
Fix: add "rescore current WCXB evidence with the shared percentile and rebind the profile (correction receipt, disclosed P95 changes)" to the remaining-work list, or open a follow-up issue and link it. That way the next WCXB release does not find out from a failing gate.

P3: src/harness/web_fetch/providers/headless.py:791-802, src/harness/web_fetch/providers/moli.py:694-726. The cleanup grace runs twice.
On the stopped path, the first await_owned_process_exit raises after 1 s. The finally then calls terminate_owned_process_tree again and waits another 1 s. That raises a second ProcessCleanupError, chained to the first. Moli does the same because process.poll() is still None. Correctness holds: after a deadline, fetch_with_deadline joins for cancellation_cleanup_seconds = 1.0, the thread is still alive, and the runner quarantines. The cost is 2 s of grace where 1 s was intended, plus a duplicate exception in the traceback. Fix: skip the second wait in finally once the bounded reap has already failed, for example with a local flag.

Verified with no defect found

  • Bounded reap: await_owned_process_exit replaces every unbounded process.wait() after a best-effort kill in headless and Moli. Moli's with process: (an unbounded Popen.__exit__ wait) became an explicit try/finally. Moli's Popen uses file objects, not PIPEs, so __exit__ did not close any handle. The headless finally still closes stdin and clears _active_process when the reap raises. No adapter except turns ProcessCleanupError into a ProviderResult, so the error reaches call_boundary and the runner.
  • Quarantine races: worker_unresolved reads liveness before the flag, and the thread sets the flag before output.put, so a dead thread has always recorded its outcome. When the error is raised synchronously, pending is None and the isinstance(caught_exception, ProcessCleanupError) branch covers it. The manifest gets non_cancellable_call_still_running and no retry runs (test_surviving_worker_quarantines_the_provider).
  • The new tests fail without the fix: with await_owned_process_exit changed back to an unbounded process.wait(), both test_unconfirmed_kill_raises_instead_of_waiting_forever tests (headless and Moli) fail after about 20 s. The fairness race test depends on the new flag.
  • Percentiles: wcxb_scoring.py, wcxb_report_check.py and lexbench/report.py (call_stats, network p95_bytes, cold-start ready_ms) now all use lexbench_webfetch.metrics.percentile. An empty population returns None instead of raising IndexError. P50 is now rounded to 2 decimals, which stays inside the check's 0.01 tolerance against the unrounded statistics.median in summarize_full_paired_latency. lexbench/verification.py checks only sums and the frozen Linux resource summaries, so changing call_stats breaks no cross-check. Leaving browser_use/report.py and the hash-bound statistics.quantiles summaries out of scope is reasonable, and the PR lists them as remaining.
  • web_search/review.py (suspected item): I agree it needs no fix. validate_result runs only after communicate() has returned and returncode == 0, so the reviewer process has already exited when any non-ValueError could escape. The run-level finally covers any other entry still in active.
  • Golden snapshots: unchanged. tests/test_golden_reports.py passes.
  • Lint and local tests: ruff (both gates) passes. test_headless_cancellation, test_moli_provider, test_fairness, test_wcxb_contract, test_wcxb_scoring, test_lexbench_report_runtime and test_golden_reports: 192 passed, 1 skipped.
  • CI: every check on 673b377c passes, including "Tests and static checks".
  • Rules: one commit per bug (the third commit is the review follow-up to the first), English, no compatibility aliases, the superseded local percentile copies are removed, and no evidence or private data is touched.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Review round 1 follow-up:

  • P3, double grace and chained error after a failed reap (headless.py, moli.py): fixed in c720cf0. A local reap_failed flag skips the cleanup kill and wait once the stopped-path reap has raised. A surviving worker now costs one 1 s grace and produces one ProcessCleanupError. Both test_unconfirmed_kill_raises_instead_of_waiting_forever tests now assert a single await_owned_process_exit call and no chained ProcessCleanupError. They fail on the previous head and pass on c720cf0.
  • P2, current WCXB evidence rejected by the nearest-rank P95 check: accepted, with no code change. The PR body's remaining-work list for Fix confirmed runtime bugs found in the codebase audit #94 now names the rescore of current WCXB evidence with the shared percentile, in a new evidence directory, with a rebound profile and a scorer-correction receipt that discloses each method's old and new P95. This PR does not touch measured evidence.

No findings were disputed.

@lanyue-llk
lanyue-llk force-pushed the fix/webfetch-process-and-percentile-bugs branch from c720cf0 to 6b3c524 Compare October 30, 2026 14:38

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Re-review complete · 6b3c524

No findings in this incremental review.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Correction: GitHub did not register the push of c720cf0, so I re-pushed the same change with a new commit date. The P3 fix is now 6b3c524. Its content is identical to c720cf0.

A failed reap on the stopped path already raised ProcessCleanupError after
the grace. The cleanup block then killed and waited again, doubling the
grace and chaining a duplicate error. Skip the second reap once the first
has failed, in both the local headless worker and the Moli provider.

The answer thread can now finish within the caller's cancellation grace,
so the Moli permission-error test checks worker_unresolved() rather than
thread liveness. That is the runner's quarantine signal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lanyue-llk
lanyue-llk force-pushed the fix/webfetch-process-and-percentile-bugs branch from 6b3c524 to 8543f8c Compare October 30, 2026 14:56

@lexmount-ocr lexmount-ocr Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Review complete · 8543f8c

No findings in this review.

@lanyue-llk

Copy link
Copy Markdown
Contributor Author

Update: Linux CI on 6b3c524 failed in test_moli_provider.py::test_cancel_permission_error_preserves_timeout_and_unresolved_worker. That test asserted that the answer thread was still alive. The P3 fix lets the thread raise ProcessCleanupError within the caller's 1 s cancellation grace, so the assertion now races. I amended the P3 commit, now 8543f8c, to assert worker_unresolved(worker, timed_out=True), the signal the runner uses for quarantine. The test also joins the thread and checks that the finished thread still reports the surviving process. Tests and static checks pass on 8543f8c.

@lanyue-llk lanyue-llk left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, round 2

Head: 8543f8c4. I found no defects at P0–P3.

Round 1 follow-up

  • P3 (headless.py / moli.py double grace): fixed. reap_failed skips the second terminate and bounded wait in cleanup. I checked out 673b377c versions of headless.py and moli.py: both test_unconfirmed_kill_raises_instead_of_waiting_forever tests fail there and pass on the head, so they are real regression tests. The success path still reaps in cleanup, which costs nothing because the process has already exited. Moli's with process: removal does not leak handles because stdin is DEVNULL and stdout/stderr are caller-owned files.
  • P2 (WCXB rescore): the PR body now lists the rescore, profile rebinding and scorer-correction receipt as remaining work under #94, and says no measured evidence changes. Accepted.

What I verified

  • lexbench_webfetch.metrics.percentile returns None on an empty list, a median for P50 and a 2-decimal nearest rank for P95. Dropping the if values guards in wcxb_scoring.py and lexbench/report.py is safe.
  • wcxb_report_check P50 compares statistics.median with the rounded stored value under a 0.01 tolerance. The rounding error is at most 0.005, so it is consistent. P95 uses the same function on both sides.
  • No other inline linear-interpolation copy remains in the Web Fetch, WCXB or Lexbench report paths. The out-of-scope browser_use/report.py::_percentile and the Lexbench resource statistics.quantiles summaries are listed as remaining in the "## Issues" section. "Part of #94" is accurate.
  • runner.py quarantine: isinstance(caught_exception, ProcessCleanupError) or worker_unresolved(...). process_cleanup_failed is set before the result is queued, so a finished thread's flag is visible.
  • The decision not to change web_search/review.py is justified: a schema-validated result cannot raise KeyError/TypeError, and the run-level finally kills registered processes.
  • Lint gate passes. Locally (macOS): test_headless_cancellation, test_moli_provider, test_fairness, test_wcxb_contract, test_wcxb_scoring, test_lexbench_report_runtime and test_golden_reports give 192 passed, 1 skipped. Golden snapshots are unchanged, which matches the PR's explanation (WCXB pages round to whole ms, and Lexbench has no snapshot).
  • CI on 8543f8c4: every check passes, including "Tests and static checks".

@lanyue-llk
lanyue-llk merged commit 2740130 into main Nov 2, 2026
6 checks passed
@lanyue-llk
lanyue-llk deleted the fix/webfetch-process-and-percentile-bugs branch November 2, 2026 04:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix confirmed runtime bugs found in the codebase audit

1 participant