Skip to content

refactor(agent): preserve Stagehand client leases - #20451

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
6ba3i:fix/agent-stagehand-client-lifetime
Oct 8, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
6ba3i:fix/agent-stagehand-client-lifetime

Conversation

@6ba3i

@6ba3i 6ba3i commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator

Stagehand clients could be closed by TTL or LRU eviction while an active session still used them. This adds leases so eviction and runtime shutdown defer closing until every operation releases the client.

Constraint: Preserve cached clients until session cleanup completes.
Rejected: Closing on eviction | active sessions can still use the client.
Confidence: high
Scope-risk: narrow
Directive: Keep cache leases around every Stagehand operation.
Tested: component tests, race tests, build, Compose, concurrent API smoke.
Not-tested: GPU runtime.
@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9ad8da92-58c2-4350-8694-448b1a13865c
📥 Commits

Reviewing files that changed from the base of the PR and between ead4696 and 2c082e4.

📒 Files selected for processing (1)
  • internal/agent/component/stagehand_runtime.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The Stagehand runtime serializes client acquisition and eviction. Task and extraction operations use client leases. Retired clients close after their active leases are released.

Changes

Stagehand client lease lifecycle

Layer / File(s) Summary
Serialized cache and lease lifecycle
internal/agent/component/stagehand_runtime.go
The runtime mutex protects acquisition and eviction. TTL and LRU eviction retire removed entries, and Close marks the runtime closed. Retired clients close when no active leases remain.
Task and extraction leases
internal/agent/component/stagehand_runtime.go, internal/agent/component/stagehand_runtime_test.go
RunTask and RunExtract acquire and release client leases. Tests cover TTL, LRU, and shutdown eviction during active operations, last-lease closure, concurrent closes, and acquisition after shutdown.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant RunTask
  participant stagehandRuntime
  participant StagehandClient
  RunTask->>stagehandRuntime: leaseClient
  stagehandRuntime-->>RunTask: client and release function
  RunTask->>StagehandClient: run task
  stagehandRuntime->>stagehandRuntime: retire cached entry on eviction
  RunTask->>stagehandRuntime: release lease
  RunTask->>StagehandClient: close after final lease
Loading

Suggested reviewers: yuzhichang

Merge Risk: ⚪ Minimal · up to 2c082

No actionable merge-blocking issue is established; the change is mergeable after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 8e500

The change protects active browser operations from premature cleanup without adding an observed operation or permission. Active clients can now survive eviction and shutdown, so resource limits and shutdown integration remain important. End-to-end access controls were not established by this review.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — TTL and LRU eviction now bound cache membership, not all live clients. An evicted entry can remain alive under existing leases while another acquisition creates a replacement. The inspected runtime does not impose a separate bound on those retained entries.

Trust Boundaries and Controls

  • observed — The cache identity remains BaseURL, API key, and model name, rather than an explicit tenant identifier. Request validation and the session sinks receiving instructions, navigation URLs, schemas, and model configuration are unchanged from the parent implementation. This lifecycle change does not establish a new tenant-isolation control or a newly reachable sink.

Resilience and Maintainability Implications

  • observed — Acquisition increments ownership under the same mutex used for retirement, preventing eviction from closing an entry between lookup and lease registration. Client Close runs outside that mutex and is guarded against duplicate execution. These controls preserve cleanup capability during concurrent eviction and shutdown.

Hardening Proposals

  • proposed — If live browser-server concurrency is a security resource budget, enforce it independently of cache capacity and define a bounded shutdown-drain policy. Preserve active leases during cleanup rather than treating eviction as forced cancellation.
  • proposed — Consider making each release callback idempotent before adding cancellation or cleanup wrappers that might invoke it more than once. Current production callers release once, but duplicate invocation would corrupt ownership accounting and could strand a retired client.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes preserving Stagehand client leases, which is the main change.
Description check ✅ Passed The description explains the defect and the lease-based fix. It omits the required "### Summary" heading, but the required summary content is present.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the client cache,
While leases keep each client near.
TTL and LRU retire entries,
But active work can finish clear.
Then the last lease closes the door,
And shutdown waits no more.

Comment @coderabbitai help to get the list of available commands.

@6ba3i
6ba3i requested a review from wangq8 September 30, 2026 07:35
@6ba3i 6ba3i added the ci Continue Integration label Sep 30, 2026
@wangq8
wangq8 requested a review from yuzhichang September 30, 2026 08:02
r.cache.Range(func(k, v any) bool {
e := v.(*stagehandClientEntry)
if e.lastUsedAt.Load() >= cutoff {
return true // still fresh

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is r.mu unlocked here?

removed = append(removed, e)
}
}
return true

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is r.mu unlocked here?
Tracking lock is hard. Suggest add a helper function which lock at the beginning, then defer unlock immediately.

@yuzhichang
yuzhichang merged commit e6bc61d into infiniflow:main Oct 8, 2026
6 checks passed
@6ba3i
6ba3i deleted the fix/agent-stagehand-client-lifetime branch October 14, 2026 03:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants