Repository navigation
fix(trajectory-replay): close the local CDP port race and align Browser Use P95 - #140
Conversation
There was a problem hiding this comment.
This review found 1 issue(s), including 1 blocking issue(s).
| except Exception: | ||
| _stop_browser(process) | ||
| raise |
There was a problem hiding this comment.
P2: Clean up the spawned browser on interruption as well as ordinary startup failures. _execute_cohort now calls this helper before entering its try/finally, whereas previously _wait_cdp ran inside that cleanup scope. If Ctrl-C interrupts port discovery or readiness polling, KeyboardInterrupt bypasses this except Exception and the browser is left running (it was launched in a separate session). Catch BaseException for this cleanup-and-rethrow block, or otherwise guarantee cleanup until ownership is transferred to the caller.
Suggestion:
| except Exception: | |
| _stop_browser(process) | |
| raise | |
| except BaseException: | |
| _stop_browser(process) | |
| raise |
|
Review round 1 follow-up: the P2 finding on interrupted startup is accepted and fixed in 594e6ab. start_local_browser() now stops the browser on any exception, including KeyboardInterrupt, before ownership passes to the caller. The new test test_local_browser_is_stopped_when_startup_is_interrupted fails with the old except clause and passes with the fix. |
There was a problem hiding this comment.
This review found 1 issue(s), including 1 blocking issue(s).
| except psutil.NoSuchProcess: | ||
| # A process left the tree during this scan, so scan it again. | ||
| ports.clear() |
There was a problem hiding this comment.
P2: Isolate exited/zombie descendants instead of discarding the entire scan. psutil.ZombieProcess subclasses NoSuchProcess; on platforms such as macOS, enumerating a retained zombie child's sockets can therefore enter this handler on every iteration. Even if the live browser's CDP listener was already found, ports.clear() discards it, and a healthy browser times out after 30 seconds. Catch these exceptions per descendant and continue scanning healthy members, while treating loss of the owner separately. Add a regression case with a healthy listener and a child whose socket enumeration repeatedly raises ZombieProcess.
|
Review round 2 follow-up: the P2 finding on zombie children is accepted and fixed in d19827f. Each process is now scanned separately, so one that cannot be inspected no longer hides a listener already found. The same commit fixes the Linux CI failure in test_local_browser_that_exits_before_binding_is_reported, where an exiting process raised psutil.AccessDenied on /proc//fd instead of the exit error. The new tests fail on the previous scan and pass on this commit. |
There was a problem hiding this comment.
✅ Re-review complete · d19827f
No findings in this incremental review.
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 1
Reviewed head d19827fb against base 27401304. There are no correctness defects in the port or percentile fixes. Two P2 findings and one P3 finding are below.
Findings
P2: src/harness/trajectory_replay/catalog_runner.py:747-751. The per-restart endpoint refresh has no regression test.
A restart now gets a new port, so start_browser must rebind endpoint. This is the one new failure mode the change adds to the catalog runner: a stale endpoint would point every later task at a dead port, or at another process that has since bound that port, which is the race this PR closes. The code is correct today. However, I mutated it to keep the first endpoint across restarts (endpoint = endpoint or fresh), and all of tests/trajectory_replay still passed (2056 passed, 5 skipped). The only test that calls catalog_runner.main() exits before the local browser starts.
Suggested fix: add a test that drives the local path with a fake start_local_browser returning a different endpoint per call and a fake _run_task. Force a restart through a dead process or a pre-evidence setup failure, then assert the next _run_task call receives the new endpoint.
P2: PR body, "Still open in #94". The remaining-work list omits two items that are still in the code.
src/harness/trajectory_replay/webarena_report.py:2239:_catalog_percentilestill interpolates linearly.:2481renders it as P95 in the catalog acceptance report (scripts/build_webarena_catalog_report.py, a supportedmaketarget). #94 says "Use the upstream definition everywhere", so another reader would conclude from this PR that Browser Use and the LexBench resource summaries were the last percentile outliers.src/harness/trajectory_replay/webarena_replay.py:742:locals().get("readiness_retries", 0)is still there. The body names only the_submithalf of that #94 suspected item.
Suggested fix: add both to the list. If you port _catalog_percentile instead, first check that nothing frozen for the catalog report depends on the old value. "Part of #94" remains the correct claim either way.
P3: src/harness/trajectory_replay/remote_execution.py:1196-1201. The cohort teardown still duplicates _stop_browser.
The PR body says _stop_browser moved so both runners share it, but _execute_cohort only reaches it through a failed startup. Its finally keeps a separate copy with a 5 s timeout and an unbounded process.wait() after kill(), the same pattern #94 lists elsewhere.
Suggested fix: replace the block with _stop_browser(process).
What I verified
- Port race: both runners now pass port 0, and the port comes only from the browser's own process tree, so no reserve-and-release window remains in the replay paths.
_execute_cohortand all catalog restart paths read the current endpoint.start_local_browserstops the browser onBaseException. - Multiple listeners: no test covers the branch, so I ran a stand-in process with two loopback listeners. It raises the "several loopback ports" error and the process is stopped.
- Real browser:
test_playwright_backend_executes_portable_and_snapshot_ref_callsran and passed on this macOS machine, not skipped, so real Chromium works through the new launcher. This answers the question left open in the PR's "Not tested" note. Linux with a real browser is still untested. I did not independently run Moli, Lightpanda or Obscura; the only Moli build available here is not executable on this host. - Percentile:
lexbench_webfetch.metrics.percentilekeeps the median for P50 and uses nearest rank for P95, with 2-decimal rounding. The empty-list result is stillNone. The new test would fail on the old code, which gives 2900. Nothing outsidebrowser_use/report.pyreads these summary values, so the "no stored evidence changes" claim holds. - LexBench deferral:
validate_measurements(resource_evidence.py:64) andvalidate_summary(resource_summary.py:257) both recompute the inclusive-method P95 and compare it with stored artifacts, so changing the formula would reject existing evidence. Deferring it for an owner decision is justified. The issue'swcxb_scoring.pyandlexbench/report.pydefinitions already use the shared helper. - Dependency:
psutilis in the samebrowser-use-evalextra aswebarena-verified, whichremote_execution.pyalready imports. The lock resolves 7.2.2 and its diff is metadata only. - Rule checks: no evidence, profile or receipt binds these source files by hash. Golden snapshots are unchanged. The
configs/report-templates.jsonreference tobrowser_use/report.pyis only a renderer path. - Local runs on this head: both ruff gates pass.
test_golden_reports.py,test_remote_execution_contracts.py,test_remote_cohort_execution.py,browser_use/test_report.pyandtest_playwright_tool.pygave 158 passed. - CI on
d19827fb: all checks pass, including "Tests and static checks" and "Installation and packaging".
d19827f to
a9f91e7
Compare
|
Review findings addressed on head a9f91e7. The branch is rebased on current main (52da9ca), so earlier SHAs changed. Fixed
Behaviour to note: Disputed: none. Local checks: both ruff gates pass. |
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 2
Reviewed head a9f91e72 against base 52da9caa. I found no correctness defects in the code or tests. There is one P3 finding, about the PR body.
Findings
P3: PR body, "Still open in #94" (code at src/harness/web_search/review.py:787-812). The list omits one item from #94. The issue's suspected web_search/review.py item is unchanged at this head: the block still has no try/finally, and except covers only TimeoutExpired, ValueError and OSError. So an exception of another type would skip active.pop.
The item may not be reachable through a malformed result. validate_result first runs a strict schema check, and the four malformed payloads I tried all raised ValueError. That is a limited check, not proof. The body currently gives no status for this item, although "Part of" requires listing what remains.
Suggested fix: add it to the "Other suspected items" list, with a note that it looks unreachable through result JSON but has not been changed. No code change is needed in this PR.
I checked every other unticked #94 item at this head. Each one is either fixed by the merged #124, #125 or #127, or already named in the PR body.
What I verified
- Round 1 fixes: all three are present.
_execute_cohortnow calls_stop_browser, the body lists both added items, and the endpoint refresh test exists. - Regression tests, by temporary mutation:
- Keeping the first endpoint across restarts fails all 3 cases of
test_local_catalog_restart_replays_on_the_new_browser_endpoint. - Requesting a fixed port instead of port 0 fails
test_local_browser_endpoint_cannot_be_taken_by_another_process, plus the interrupted-startup test. - Narrowing
except BaseExceptiontoexcept Exceptionfailstest_local_browser_is_stopped_when_startup_is_interrupted. - Restoring linear interpolation fails
test_summary_percentiles_use_the_shared_nearest_rank_definition.
- Keeping the first endpoint across restarts fails all 3 cases of
- Real browsers on macOS:
start_local_browserstarted Chromium, Moli, Lightpanda and Obscura, 3 times each on a reused profile directory. Each start got a new port, and eachwebSocketDebuggerUrlcarried that port. test_playwright_backend_executes_portable_and_snapshot_ref_calls: it ran and passed here. The body says it could not tell whether this test ran locally.- Endpoint handling:
run_taskreadsendpointfrom the closure when it runs, so setup recovery, an exited browser and a poisoned runtime all use the new endpoint. - Percentile swap: the report now calls the shared
percentile. The median at 0.5 is unchanged, P95 is nearest rank, and results are rounded to 2 decimals. Empty input still returnsNone. No other code or check reads the summary P95 fields, and the rounding does not matter at the scale of these metrics. - Other percentile code:
wcxb_scoring.pyandlexbench/report.pyalready use the shared function._catalog_percentileis the only remaining linear one, and it is already listed. - LexBench deferral: the first reason holds.
validate_measurementsandvalidate_summaryrecompute against stored values, and those artifacts are not available to re-summarize here. I did not trace the second reason (the mixed-definition table) through to rendered output. "Part of #94" is the correct claim. - Dependency:
psutilsits in the same extra aswebarena-verified, whichremote_execution.pyalso imports at the top level. The lock resolves 7.2.2. - Local checks: both ruff gates pass.
tests/test_golden_reports.pyplus the remote execution, cohort, catalog and Browser Use report tests give 163 passed, with snapshots unchanged. I did not rerun the full suite locally. - Evidence: the diff touches no evidence, profiles or receipts.
- CI at this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks" and "Python 3.11" all pass.
- Main has moved: main is now one commit ahead (#135). A trial merge has no conflicts, but CI has not run on that combination.
Not tested: a real browser on Linux, which the PR body already discloses.
|
Review round 2 follow-up on head a9f91e7. This finding needed only a PR body change, so there is no new commit. Fixed
Disputed: none. Not rebased: main moved to a26f6ed (#135) after the last push. GitHub reports the PR as mergeable and clean, so I did not push a rebase. The test plan in the PR body gives the local result on a test merge. |
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 3
Reviewed head a9f91e72 against base 52da9caa. No defects were found, and there are no findings at any severity.
What I verified
- Port race, startup:
start_local_browserpasses port 0 for all four engines and reads the port only from the spawned process tree. Nothing else insrc/orscripts/calls_browser_commandor_wait_cdp. Restoring reserve-then-release makestest_local_browser_endpoint_cannot_be_taken_by_another_processfail. - Port race, callers: the catalog runner reads
endpointwhen each task runs, so a retry or restart uses the new port. The cohort runner has no uses ofendpointbefore the assignment._stop_browserdiffers from the old cohort teardown only in its longer bound (10 s instead of 5 s), its boundedwait()afterkill()and its early return for an exited process. - Real browser:
test_playwright_backend_executes_portable_and_snapshot_ref_callsran against Chrome through the new launcher on macOS and passed. This settles the open question in the test plan for macOS. A real browser on Linux is still untested, as the PR body says. - Percentile: I compared
lexbench_webfetch.metrics.percentilewith the removed helper. Empty input still givesNone. P50 stays the median, now rounded to 2 decimals. P95 changes to nearest rank, as the PR body says._primary_summaryoutput is consumed only insidebrowser_use/report.py, and I found no check there that compares it with stored values. Restoring linear interpolation makestest_summary_percentiles_use_the_shared_nearest_rank_definitionfail. - Packaging:
remote_execution.pyalready needed thebrowser-use-evalextra throughwebarena_verified, and onlycatalog_runner.pyand scripts import it from outside tests. So the top-levelimport psutiladds no new import requirement. - Evidence and rules: nothing under
evaluation/names the changed source files by path, and the diff touches no evidence or profile. Commits carry no attribution lines, and the added lines contain no private paths or hostnames. - Scope claim: "Part of #94" is correct. I checked the deferred LexBench reasoning against the code:
resource_summary.py::validate_summaryandresource_evidence.py::validate_measurementsboth recompute P95 with the inclusive formula and compare it with stored values, so changing the formula would make existing artifacts fail. I confirmed the listed open port-race and percentile sites at this head, plushar.py:420andwebarena_replay.py:742. A pattern search ofsrc/harnessfound no other linear percentile.
Test results
- Lint: both ruff gates pass.
- At this head, macOS,
-n 2:tests/test_golden_reports.py,tests/trajectory_replay,tests/browser_useand the LexBench report, resource and verification tests give 2418 passed, 5 skipped. Golden snapshots are unchanged. - Merged with current main (
a26f6ede): the merge is clean anduv lock --check --offlinepasses.tests/test_golden_reports.py,tests/test_packaging_hygiene.py,tests/trajectory_replayandtests/browser_usegive 2386 passed, 5 skipped. I did not run the full suite on the merge. - CI at this head: "Tests and static checks", "Installation and packaging", "Rendered reference and report checks" and "Python 3.11" all pass. GitHub reports the PR as mergeable and clean.
Not checked
- I did not run the Moli, Lightpanda or Obscura binaries; the PR body's manual results for them are not reproduced here.
- No real LexBench evidence is available here, so the deferred reasoning is confirmed from the code only.
…ries The Browser Use report interpolated P95 linearly while Web Fetch, WCXB and the Lexbench call statistics use lexbench_webfetch.metrics.percentile. The summary now calls the shared definition, so P95 is an observed value rounded to 2 decimals. Summaries are recomputed from attempts on every build, so no stored evidence changes.
Both replay runners reserved a port, released it and then started the browser. Another process could take the port in that window. The readiness probe would accept that listener and the replay would drive the wrong browser, and Lightpanda stays alive after losing the bind so its exit could not expose the conflict. start_local_browser() now passes port 0 and reads the port from the listening sockets of the browser's own process tree. This declares psutil, which the lock already resolves, in the browser-use-eval extra. A restart gets a new endpoint, so the catalog runner re-reads it for each task.
…upted start_local_browser() runs before the caller's cleanup scope and the browser has its own session, so an interrupt during port discovery or readiness polling left it running. Clean up on any exception before ownership passes to the caller.
…port Linux denies /proc/<pid>/fd while a process exits, so a browser that exited during the scan raised psutil.AccessDenied instead of the exit error. A child that could not be inspected also discarded a listener already found, and a retained zombie child could time out a healthy browser. Skip the process that cannot be inspected and keep scanning; the poll still reports the owner's exit.
a9f91e7 to
74d6173
Compare
Issues
Closes #94. This PR fixes the replay port race and the Browser Use percentile. It deliberately does not change the LexBench resource summaries (reasons below).
Still open in #94:
web_fetch/providers/headless.py::native_cdp_browserstill reserves a port and then releases it.environments/webarena/backend.py::find_free_porthas the same pattern, but nothing undersrc/calls it.lexbench/resource_matrix.pycalls thefind_free_portof the frozen external runner.trajectory_replay/webarena_report.py::_catalog_percentilestill interpolates linearly and is rendered as P95 in the catalog acceptance report. I did not check whether anything frozen for that report depends on the old value, so this PR leaves it alone.environments/webarena/har.py:420still keys requests byid(request).webarena_replay.pystill calls the privateservice._submitand still useslocals().get("readiness_retries", 0)at line 742. I only checked these by searching the code; this PR does not touch them.web_search/review.py(the job loop aroundvalidate_result) still has notry/finally, and itsexceptcovers onlyTimeoutExpired,ValueErrorandOSError, so any other exception type would skip the kill andactive.pop. It looks unreachable through malformed result JSON, becausevalidate_resultruns a strict schema check first and four malformed payloads tried in review all raisedValueError. That is a limited check, not proof, so the item stays open. This PR does not change it.Summary
Each of the three items was still present at the base commit.
Replay port race (fixed)
catalog_runner.pyandremote_execution.pybound port 0, closed the socket and then started the browser. Another process could take the port in that window._wait_cdpwould then accept the other listener's200, and the replay would drive the wrong browser.Waiting for our browser to exit does not reliably expose this, as I found by running the pinned binaries on an occupied port:
The new
remote_execution.start_local_browser()passes port 0, so the browser binds its own port and there is no window. It then reads the port from the listening loopback sockets of that browser's own process tree. This works the same way for every engine, and Obscura logs no address when its output is not a terminal, so parsing logs would not have worked.Effects of the change:
_stop_browsermoved toremote_execution.pyso both runners share it. The cohort runner's own teardown copy, which had an unboundedwait()afterkill(), is gone.psutil>=7,<8joins thebrowser-use-evalextra. The lock already resolved 7.2.2 throughcrawl4ai, so only the lock's dependency metadata for this project changes.Browser Use percentile (fixed)
browser_use/report.py::_percentilestill interpolated linearly. The report now callslexbench_webfetch.metrics.percentile.Reported values that change. On the next rebuild, every P95 in the Browser Use summary moves to an observed value: Agent duration, BrowserTool duration, tokens and the resource metrics. All P50 and P95 values are also rounded to 2 decimals. For example,
[1000, 3000]ms gives a P95 of 3000 instead of 2900. These summaries are recomputed fromattempts.jsonlon every build and no check compares them with stored values, so no evidence changes.Golden snapshots: no route hash changed, because the synthetic fixtures have too few samples for the two definitions to differ. I did not regenerate them.
For the next release: authored prose stored with the report assets is outside Git and was not available here. If it quotes a Browser Use P95, recheck it when the report is next rebuilt.
LexBench resource summaries (not changed)
resource_summary.py::statsandresource_evidence.py::validate_measurementsstill usestatistics.quantiles(..., method="inclusive"). I left them alone because:validate_measurementsrecomputes the P95 of the storedlexbench_moli_macos_fixed_resource_summary/1files, and nothing in this repository produces those files.validate_summarydoes the same forlinux-resource-profiles.jsonin a built site. With a new formula, both would reject existing artifacts as differing from the physical measurements.verification.pyandapp.jscompares the four Linux builds with rows from the hash-boundversion-resource-measurements.json, and it marks a single winner per column. Those frozen rows cannot be recomputed here, so they would keep their stored P95 next to nearest-rank values.Decision needed: either keep the frozen definition and state it on the report, or re-summarize all of these artifacts under a new schema with a correction receipt that discloses the old and new values.
No LexBench evidence is available on this machine, so this reasoning comes from reading the code and was not tested against real artifacts.
Test plan
ruff check --config 'include=["*.py"]' --select F,TID252 .andruff checkboth pass.uv lock --check --offlinepasses with the hand-edited lock metadata.-n 2:tests/trajectory_replay,tests/browser_use,tests/test_golden_reports.pyand the LexBench resource and report tests give 2392 passed, 5 skipped, no failures. Golden snapshots are unchanged. After the latest review fixes, rebased on current main, I rerantests/trajectory_replay,tests/browser_useandtests/test_golden_reports.py: 2351 passed, 5 skipped, golden snapshots unchanged.a26f6ede(build(packaging): bundle package data and move package gate to Python #135), which merged after the last push; this round made no code change. A test merge of the two is clean. On that merge, locally on macOS:tests/test_packaging_hygiene.py,tests/test_golden_reports.py,test_remote_execution_contracts.pyandtests/browser_use/test_report.pygive 138 passed. The full suite was not run on the merge.test_remote_execution_contracts.py::test_local_browser_endpoint_cannot_be_taken_by_another_processstarts a foreign CDP listener on any port requested before the spawn, then checks that the endpoint answers from the spawned process.test_report.py::test_summary_percentiles_use_the_shared_nearest_rank_definition(the old code gives 2900.0).test_remote_execution_contracts.py::test_local_browser_is_stopped_when_startup_is_interruptedchecks that an interrupt during startup stops the browser. This came from review round 1.test_uninspectable_child_does_not_hide_the_browser_listenerandtest_exiting_browser_that_denies_inspection_is_reported_as_exitedcover a process that cannot be inspected, and fail on the previous scan. They came from review round 2 and from a Linux CI failure.test_run_webarena_catalog.py::test_local_catalog_restart_replays_on_the_new_browser_endpointdrives the local catalog path through a poisoned runtime, an exited browser and a setup failure, and checks that the next task gets the new endpoint. All three cases fail if the first endpoint is kept. This came from the latest review.test_remote_execution_contracts.py::test_cohort_teardown_never_waits_without_a_boundfails on the old teardown copy. This also came from the latest review.test_local_browser_that_exits_before_binding_is_reportedcovers a browser that exits before it binds. It was not part of the old-behaviour check. On Linux CI this test failed once withpsutil.AccessDeniedon/proc/<pid>/fd, because the process was exiting during the scan. It passed on the earlier CI run, so that failure was timing-dependent. d19827f fixes the cause.start_local_browserstarted Chromium, Moli, Lightpanda and Obscura from pinned binaries, and eachwebSocketDebuggerUrlcarried the assigned port.test_playwright_tool.pynow uses the new launcher, but that test only runs on macOS, and the local run does not show whether it ran or was among the 5 skipped. The Linux CI browser job does not run it either. The regression tests above do run on Linux, using a stand-in server process.