browser-harness icon indicating copy to clipboard operation
browser-harness copied to clipboard

`js(expr, target_id=...)` opens a new CDP session on every call and never detaches — iframe loops leak sessions

Open rajarshidattapy opened this issue 3 months ago • 1 comments

Labels: bug, helpers, resource-leak

Description

# src/browser_harness/helpers.py:486-500
def js(expression, target_id=None):
    sid = cdp("Target.attachToTarget", targetId=target_id, flatten=True)["sessionId"] if target_id else None
    try:
        return _runtime_evaluate(expression, session_id=sid, await_promise=True)
    except RuntimeError as e:
        if _is_illegal_return_error(e):
            return _runtime_evaluate(_wrap_js_function(expression), session_id=sid, await_promise=True)
        raise

Every js(..., target_id=...) call issues a fresh Target.attachToTarget. Chrome returns a new sessionId each time. Nothing ever sends Target.detachFromTarget, and the session id is discarded the moment the function returns — so the caller could not detach it even if they wanted to.

The helper layer also cannot clean up after itself, because the daemon strips the session from every Target.* call by design:

# src/browser_harness/daemon.py (handle)
# Browser-level Target.* calls must not use a session (stale or otherwise).
sid = None if method.startswith("Target.") else (req.get("session_id") or self.session)

Impact

This is the documented cross-origin-iframe workflow. interaction-skills/iframes.md and cross-origin-iframes.md both point at iframe_target() + js(..., target_id=...), and the natural shape of that work is a poll or a loop:

tid = iframe_target("checkout.stripe.com")
while not js("!!document.querySelector('#card')", target_id=tid):
    wait(0.5)                                   # one leaked session per iteration
js("document.querySelector('#card').value", target_id=tid)

Each iteration accumulates a live session against the same target. Sessions are held by the browser for the lifetime of the daemon's WebSocket, and the daemon is long-lived by design ("preserves the attached tab across separate CLI invocations"). Each session also gets its own copy of every enabled-domain event stream, which feeds straight into the daemon's shared deque(maxlen=500) event buffer — so a leaking loop can also evict the events wait_for_network_idle() is trying to read.

switch_tab() has the same attachToTarget call but at least stores the result via {"meta": "set_session"}; the js() path stores nothing.

Reproduction

tid = iframe_target("some-iframe-host")
for _ in range(200):
    js("1", target_id=tid)
print(len(cdp("Target.getTargets")["targetInfos"]))   # targets unchanged
# but the browser now holds 200 sessions on that one target

Observable in chrome://inspect or by counting distinct session_id values coming back through drain_events().

Suggested fix

Cache the session per target_id for the life of the process, so repeated calls reuse one session instead of minting a new one:

_IFRAME_SESSIONS = {}

def _iframe_session(target_id):
    sid = _IFRAME_SESSIONS.get(target_id)
    if sid is None:
        sid = cdp("Target.attachToTarget", targetId=target_id, flatten=True)["sessionId"]
        _IFRAME_SESSIONS[target_id] = sid
    return sid

with invalidation on Session with given id not found. That keeps the diff small and does not need a detach path through the daemon's Target.* rule.

rajarshidattapy avatar Aug 29 '26 21:08 rajarshidattapy

I’d like to work on this. Is caching the CDP session per target_id the intended approach, or would you prefer a different session lifecycle?

@gregpr07

rajarshidattapy avatar Aug 29 '26 21:08 rajarshidattapy