Skip to content

fix(web-fetch): prove native CDP server ownership before connecting - #228

Merged
lanyue-llk merged 2 commits into
mainfrom
fix/native-cdp-server-ownership
Nov 4, 2026
Merged

lanyue-llk merged 2 commits into
mainfrom
fix/native-cdp-server-ownership

Conversation

@lanyue-llk

@lanyue-llk lanyue-llk commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What, why and how of this PR

Issues

Closes #170

Summary

native_cdp_browser now connects only after the kernel reports the launched server as the owner of the listening socket on 127.0.0.1:<port>. Until then nothing touches the port, including the old TCP probe, so a listener already on that port is never contacted.

  • Linux: joins /proc/<pid>/net/tcp listening rows to the socket inodes in /proc/<pid>/fd.
  • macOS: asks /usr/sbin/lsof for that process and port.
  • No new dependency: psutil is not needed and uv.lock is unchanged.
  • Why this is a proof: the pid cannot be reused because the child is not reaped yet. Only the exact address counts, because a wildcard listener can lose to a more specific foreign socket on systems that allow both.

Behavior changes:

Case Before Now
Foreign CDP server answers before our server exits Measured against the wrong browser, or caught only if the exit was seen later Never contacted; restart on a new port after the "address in use" exit
Foreign listener that accepts and never answers Handshake held until the call deadline Never contacted; same restart
Server stays alive without holding its port Handshake to whatever answered TimeoutError at the deadline, no handshake
Handshake fails Waited up to 1 s for an exit, then decided Raised at once, because the failure comes from our own server

NATIVE_CDP_BIND_EXIT_GRACE_SECONDS and the handshake-error return path are removed, since they only existed to tell a foreign rejection apart. The check for a server that exits while its browser is in use stays, and its message no longer says the result may come from another process.

Limits

  • Port replaced after the proof (review finding): if the proven server exits and another process binds the address before the handshake, that handshake reaches the other process. The proof cannot prevent this, because it does not reserve the address. The server being alive when the handshake returns shows it held the address throughout, so the other browser is closed and the call fails before a caller gets it, which is the issue's condition for a connection being used. A new test forces this order. Zero contact in this window would need a relay in front of Playwright that verifies each connection. I did not add one, because it would sit in the measured path of a latency benchmark to cover a narrow race whose result is already discarded. That choice is the owner's to overrule.
  • SO_REUSEPORT: two sockets can share an address only if both set it. All three servers exit on a taken port (measured below), so this does not apply to them.
  • Listener in a child process: a server that listens from a child would not pass the check and would time out. Moli, Lightpanda and Obscura all hold the socket in the launched process itself on macOS.
  • Linux binaries: I could not run them here because no Docker daemon is available. The /proc path is exercised by the stand-in tests in CI, not by real Linux servers.
  • Latency: the check adds a small startup cost to measured native CDP calls, and comparisons with earlier cohorts should allow for it. See the table below. Existing evidence is not touched.

Resource image

  • headless_worker.py is unchanged, so worker_sha256, execution_sha256 and adapter_input_sha256 keep their values.
  • Container cohorts need a rebuild to get this fix. The image holds its own copy of headless.py, and the worker imports it from there.
  • Nothing enforces that rebuild. ContainerResourceRunner.validate() compares only the worker hash, so a stale image still passes and keeps the old behavior. Local runs pick up the fix at once.
  • The image needs nothing new. The Linux path reads only /proc, and the worker and server run as the same user.
  • The rebuild has its own blocker: resource.Dockerfile still has COPY harness ./harness, but harness/ moved to src/harness/. I could not run docker build here, and this PR does not fix it.

Test plan

Everything below ran on macOS. Each of the two result tables was one run.

  • Lint gate: both ruff commands pass.
  • Targeted tests: tests/test_native_cdp_port.py, test_golden_reports.py, test_headless_engine_routes.py, test_headless.py, test_headless_files.py, test_network_dns.py and test_container_resources.py gave 108 passed, 8 skipped, 1 failed. The failure is test_converter_shared_and_nonzero_not_converted, on the known local failure list. Golden route hashes are unchanged.
  • How tests were invoked: with pytest -o pythonpath="src ." rather than the PYTHONPATH environment variable, which this environment's command guard refused. Both import this checkout. CI runs the full suite.
  • After the review follow-up (docstring and one new test): test_native_cdp_port.py, test_golden_reports.py and test_headless_engine_routes.py gave 40 passed. CI passed on the final head.
  • Negative control: with the production change removed, the four ownership tests fail. These are the second CDP listener that answers first, the second listener with a lingering server, the silent listener, and the wildcard listener.
  • The test the issue asks for: a real HTTP listener holds the forced port and answers any client. The handshake is a real HTTP request, and the test asserts that the listener received zero requests and that the launched server answered.

Real servers and real Playwright, with a second real server of the same engine holding the forced port. That second server is then stopped, and a local page is loaded through the returned browser:

Engine Rounds Restarted on a new port, page loaded Script errors
Moli 1.1.17 30 30 0
Obscura 10 10 0
Lightpanda 10 8 2

The 2 Lightpanda errors came from my script's own 5 s wait for the second server to stop (TimeoutExpired on that process). No result was taken from those two rounds, so they do not show the ownership path passing or failing. Lightpanda also takes 1.9 to 3.9 s to exit on a taken port, which is why entry takes longer in that case.

Median time to enter native_cdp_browser on a free port, 15 rounds each with a median of one run, so differences of this size are close to noise:

Engine Before After
Moli 45.8 ms 63.8 ms
Lightpanda 63.1 ms 70.3 ms
Obscura 39.1 ms 24.5 ms

@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 · b4f885b

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

Comment on lines +1054 to +1055
browser = playwright.chromium.connect_over_cdp(
f'http://{_NATIVE_CDP_HOST}:{port}', timeout=remaining() * 1000)

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 — Ownership observation does not reserve the port until the handshake. If the launched server exits after _process_listens_on returns true, another process can bind the released address before connect_over_cdp sends its HTTP request. Keeping the child unreaped prevents PID reuse, not socket-address reuse. The subsequent process.poll() rejects the browser but cannot undo requests sent to that foreign listener, so the stated “another listener is never contacted” requirement remains incomplete. The existing exit-during-handshake test connects before stopping the server and does not cover this ordering. Protect the connection against port replacement (another pre-connect poll alone is insufficient), and add a deterministic regression that stops the verified server, binds a foreign listener before the handshake, and asserts zero foreign requests. This is P2 because it requires a narrow server-exit/port-rebinding race.

@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 · a4d8d46

No findings in this incremental 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

Head reviewed: a4d8d460. No defects found (no P0, P1, P2 or P3 findings).

What I verified

The fix itself

  • I read _connect_native_cdp, _process_listens_on, and the Linux and macOS helpers against the code they replace. Nothing touches the port before the ownership check passes, because the old TCP probe is gone. The /proc/<pid>/net/tcp columns, the byte order of the address and the lsof -Fn output match use.
  • NATIVE_CDP_BIND_EXIT_GRACE_SECONDS and the handshake-error return path have no remaining references. In Web Fetch, native_cdp_browser is the only code that launches a native server, and headless_worker.py:261 calls it. Browser Trajectory Replay launches Moli, Lightpanda and Obscura separately in remote_execution.py. Issue #170 is scoped to native_cdp_browser and this PR does not change that track, so I did not review it here.
  • The worker has no waitpid or other reaper, so the claim that the pid cannot be reused holds.

Do the tests fail without the fix?

Restoring the old headless.py outright fails 15 of 16 tests, but only because the harness replaces the socket module, so that says nothing about the fix. I used two targeted mutations instead:

Mutation Result
Replace the proof with a TCP probe The second-listener, lingering-server, silent-listener and wildcard tests fail, plus the two forced-port restart tests
Accept any address on the port Only the wildcard test fails

Real server: I ran Moli 1.1.17 with real Playwright on macOS. A free port worked. In 5 of 5 rounds with a second Moli holding the forced port, the call restarted on a new port. The second Moli was then stopped and a page still loaded through the returned browser.

Test runs

  • tests/test_native_cdp_port.py passed 16 of 16 in three repeat runs.
  • test_native_cdp_port.py, test_golden_reports.py, test_headless_engine_routes.py and test_headless.py together gave 86 passed, 1 failed. The failure is test_converter_shared_and_nonzero_not_converted, on the known local failure list. The golden route tests pass and the diff touches no snapshots.
  • Both ruff commands pass.
  • CI is green on this head. The Linux job ran all of tests, which includes the /proc path through the stand-in servers (19866 passed, 157 skipped).

PR description and repository rules

  • headless_worker.py, worker_sha256, execution_sha256 and adapter_input_sha256 are unchanged, and those hashes cover only the worker file.
  • ContainerResourceRunner.validate() compares only the worker hash, and resource.Dockerfile still has COPY harness ./harness. The resource image section is therefore accurate.
  • uv.lock is unchanged, the diff touches only headless.py and its test file, and I found no attribution lines.

Points for the owner (not defects)

  • Closes #170 and the port-replacement race: the bot's inline comment on the handshake describes a real window. If the proven server exits and another process binds the address before the handshake, that process is contacted. The issue's condition is that a connection is used only after proof. That still holds, because this browser is closed before a caller receives it, and test_listener_that_takes_the_port_after_the_proof_is_never_given_to_the_caller covers it. I agree with the closure, and the PR correctly leaves the choice of a relay to the owner.
  • Not verified on the image: there is no Docker daemon here, so I did not run the Linux binaries. The image pins Moli 1.1.1 and Obscura v0.2.1, which may differ from the macOS versions measured. If one of them listens from a child process or ignores --host, it fails with a TimeoutError rather than a silent wrong result. The first rebuilt-image cohort will show this.

lanyue-llk added a commit that referenced this pull request Nov 4, 2026
Wait until the kernel reports the launched server as the owner of the listening socket on its exact loopback address before any connection to that port. Linux reads /proc and macOS asks lsof, so no dependency is added. A second listener is never contacted, so the handshake no longer needs the post-failure exit grace.
State what the proof does not reserve: a server that exits after it can lose the address before the handshake. The browser from that handshake is discarded before a caller gets it, and a test now forces that order.
@lanyue-llk
lanyue-llk force-pushed the fix/native-cdp-server-ownership branch from a4d8d46 to f76fb41 Compare November 4, 2026 06:01

@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 · f76fb41

No findings in this review.

@lanyue-llk
lanyue-llk merged commit 0051691 into main Nov 4, 2026
7 checks passed
@lanyue-llk
lanyue-llk deleted the fix/native-cdp-server-ownership branch November 4, 2026 06:11
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.

Prove native CDP server ownership before using a connection

1 participant