Repository navigation
fix(web-fetch): bound worker reaping and unify P50/P95 percentiles - #127
Conversation
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]>
There was a problem hiding this comment.
This review found 2 issue(s), including 2 blocking issue(s).
| elif isinstance(late, ProcessCleanupError): | ||
| # The answer is late, but a surviving worker must quarantine the provider. | ||
| raise late |
There was a problem hiding this comment.
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.
| stopped_provider = (isinstance(caught_exception, ProcessCleanupError) | ||
| or (result.error_type == 'timeout' and pending is not None | ||
| and pending.is_alive())) |
There was a problem hiding this comment.
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]>
lanyue-llk
left a comment
There was a problem hiding this comment.
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_exitreplaces every unboundedprocess.wait()after a best-effort kill in headless and Moli. Moli'swith process:(an unboundedPopen.__exit__wait) became an explicittry/finally. Moli's Popen uses file objects, not PIPEs, so__exit__did not close any handle. The headlessfinallystill closes stdin and clears_active_processwhen the reap raises. No adapterexceptturnsProcessCleanupErrorinto aProviderResult, so the error reachescall_boundaryand the runner. - Quarantine races:
worker_unresolvedreads liveness before the flag, and the thread sets the flag beforeoutput.put, so a dead thread has always recorded its outcome. When the error is raised synchronously,pendingisNoneand theisinstance(caught_exception, ProcessCleanupError)branch covers it. The manifest getsnon_cancellable_call_still_runningand no retry runs (test_surviving_worker_quarantines_the_provider). - The new tests fail without the fix: with
await_owned_process_exitchanged back to an unboundedprocess.wait(), bothtest_unconfirmed_kill_raises_instead_of_waiting_forevertests (headless and Moli) fail after about 20 s. The fairness race test depends on the new flag. - Percentiles:
wcxb_scoring.py,wcxb_report_check.pyandlexbench/report.py(call_stats, networkp95_bytes, cold-startready_ms) now all uselexbench_webfetch.metrics.percentile. An empty population returnsNoneinstead of raisingIndexError. P50 is now rounded to 2 decimals, which stays inside the check's 0.01 tolerance against the unroundedstatistics.medianinsummarize_full_paired_latency.lexbench/verification.pychecks only sums and the frozen Linux resource summaries, so changingcall_statsbreaks no cross-check. Leavingbrowser_use/report.pyand the hash-boundstatistics.quantilessummaries 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_resultruns only aftercommunicate()has returned andreturncode == 0, so the reviewer process has already exited when any non-ValueErrorcould escape. The run-levelfinallycovers any other entry still inactive.- Golden snapshots: unchanged.
tests/test_golden_reports.pypasses. - 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_runtimeandtest_golden_reports: 192 passed, 1 skipped. - CI: every check on
673b377cpasses, 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.
|
Review round 1 follow-up:
No findings were disputed. |
c720cf0 to
6b3c524
Compare
There was a problem hiding this comment.
✅ Re-review complete · 6b3c524
No findings in this incremental review.
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]>
6b3c524 to
8543f8c
Compare
|
Update: Linux CI on 6b3c524 failed in |
lanyue-llk
left a comment
There was a problem hiding this comment.
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_failedskips the second terminate and bounded wait in cleanup. I checked out673b377cversions ofheadless.pyandmoli.py: bothtest_unconfirmed_kill_raises_instead_of_waiting_forevertests 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'swith 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.percentilereturnsNoneon an empty list, a median for P50 and a 2-decimal nearest rank for P95. Dropping theif valuesguards inwcxb_scoring.pyandlexbench/report.pyis safe.wcxb_report_checkP50 comparesstatistics.medianwith 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::_percentileand the Lexbench resourcestatistics.quantilessummaries are listed as remaining in the "## Issues" section. "Part of #94" is accurate. runner.pyquarantine:isinstance(caught_exception, ProcessCleanupError) or worker_unresolved(...).process_cleanup_failedis set before the result is queued, so a finished thread's flag is visible.- The decision not to change
web_search/review.pyis 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_runtimeandtest_golden_reportsgive 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".
Issues
Closes #94. This PR covers two confirmed items and checks one suspected item. Still open in #94:
_wait_siterejects 4xx readiness responsesagent_run_ms/evidence_finalize_msResultAuditError_wait_cdpspin, port TOCTOU, docker client leak,id(request)keys, import-timetiktoken, runtimeassert,locals().get)src/harness/browser_use/report.py::_percentilestill interpolates linearly. The trajectory-replay,resource_accountingandresource_calibrationhelpers already use nearest rank but do not round. The Lexbench Linux resource summaries (resource_summary.py,resource_evidence.py) usestatistics.quantiles(..., method="inclusive"), and their stored hash-bound summaries are re-verified against that formula, so changing it needs a deliberate evidence re-summary.latency_correction_receipt_sha256(the current profile in the evaluation checkout does),wcxb_report_checknow compares the storedp95_latency_mswith the nearest-rank value, so evidence scored with linear interpolation is rejected.score_wcxb_resultsrefuses 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.
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 calledprocess.wait()with no timeout. In Moli,Popen.__exit__made a second unbounded wait. The newawait_owned_process_exit()inproviders/base.pywaits for at most 1 s and then raisesProcessCleanupError. The runner treats that error like a non-cancellable timeout: it quarantines the provider, leaves the remaining cases unexecuted, recordsnon_cancellable_call_still_runningin the manifest and makes no retry. A cleanup failure that arrives after the answer deadline, afterfetch_with_deadlinereturns or whose late result is consumed as a timeout, is recorded on the answer thread before it exits. The runner checks it throughcall_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 replaceswith process:with an explicittry/finallyreap. 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 oneProcessCleanupErrorinstead of two chained ones.fix(reports): ...).wcxb_scoring.py, the inline copy inwcxb_report_check.pyandlexbench/report.pynow calllexbench_webfetch.metrics.percentile: nearest-rank P95, median P50, rounded to 2 decimals,Nonefor an empty population (no moreIndexError). The Lexbench call statistics move to the module-levelcall_stats()so they can be tested.Reported values that change
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, providerbetawith 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 beforewcxb_report_checkaccepts it, because the check now compares the stored P95 with the nearest-rank value.duration_ms_*,cpu_ms_*,pss_*,fixture_tx_bytes_*P95, network RXp95_bytes, cold-startready_ms.p95). The values move to the nearest observed sample. For example, values 1..100 give a P95 of 95 instead of 95.05.3), and the Lexbench report has no golden snapshot.Suspected item checked:
web_search/review.pyvalidate_resultNot fixed, because it is not a real leak.
_validate_schemaruns first and checks every field's type, enum and key set, so a reviewer result cannot reach aKeyErrororTypeError. Malformed results fail withValueError, which is already caught, and the process is killed. A different exception type, for example aRecursionErrorfromjson.loadson deeply nested output, does skip the local kill. But the process stays inactive,future.result()re-raises the error at once in the main loop, and the run-levelfinallykills every registered process. No orphan process survives the run.Test plan
ruff check --config 'include=["*.py"]' --select F,TID252 .andruff checkboth pass.tests/test_headless_cancellation.py::test_unconfirmed_kill_raises_instead_of_waiting_foreverchecks that the call raises within 5 s and leaves the worker unreaped.tests/test_headless_cancellation.py::test_surviving_worker_quarantines_the_providerchecks 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_forevertest_unconfirmed_kill_raises_instead_of_waiting_forevertests also assert one bounded reap and no chainedProcessCleanupError. They fail without the follow-up commit and pass with it.tests/test_fairness.py::test_cleanup_failure_after_the_deadline_still_quarantinescovers 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_percentilestests/test_wcxb_scoring.pyexpectation updated from 2.9 to 3.-n 2): headless/Moli provider tests, WCXB, Lexbench, WebMainBench report, resource-summary tests andtests/test_golden_reports.py(unchanged). Two local failures:test_headless.py::test_converter_shared_and_nonzero_not_convertedis already on the known macOS failure list.test_moli_provider.py::test_debug_logging_is_passed_and_complete_raw_stderr_is_boundfailed once under parallel load (2 s subprocess budget) and passed on rerun.🤖 Generated with Claude Code