Repository navigation
fix(runtime): recover lost CDP ports, finish failed review jobs and share catalog P95 - #169
Conversation
There was a problem hiding this comment.
This review found 1 issue(s), including 1 blocking issue(s).
| except Exception: | ||
| if process.poll() is None: | ||
| raise | ||
| return None |
There was a problem hiding this comment.
P2 — Port-collision recovery is bypassed when the foreign listener rejects CDP before the launched child exits. An existing HTTP listener can return an error while the child is still starting or reporting its bind failure; this poll() then returns None, the exception escapes, and the outer finally terminates the child without inspecting its address-in-use log or trying another port. This is separate from the documented foreign-CDP successful-handshake limitation. Resolve the child's startup outcome within the remaining deadline before deciding whether to propagate the handshake error, and route confirmed bind failures through the retry loop. Add a regression where the handshake fails before child exit: the current test harness explicitly waits for the child in connect(), masking this ordering. This is a localized but functional gap in the recovery promised by this change.
There was a problem hiding this comment.
✅ Re-review complete · 1464767
No findings in this incremental review.
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 1
Reviewed head 14647676. No stored evidence, profile or golden route changed. Five findings, none blocking correctness of stored data: three P2 defects, one P2 scope gap and one P3 group.
P2: tests/web_search/test_review.py:634 never reaches the code it claims to test
test_malformed_opinion_error_records_a_terminal_failed_job patches validate_result to raise KeyError/TypeError, but the fake Process writes no result.json. json.loads(result_path.read_bytes()) is evaluated first and raises FileNotFoundError, which the existing OSError branch catches. The recorded state["error"] in all four cases is [Errno 2] No such file or directory: ...attempt-001/result.json.
Mutation check: removing KeyError, TypeError from the except at src/harness/web_search/review.py:799 leaves all 58 tests in the file passing. The PR's claim that a malformed opinion now counts as a failed job is therefore unproven.
Fix: have the fake process write valid JSON to result.json (or write it through the --output-schema result path), and assert state["error"] == str(error).
P2: src/harness/web_fetch/providers/headless.py:849 discards the handshake error when the server exits during the grace period
_connect_native_cdp returns None from the except Exception block, so the Playwright exception is lost. If the server exits within the grace second without an "address in use" line, the caller raises RuntimeError(output) from that attempt's log alone. Before this PR, the handshake error was raised.
Reproduced with a stand-in server that binds its port, exits 1 silently after 0.3 s, and a connect_over_cdp that raises ConnectionError:
RuntimeError '' context: None
The worker stores str(error) as error_message, so this attempt is recorded with an empty message and no handshake detail. A Playwright timeout on this path would also change browser_error_type from timeout to browser_error, though the grace window is very small at the deadline.
Fix: keep the exception and re-raise it when the log does not match _ADDRESS_IN_USE, including the server log in the message if useful. Add a test with a silent server exit. The current tests all use a matching log or a server that stays alive.
P2: src/harness/trajectory_replay/webarena_report.py:2424 has no test for the P95 change
Replacing the rendered value with a constant ({-999.0:.2f}) leaves tests/trajectory_replay/test_catalog_report.py and test_catalog_contracts.py passing (14 passed). The PR discloses that the one-task fixture cannot distinguish the definitions, but nothing protects this change from being reverted, or the argument from being wrong: for example, a fraction expressed as 95 rather than .95.
Fix: add a multi-task build, or a small build with durations where interpolated and nearest-rank P95 differ, and assert the rendered cell.
P2: "Closes #165" leaves a stated limit with no follow-up issue
The PR body states that a run can still connect to another CDP server if that server answers before ours has exited. That is the race #165 names, narrowed but still open, and it matters here because parallel workers each start their own CDP server, so the other listener can be a real CDP endpoint running another call. I found no follow-up issue for it. The PR also says it did not check whether the server binaries could accept an inherited socket.
Fix: open a follow-up for ownership proof (psutil or an inherited socket), link it in the "## Issues" section and keep "Closes #165".
P3: statements that overclaim
tests/test_native_cdp_port.py:1says "restarted, never impersonated", and the comment at:59says "The real handshake outlives a server that exits on its failed bind". The fake forces that order withself.processes[-1].wait(20), and the real binaries were not run. The PR body's own limit contradicts "never".test_foreign_cdp_server_is_not_used_after_this_server_lost_the_portonly proves the forced order. Fix: reword both to describe the case where the server has exited first.- The PR body says nothing frozen depends on the catalog P95 because it is not in the manifest.
catalog_contracts.py:585-591also bindsreport_archive_sha256, and that archive containsindex.html. Existing archives still verify against their own bytes, so the conclusion holds for stored evidence, but a rebuilt report needs a new binding. Fix: say so in "Effect on reports". - The PR body says removing
DockerBackend.find_free_port"would break that interface".ContainerBackendis a plainProtocol, notruntime_checkable,DockerBackenddoes not inherit from it, and the upstream manager has no caller. Removal would affect static conformance only. Issue #165 says to remove it if nothing calls it. Keeping it for conformance is defensible, but the PR should state the reason at that strength, or remove it.
Verified without findings
- CI on
14647676:ciand OCR runs succeeded, including "Tests and static checks" and "Installation and packaging". - Local: both ruff gates pass.
tests/test_native_cdp_port.py,tests/web_search/test_review.py,tests/test_review_runner.py,tests/trajectory_replay/test_catalog_report.pyandtests/test_golden_reports.py: 88 passed, no route hash changes. - Mutations that are caught: removing the post-handshake
pollcheck, removing the handshake grace path, and removingsessions.killfrom thefinally. readiness_retries: same value on every path. The oldlocals().getonly ran underexcept Exception, so aBaseExceptionused to reach line 810 unbound.lexbench_webfetch.metrics.percentiletakes a 0..1 fraction, anddurationsis nonempty becausestatistics.meanalready requires it.id(request): the claim holds._impl_to_api_mapping.from_maybe_implcaches the wrapper on the implementation object, the recorder retains registered requests, and HAR assembly walks only registered keys.service._submit: no public alternative is used anywhere in the repository, andPlaywrightReplayToolimplements the same method.review.py: the completed path writes the same state keys in the same order._kill_sessionis a no-op once the process is reaped._validate_schemais strict, soAttributeErroris not a plausible malformed-opinion outcome.- Restart loop: every earlier attempt has exited before the next one starts, the log offset handling is correct, and the regex matches
AddressInUseandAddress already in use. - The two
tests/test_headless_runner.pyfailures the PR mentions pass when selected alone on both this head and basea239d1cc, so I found no evidence that the PR caused them.
|
Review round 1 is addressed on head Fixed:
CI: the checks on |
There was a problem hiding this comment.
✅ Re-review complete · 4045292
No findings in this incremental review.
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 2
Head 40452923. CI on this head is green: Tests and static checks, Installation and packaging, Rendered reference and report checks, and Python 3.11 all pass.
The round 1 fixes hold. I found one P2 and two P3 items. All three are in the native CDP port change, and the first comes from running a real server binary, which the PR had not done.
P2: src/harness/web_fetch/providers/headless.py:925: with a real CDP listener, the run almost always stays on the other browser
Problem: the PR body says that if the server has exited when the connection returns, the connection is discarded, "so a run does not continue on another process's browser". It describes the remaining gap as a limit, but with a real server that gap is the usual outcome.
I ran native_cdp_browser with real Playwright and Moli 1.1.17. A second Moli server was already listening, and the first candidate port was forced onto it:
| Outcome (30 runs) | Count |
|---|---|
| Handshake finished first, and the context yielded the other server's browser | 28 |
| Our server's exit was seen, and it restarted on a new port | 2 |
- In the 28 runs, our server exited with code 1 about 5 ms after the context was entered, and nothing reported an error.
- This is not a regression, because the old code had the same hole, and #170 tracks ownership proof.
- However,
test_foreign_cdp_server_is_not_used_after_this_server_lost_the_portpasses only because its fake handshake waits for the server to exit. The real order is usually the opposite. - Parallel native servers are the most plausible thing to hold a lost port, so the case this path handles is rarely the one that occurs.
Fix:
- Correct the PR text: restart is reliable for a non-CDP listener, while a real CDP listener usually wins the race (28 of 30 with Moli). Record the same measurement in #170.
- Consider a cheap detection that needs no
psutil: on normal exit from theyield, raise ifprocess.poll() is not None. Our server exits within milliseconds of losing the port, so any real page load would end with it dead, and the attempt would fail instead of being silently measured on the wrong browser. The check also fails an attempt whose server really crashed mid-call, which seems correct. If you prefer to defer this, add it to #170 as an option.
P3: src/harness/web_fetch/providers/headless.py:847: a silent listener uses the whole deadline, so the restart cannot help
Problem: connect_over_cdp gets the full remaining deadline. If a listener accepts the connection but never answers, Moli exits at once while the handshake keeps blocking. With an 8 s budget I measured two processes started and TimeoutError: Native CDP server startup exceeded the call deadline at 8.01 s. The old code also blocked here, and the attempt fails with an error rather than being contaminated. The PR body does not mention this path.
Fix: add one line to the PR's limits. No code change is needed unless you want to cap the handshake timeout.
P3: src/harness/web_fetch/providers/headless.py:918: nothing tests that the log check is limited to the current attempt
Problem: changing the os.pread to read from offset 0 leaves all 11 tests in tests/test_native_cdp_port.py passing. With that change, an attempt that fails for an unrelated reason after an earlier lost port would be treated as another lost port.
Fix: add a test where the first attempt loses the port and the second exits with an unrelated log. Assert that it does not retry and that the error is the second attempt's log.
What I verified without finding a defect
- Round 1 fixes: the new tests fail when the code is broken. I removed the post-connect liveness check, set the attempts to one, removed the exit-code message, removed
sessions.kill, and forced the terminal-state branch, and each caused a failure. I did not repeat the round 1 mutations for the P95 cell and theexcepttypes; the author reports those. - Real binary: Moli on a held port prints
Address already in use (os error 48)and exits with code 1, which_ADDRESS_IN_USEmatches. A free port and a non-CDP HTTP listener both behave as claimed. Lightpanda and Obscura were not available, so their messages remain unverified. - Command and diagnostics: the argument order is unchanged, the attempt's log is read correctly, every process has exited at the end, and a Moli log keeps all attempts.
find_free_port: no caller remains in this repository. The pinned upstream only declares it on its own protocol and its own backend.run.find_free_portinresource_matrix.pyis unrelated.- Catalog P95:
percentileis nearest-rank rounded to two decimals and matches the shared definition. Neither the renderer's contracts nor any golden route binds the value, and no profile underevaluation/carriesreport_archive_sha256. readiness_retries: it is assigned once in thetryand is 0 on every earlier path, so the values match the old code.service._submit: the private shape is the same inPlaywrightReplayTool, and there is no public alternative.har.py: the keeps-the-request-object claim holds, and an unregistered request is reported inrecorder.errors.web_search/review.py:_kill_sessiononly acts on a live process, so a normal exit behaves as before. Completed jobs keep their state.review_runner.pyis in theimplementation_sha256ofreview_execution.py, so an unfinished review directory must be restarted, as the existing check demands; stored evidence is not affected.- Local checks: ruff passes both configurations. The golden reports, port, review, catalog, headless runner and
tests/environmentstargets ran with 249 passed and no route hash changes.
There was a problem hiding this comment.
✅ Re-review complete · 6364866
No findings in this incremental review.
|
Review round 2 is addressed on head Fixed:
Limits of the fix, also in the PR body:
CI on |
lanyue-llk
left a comment
There was a problem hiding this comment.
Independent review, round 3
Head 63648668. No defects found. I did not approve or request changes.
What I verified
CI: all checks pass on this head: Tests and static checks, Installation and packaging, Rendered reference and report checks, Python 3.11. main is still the PR's base (a239d1cc).
Local runs (Python 3.11, locked environment):
- Both ruff gates pass.
test_native_cdp_port.py,test_golden_reports.py,test_catalog_report.py,test_catalog_contracts.py,web_search/test_review.pyandtest_review_runner.py: 108 passed.- No golden route hash changed.
Real binaries, using native_cdp_browser with real Playwright and a local page, 5 runs each:
| Engine | Result |
|---|---|
Obscura, with allow_private_network |
5 of 5 completed |
| Lightpanda | 5 of 5 completed |
| Moli | 5 of 5 completed |
No run failed falsely on the new exit check. The Obscura run covers the normal path that the PR's test plan says it could not exercise, because setting allow_private_network lets it load the local page.
Address-in-use detection: I started each binary with the flags native_cdp_browser passes, on a held port. Each one exited with code 1, and its log matches _ADDRESS_IN_USE. This includes Obscura with --quiet and Lightpanda's address already in use log.
Mutations, each failing a test in the file named:
| Change | Test file |
|---|---|
Remove sessions.kill from the finally |
web_search/test_review.py |
Make ReviewerSessions.kill skip the kill |
test_review_runner.py, web_search/test_review.py |
Remove the exit check after yield |
test_native_cdp_port.py |
| Keep a connection after the server has exited | test_native_cdp_port.py |
| Remove the attempt bound | test_native_cdp_port.py |
| Remove the Moli diagnostic log capture | test_native_cdp_port.py |
| Skip stopping the server | test_native_cdp_port.py |
What I checked by reading the code
- Exit check reaches the result: a
returninside thewithinheadless_worker.fetchstill runs the exit check. TheRuntimeErrorreaches theexcept Exceptionthere and becomesok=Falsewitherror_type=browser_error. - Multi-attempt Moli log: the extra bind-failure line is harmless to
main_document_url_from_fetch_log, which only matches specificDEBUGlines. - Catalog P95:
percentileis nearest rank, and rounding to 2 places does not change the.2foutput._catalog_percentilehas no remaining references.catalog_release.pyandcatalog_contracts.pydo not read P95.- No file under
evaluation/contains areport_archive_sha256binding.
DockerBackend.find_free_port: no caller remains. The pinned package only defines its own copy and declares the method on its protocol.readiness_retries: it has one assignment in thetry, and the initial value matches the old fallback.id(request): the recorder stores each registered request in_playwright_request_objectsfor its lifetime, as the PR says.- Review job:
finallykeeps a completed state and only overwrites a state that is not completed. The default failure message is asserted for an unexpected error. - Issues section: every #165 item has a result in the PR, and #170 holds the measurements and the remaining ownership gap, so
Closes #165is accurate. - Public repository rules: no attribution lines in commits, and no local paths or usernames in the diff.
Limits of this review
I did not run the full suite locally. CI is the gate for that. I also did not repeat the round 2 measurements for a second real CDP server on the forced port.
…hare catalog P95 Restart a native CDP server on a new port when it reports that another process took the chosen port, and stop trusting an answer on that port once the server has exited. Record a terminal state and reap the reviewer on every web search review job exit path, and treat KeyError and TypeError from a malformed opinion as a failed job. Use the shared nearest-rank percentile for the catalog report P95, and replace locals().get with an initialized variable in the replay runner.
…shake first A foreign listener can fail the handshake while the server is still reporting its failed bind. Give the server a short grace to exit before raising, so that case reaches the restart path.
…out a port conflict A server that exited during the grace period discarded the handshake error, so a silent exit raised an empty RuntimeError. Re-raise the handshake error unless the attempt log reports a lost port, and name the exit code when a server exits silently before any handshake.
Nothing calls it, here or in the pinned webarena_verified package. The upstream ContainerBackend protocol still declares it, but that protocol is not runtime-checked and this repository runs no static type check.
6364866 to
439c302
Compare
Issues
Closes #165
Follow-up: #170 tracks the remaining native CDP ownership gap described below.
Summary
I checked each of the five items against current code. The table gives the result for each part.
_catalog_percentileindex.html: it is not in the catalog manifest,catalog_release.pyandvalidate_catalog_acceptance_reportdo not check it, and no golden route covers it. The report now callslexbench_webfetch.metrics.percentile.native_cdp_browserport raceDockerBackend.find_free_portwebarena_verifiedpackage. The upstreamContainerBackendprotocol still declares it, butDockerBackenddoes not inherit from that protocol, the protocol is notruntime_checkable, and this repository runs no static type check, so only static conformance is affected. If an upstream bump starts calling it, the call fails withAttributeError. The unrelatedrun.find_free_portinlexbench/resource_matrix.pyis a different function.id(request)inhar.py_playwright_request_objectskeeps every registered request for the recorder's lifetime, so an id cannot be reused. Playwright caches the API wrapper on its implementation object, soresponse.requestand the event'srequestare the same object. If capture fails, the request is not registered, the error is already inrecorder.errors, and HAR assembly only walks registered keys.locals().get("readiness_retries", 0)try, with the same value on every path.service._submitinwebarena_replay.pyservicecomes from upstreamBrowserTool._get_service(), andPlaywrightReplayToolimplements the same private shape. Renaming it here would break the upstream tool.web_search/review.pyjob loop_successfuland_public_executionaccept only completed jobs, whose state is unchanged. See below.Native CDP port
The servers take a numeric port and bind it themselves, so a reservation cannot be held across the launch. The fix detects a lost port and recovers:
os.pread, because the child shares the file offset. A Moli diagnostic log keeps the output of every attempt.Remaining limits (#170 tracks the ownership gap and has the measurements):
connect_over_cdpuntil the call deadline, so the restart cannot help. The review measured two processes started and aTimeoutErrorat 8.01 s with an 8 s budget. The old code also blocked here, and I did not cap the handshake.psutil, which is not in theheadless-evalextra, and adding it means a lockfile change. Binding the port in the parent would need server support for an inherited socket. I did not check whether the server binaries could support that.Review job
An unexpected error used to leave
status.jsonatrunningwith no attempt status. An error while saving the first status could also leave the reviewer running until the run ended. Now:finallyblock kills and reaps the reviewer through the newReviewerSessions.kill, then writes a terminal state on every exit path.KeyErrorandTypeErrorfrom a malformed opinion now count as a failed job, matching_successful. Other unexpected errors still propagate after the state is recorded.Effect on reports
No stored evidence, profile or receipt changes, and already published reports are unchanged. Stored catalog archives still verify, because nothing rebuilds them.
A future rebuild of a catalog report will show a nearest-rank P95 instead of an interpolated one.
report_archive_sha256covers the whole archive, includingindex.html, so if that value changes the rebuilt report needs a new archive binding in its profile (catalog_contracts.py).Test plan
Run on head
63648668with the locked Python 3.11 environment. CI results are posted in the PR comment.ruff check --config 'include=["*.py"]' --select F,TID252 .andruff check: pass.tests/test_native_cdp_port.py,tests/test_golden_reports.py,tests/test_headless.py,tests/test_headless_runner.py,tests/test_headless_access.py: 109 passed, 1 failed. The failure,test_headless.py::test_converter_shared_and_nonzero_not_converted, is on the known local macOS list. No golden route hash changed.40452923, with no changes to these areas since:tests/web_search,tests/test_review_runner.py,tests/trajectory_replayandtests/environmentspassed. They were not rerun locally on this head, and CI runs the full suite.tests/test_native_cdp_port.pyruns a stand-in server binary against real held sockets, and its fake handshake forces each ordering. It covers a free port, a non-CDP listener, a handshake rejected before the server exits, a handshake failure from a running server, a handshake failure followed by a silent or unrelated exit, a silent exit before any handshake, a CDP listener with either exit order, an exit while the browser is in use, a caller error alongside an exit, an unrelated failure after a lost port, bounded attempts, a non-port failure and a missing binary.tests/trajectory_replay/test_catalog_report.pybuilds five tasks whose interpolated P95 (8.80) and nearest-rank P95 (10.00) differ, and asserts the rendered cell.tests/web_search/test_review.pyandtests/test_review_runner.pycover a malformed opinion that reachesvalidate_result, a real reviewer killed after an error before the wait, and the newkill. I addedpollto one existing fake process intest_review.py, because the job now calls it.KeyErrorandTypeErrorfrom theexcept, dropping the handshake re-raise, removing the exit check, and reading the log from offset 0 each fail the matching test.