Skip to content

fix(browser): preserve tab ownership during lazy cleanup - #137671

Merged
steipete merged 2 commits into
mainfrom
codex/browser-cleanup-ownership
Sep 4, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/browser-cleanup-ownership

Conversation

@steipete

@steipete steipete commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #137502.

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers can help update the branch when needed.

What Problem This Solves

Session cleanup could initialize Browser runtime even when the session owned no browser tabs. Independent reproductions also found cleanup closing or removing a replacement registration, absorbing a replacement's cleanup request, and failing to coalesce requests that overlapped lazy client preparation.

Why This Change Was Made

Browser maintenance now resolves runtime dependencies only when a selected tab needs them. The volatile cleanup owner reserves the target before preparation, revalidates registration and activity after the import, and retires only registrations acquired by that operation. Replacement requests wait and acquire their own operation. Requests covered by the same attempted close share its outcome, including failure; a later independent call can retry.

A sweep revoked before dispatch releases its claim without pretending a close occurred, allowing a waiting lifecycle cleanup to proceed. The reservation remains visible through the outer completion await so two waiting callers cannot repeat a synchronously failed close during handoff. This uses the existing in-flight owner; it adds no completed-failure history or cache.

Durable cleanup retains the existing SQLite owner and revalidates its claim after asynchronous configuration resolution. Broad target deletion, duplicate durable forwarding and a redundant type alias are removed. No schema, storage, SDK, configuration or dependency change.

User Impact

Sessions without browser tabs avoid unrelated Browser initialization during cleanup. Replacement registrations remain available to their current owner, and overlapping cleanup requests share the appropriate operation without deleting a replacement or repeating a failed close.

Evidence and Review Correction

The earlier body incorrectly dismissed a review concern about the gap before acquiring the target reservation. That assessment is withdrawn. A deterministic regression against the original PR observed the unwanted overlapping custom closer. A second regression against the first local repair reproduced duplicate failure during a revoked-sweep handoff. Both failures are retained and both pass on the final source. The fix reserves through preparation rather than retaining completed failure history.

Final source validation passed 87 cases across 13 complete sibling files, including all 26 registry cases, plus the original 14-case Gateway file: 101 distinct selected cases across 14 files. Tests preserve original deadlines and use explicit deferred gates, not sleeps. Coverage includes real loopback HTTP DELETE/CDP WebSocket closure, public SDK facade, cold loading, duplicate bundles, SQLite ownership, route/alias selection, replacement and lifecycle cleanup. Full changed checking passed all 26 normal gates, including plugin/test typechecks, three dead-code scans, lint and architectural guards. The normal build also passed.

Fresh managed Codex P0–P2 review and an independent full-owner source review found no remaining actionable findings. Intermediate failed reproductions, line-limit/type/lint failures and their fixes remain recorded; the final implementation uses ordinary promises without a compiler-lib change, polyfill or cast.

The original hosted Linux 120-second rollback timeout was not reproduced exactly. These passing cases do not establish that timeout's cause. Main's separate fixture repair #137743 joins timed-out cleanup and prepares the real mutation runtime at suite scope; it was not substituted into this original-file proof. No full desktop Browser service was launched: closure proof uses real loopback transports and SQLite with synthetic fixtures.

Production for the whole PR is +150/−107, net +43; tests +584/−6, net +578. The corrective commit alone removes three production lines. The remaining growth records the registration identity required to distinguish activity, replacement and an already-owned cleanup operation. Removed broad deletion and forwarding paths keep that ownership in one place.

Current Landing State

Current head 128b8e3e13a950bafb715eac9de4f8b80909ae26 mechanically rebases the two reviewed commits onto main e5d413f7e54a85f0a365ddcf36bd1ba23afcb212, including the separately approved ordinary-CI availability policy from #137881. All nine files and both stable patch IDs are identical to the prior reviewed 395 head. All nine Browser source/test files are byte-identical to reviewed 0807123; both commits have identical range-diff patches. The latest ClawSweeper review at 04:40 UTC covers 395b1d0 with no actionable code or security finding. Its remaining rank-up is green required CI; its reviewer could not fetch current-main Browser blobs. The maintainer inspected them locally: the entire Browser plugin and core Browser/lifecycle neighborhood are unchanged between the reviewed c86 baseline and current main e5d413f, so this repair is not superseded. All nine final files remain byte-identical after the rebase. The +43 production-line risk is addressed by the registration-identity owner and failure-first transport coverage above. Current-head required CI is complete and green.

Independent verification of 0807123 reproduced three intended failures with the unchanged registry tests on 2dd7591 (23 controls passed), then passed all 124 tests across the complete 14-file owner/transport selection. Targeted formatting, type-aware lint and patch checks passed; source and review-context hashes stayed unchanged. Independent Codex review is scoped-clean with no P0–P2 findings. The cold-import case intentionally runs first within its file; canonical file order passed, with no shuffled-order claim.

A subsequent controlled Linux pair used the exact failed cache CI merge 1da0eec7d51fbd96dc6190370d64ab28fda538ea, which already includes #137743. The original 214-pattern child, unchanged config order and two workers passed all 2,959 tests in both arms. With separate dependency trees and cold Node/Vitest caches, the first rollback took 85.411 seconds before and 4.120 seconds after applying only the four reviewed Browser production files. The other three rollback cases changed from 3.945/3.864/1.762 seconds to 1.260/1.315/0.343 seconds. All 37,354 tracked blobs were verified before and after each run; tests, assertions and deadlines stayed unchanged. The Testbox was stopped.

This one pair supports a substantial Browser initialization cost; the baseline did not exceed 120 seconds, so it is not an exact reproduction of the hosted timeout, a production benchmark or a guarantee against other waits. Both arms used the same machine, whose filesystem pages may remain warm, and parallel completion interleavings are scheduler-dependent. Functional ownership and real transport proof remain the basis for the repair.

Earlier required CI run 33827417711 completed all selected source checks, but four attempts failed the dependency audit on bulk-advisory response deadlines. The last audit ran from 03:13:29 to 03:15:30 UTC. Exact-request diagnostics established TLS and sent the body before a no-header stall; an identical later request succeeded. These are missing audit results, not vulnerability findings or waived checks. The refreshed base inherits the subsequently landed bounded retry/backoff owner from #137825, whose hosted production audit completed successfully. The current PR still requires its own successful checks before landing.

On preceding head 395b1d0, CI run 33832934065 retains 30 passing and 17 skipped jobs. All four attempts failed only the required npm audit and its aggregate gate after the bounded audit requests exhausted their deadlines. An initial lint-job setup failure downloading pnpm with HTTP 504 recovered on the normal failed-job retry; lint itself passed. Attempt four completed at 04:07:35 UTC on September 4; its audit exhausted three requests and ended with the existing 60-second timeout. No audit clearance was obtained. The final base refresh inherits #137881: ordinary CI records service unavailability as an explicit incomplete-coverage warning, while known findings, permanent failures and release/local callers remain blocking. The refreshed head passed its required CI: 32 jobs successful, 17 skipped, no failures. Its production audit exhausted three requests and emitted the explicit incomplete-coverage warning under #137881; this is not complete advisory clearance. No Browser code, test assertion or deadline changed.

Completed current-head integration checks (32 passed, 17 skipped): CI run 33840358148.

@steipete steipete self-assigned this Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete

steipete commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The completed candidate is 7ac66599b10ab1e881d9d83a1a9baea24109b6d6. Failure-first owner tests, actual HTTP/CDP closure, 120 focused tests, the original 2,825-test CI selection, both plugin type gates and the package build pass. The PR body records the final independent review disposition and the preparation/in-flight ownership contract. Current hosted CI has passed its selected code checks; its dependency audit hit the upstream bulk endpoint deadline. No check is waived.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 12:40 AM ET / 04:40 UTC.

ClawSweeper review

What this changes

The PR makes Browser tab cleanup load its runtime only for tabs it owns and preserves tab-registration ownership across overlapping cleanup operations.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 4 items remain

No introduced correctness or security finding was identified. This member-owned Browser cleanup PR remains open pending a successful exact-head required security audit.

Priority: P1
Reviewed head: 395b1d0d22a2ae8655ab468637eb907dbd2e9997

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-boundary repair with strong transport-oriented regression coverage, pending only required exact-head audit clearance.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: The supplied repository state identifies this as a member-authored PR, so the external-contributor proof gate does not apply; independently, the added loopback HTTP/CDP test uses the production cleanup owner and records closure behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies this as a member-authored PR, so the external-contributor proof gate does not apply; independently, the added loopback HTTP/CDP test uses the production cleanup owner and records closure behavior.
Evidence reviewed 7 items Volatile cleanup ownership: The introduced owner is published before lazy client preparation, rechecks its registration afterward, and retires only registrations acquired by that operation.
Durable cleanup boundary: Durable rows retain the existing SQLite claim owner, and the async configuration path rechecks the claim before CDP closure.
Transport-oriented regression coverage: The added test exercises the maintenance entrypoint with loopback HTTP DELETE and CDP WebSocket closure, including a durable tab touched during async runtime lookup.
Findings None None.
Security None None.

How this fits together

Browser session cleanup tracks tabs owned by an agent session, then closes them through the Browser control service or Chrome DevTools Protocol. The registry coordinates lifecycle and idle-sweep cleanup before issuing a close.

flowchart LR
A[Session lifecycle or idle sweep] --> B[Tracked tab registry]
B --> C{Registration still owned?}
C -->|yes| D[Lazy runtime lookup]
C -->|no| E[Preserve replacement tab]
D --> F[Browser control or CDP close]
F --> G[Retire acquired registration]
Loading

Before merge

  • Resolve merge risk (P1) - The exact-head required npm advisory audit has no successful result, which blocks merge readiness.
  • Resolve merge risk (P1) - Current-main Browser blobs could not be inspected locally while the promisor remote and GitHub API were unreachable, so current-main supersession was not independently ruled out.
  • Complete next step (P2) - Obtain a successful required npm advisory audit and aggregate CI gate on the exact current head before merge.
  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.
Agent review details

Security

None.

PR surface

Source +43, Tests +578. Total +621 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 150 107 +43
Tests 5 584 6 +578
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 734 113 +621

Review metrics

Metric Value Why it matters
Production versus tests production +150/-107 (net +43); tests +584/-6 (net +578) Production growth is concentrated in registration identity and the process-global in-flight owner needed to distinguish replacement, activity, and an active cleanup operation.

Merge-risk options

Maintainer options:

  1. Obtain exact-head audit clearance (recommended)
    Rerun or wait for the required npm advisory audit to succeed on this exact head, then recheck mergeability before landing.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Merge only after the required security audit and CI gate are green on the exact current head.

Technical review

Best possible solution:

Keep one cleanup owner per volatile target, retain registration identity through lazy preparation, and merge after a successful exact-head security audit confirms the reviewed head.

Do we have a high-confidence way to reproduce the issue?

Yes—source and the added held-operation tests provide a high-confidence path for the lazy-import, replacement, and cleanup-handoff races, though this read-only review did not execute them.

Is this the best way to solve the issue?

Yes—the repair belongs at the tab registry that owns selection, coalescing, and retirement; downstream caller guards or a completed-failure cache would not preserve registration identity through preparation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 5ebe54c250b3.

Labels

Label justifications:

  • P1: Browser session cleanup could otherwise close or discard a current tab registration during overlapping lifecycle and idle cleanup.
  • merge-risk: 🚨 other: The PR changes process-global concurrent cleanup coordination across lazy runtime preparation and close completion.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied repository state identifies this as a member-authored PR, so the external-contributor proof gate does not apply; independently, the added loopback HTTP/CDP test uses the production cleanup owner and records closure behavior.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Yiğit ERDOĞAN: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain a green exact-head npm advisory audit and aggregate CI gate before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (8 earlier review cycles)
  • reviewed 2026-09-04T00:10:16.770Z sha 7ac6659 :: blocked before merge. :: none
  • reviewed 2026-09-04T01:19:39.508Z sha 7ac6659 :: blocked before merge. :: none
  • reviewed 2026-09-04T01:41:12.802Z sha 2dd7591eb6670fe62fc059b334a4a63521c9466f :: blocked before merge. :: [P1] Reserve cleanup ownership before loading the raw client
  • reviewed 2026-09-04T01:59:46.574Z sha 0807123eb2cc12447a686c7d898eaa8852d0402f :: blocked before merge. :: none
  • reviewed 2026-09-04T02:11:10.123Z sha 0807123eb2cc12447a686c7d898eaa8852d0402f :: blocked before merge. :: none
  • reviewed 2026-09-04T02:40:52.186Z sha 0807123eb2cc12447a686c7d898eaa8852d0402f :: blocked before merge. :: none
  • reviewed 2026-09-04T02:53:03.847Z sha 0807123eb2cc12447a686c7d898eaa8852d0402f :: blocked before merge. :: none
  • reviewed 2026-09-04T03:55:15.484Z sha 395b1d0 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Sep 4, 2026
@steipete
steipete force-pushed the codex/browser-cleanup-ownership branch from 7ac6659 to 2dd7591 Compare September 4, 2026 01:22
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

I am correcting the earlier dismissal of the cleanup-coalescing finding. Please hold this PR for the repair already in progress.

A deterministic regression on the original PR source now reproduces an overlapping custom closer running while the first cleanup waits for its client import. The import at session-tab-registry.ts:623 precedes publication of the in-flight owner at line 642. A synchronous close failure can therefore release its reservation before the preparing request resumes. The whole registry file reported 22 passing tests and this one expected regression failure, with normal process closure and no timeout.

The fix reserves the operation across preparation and dispatch, then keeps the reservation until completion settles. A second failure-first case against the initial local repair exposed an overlapping-waiter handoff that also needed this completion ordering. This does not require a completed-failure cache, and later independent cleanup calls must still retry failed closes.

The new public head 2dd7591e is a mechanical refresh onto main: its complete parent-relative patch and all nine changed files are byte-identical to 7ac66599. I will preserve that refresh and append the corrected, independently reviewed repair after its full checks. Neither these reproductions nor the earlier local timing diagnostic prove the exact cause of the historical Linux 120-second timeout.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 4, 2026
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The body now corrects the earlier coalescing assessment. Head 0807123eb2cc12447a686c7d898eaa8852d0402f reserves cleanup before lazy preparation and holds ownership through completion handoff. Both deterministic failures are retained; final source passes 101 distinct selected cases, full changed checking, build, fresh managed Codex review and independent source review. The repair is production net −3; whole-PR growth and the limits of the historical timeout evidence are stated in the body. Please review the corrected behavior and current head.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 4, 2026
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Supplementary local cleanup evidence for exact head 0807123eb2cc12447a686c7d898eaa8852d0402f, also investigated alongside #137703:

One baseline-then-candidate diagnostic applied all nine exact PR files to the same fixture. Both arms passed the same 14 cases with unchanged calls, assertions, request deadlines and diagnostic markers. The first Browser cleanup call was 63.020 s before and 2.700 s with this PR; the three later calls were 1.026–1.048 s before and 0.133–0.139 s after. The driver's child-and-group interval was 90.853 s and 26.567 s. That interval excludes source rehashing, temporary-runtime removal and receipt publication. The replacement case passed in both arms (2.247 s and 1.333 s); one other case rose from 289 to 290 ms. All raw observations, including slower phase markers, remain retained.

An independent audit matched all 162 diagnostic signatures, 14 case identities, 11 shared source hashes and nine Browser postimages. This is one instrumented local pair, not an order-balanced statistical benchmark, production Gateway timing, normalized-memory measurement or proof of the hosted Linux timeout's cause. The original pair records the Node path/version but not its binary hash or actual loaded-module origins.

To check the swallowed-loader-error possibility, a separate observation-only candidate run recorded the actual worker Browser maintenance and registry module URLs, four empty tracked-tab selections, four normal zero-count returns, and no warning callbacks. All 14 cases passed. It also recorded the actual Jiti resolver and the resolved Node executable hash before and after. Its timings are excluded from the earlier pair; it does not retroactively add missing records to that pair. Positive tab closure remains covered by the separate ownership and HTTP/CDP tests already described in the PR.

No source change or CI retry accompanied this evidence. Attempt 3 of the current CI run still fails the npm advisory audit, so landing remains held. This supplements the existing verification in the body without replacing it.

@steipete
steipete force-pushed the codex/browser-cleanup-ownership branch from 0807123 to 395b1d0 Compare September 4, 2026 03:21
@steipete
steipete force-pushed the codex/browser-cleanup-ownership branch from 395b1d0 to 128b8e3 Compare September 4, 2026 05:24
@steipete
steipete merged commit 05269b5 into main Sep 4, 2026
102 checks passed
@steipete
steipete deleted the codex/browser-cleanup-ownership branch September 4, 2026 05:39
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Sep 4, 2026
Backport main commit 05269b5 (#137671)
unchanged for the 2026.9.2 release candidate.

Avoid loading Browser control, config and transport code for empty cleanup.
Reserve exact tab registrations through client preparation and dispatch so
replacements survive overlapping or cancelled cleanup.

Release-context proof: 105 Browser/SDK tests, 14 Gateway tests, 17 Cron tests,
full build and extension types. The frozen-production negative control
fails on eager imports and replacement ownership. Independent review clean.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
…7671)

* fix(browser): preserve tab ownership during lazy cleanup

* fix(browser): reserve cleanup through client preparation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: browser maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant