Skip to content

fix(harness): defer self-managed sandbox shutdown until session mirro… - #3094

Open
xy-ygz wants to merge 1 commit into
agentscope-ai:mainfrom
xy-ygz:feature_fix_sandbox_async_npe
Open

xy-ygz wants to merge 1 commit into
agentscope-ai:mainfrom
xy-ygz:feature_fix_sandbox_async_npe

Conversation

@xy-ygz

@xy-ygz xy-ygz commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Summary

Fix NPE caused by synchronous call shutdown clearing sandbox connections before async sandbox write completes
Fixes #3036

Behavior notes (ops)

Repair Ideas:
When a call completes, if there are still outstanding asynchronous mirror tasks relying on the sandbox connection, do not destroy the connection immediately. Defer the release ownership until the reference count drops to zero.

Key changes:

  1. Add a new deferred‑release coordinator
    ‑ Enqueue mirror task: call retain() (increment reference count by 1)
    ‑ Task completion: call releaseMirror() (decrement count by 1; perform real shutdown only when count reaches zero)
    ‑ Call teardown: call requestRelease() — if pending tasks exist, defer destruction; otherwise shut down immediately
    ‑ Self‑managed sandbox: keep existing behavior; do not physically destroy the sandbox instance
  2. In SessionTree, prepare data before enqueuing asynchronous mirror tasks and then invoke retain(). Roll back the reference count upon submission failure. Decrement the count inside the finally block.
  3. Destruction must not block mirror threads. Deferred stop()/shutdown() runs on a dedicated cleanup thread, preventing slow‑teardown operations from blocking the global mirror queue.
  4. Defensive safeguards
    ‑ When the sandbox is already stopped (isRunning() == false), treat upload/download as soft‑fail to avoid crashing on dead connections.
    ‑ Prevent unintended destruction when reference‑count underflow occurs (count goes negative).
  5. Test coverage
    ‑ Deferred‑release logic
    ‑ Sandbox shutdown only after completion of dual tasks (segment‑level + full‑file mirroring)
    ‑ Avoid premature teardown on reference‑count underflow

Test plan

  • mvn -pl agentscope-harness -am -DskipITs -Dtest=SandboxMirrorReleaseCoordinatorTest,SessionTreeMirrorTest -Dsurefire.failIfNoSpecifiedTests=false test
  • mvn -pl agentscope-harness -am -DskipITs -Dtest=SandboxBackedFilesystemTest -Dsurefire.failIfNoSpecifiedTests=false test
  • Manual: self-managed K8s/Docker call with session flush — mirror completes, then pod/claim terminates; no NPE on session-tree-mirror
  • Manual: user-managed sandbox path still reuses sandbox across calls (no shutdown on release)

@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Defers self-managed sandbox stop/shutdown (and the lease close) until in-flight session mirrors drain, via a new process-wide SandboxMirrorReleaseCoordinator, plus soft-fail when the bound sandbox has already stopped. The root cause reads correctly and the coordinator's pairing/underflow handling is careful.

Verdict

One blocking concern: the sandbox that gets retained is resolved from the shared SandboxAware.getSandbox() field instead of the per-call RuntimeContext binding, which is precisely the race #2490 fixed — under concurrent distinct sessions the deferral protects the wrong sandbox and the fix is a no-op for the reported scenario.


Automated review by github-manager-bot

});

private final Object lock = new Object();
private final IdentityHashMap<Sandbox, State> states = new IdentityHashMap<>();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The process-wide IdentityHashMap<Sandbox, State> only shrinks in doReleaseMirror (count hits 0 or goes negative) and in doRequestRelease. A retain() whose mirror task never runs — MIRROR_EXECUTOR rejecting/shutting down while a task is queued, or a task killed before its finally — pins both the entry and the deferred SandboxAcquireResult (lease, pod/claim) forever, and awaitReleaseQuiescence does not observe it because nothing was ever submitted to RELEASE_EXECUTOR. Consider stamping each registration and force-releasing (with an error log) any deferred release older than a bounded grace period, so a lost mirror task cannot leak sandboxes.

@xy-ygz
xy-ygz force-pushed the feature_fix_sandbox_async_npe branch from 1fba495 to 75abefb Compare September 11, 2026 14:57
@xy-ygz

xy-ygz commented Sep 11, 2026

Copy link
Copy Markdown
Contributor Author

Summary

Defers self-managed sandbox stop/shutdown (and the lease close) until in-flight session mirrors drain, via a new process-wide SandboxMirrorReleaseCoordinator, plus soft-fail when the bound sandbox has already stopped. The root cause reads correctly and the coordinator's pairing/underflow handling is careful.通过一个新的进程级机制,将自我管理的沙箱 stop / shutdown 的相关操作(包括租约的终止)推迟到当前正在进行的会话处理完成后再执行。如果被管理的沙箱已经停止了运行,系统会采取软故障处理方式。该方案的根源处理方式是正确的,协调器在处理配对或流量不足的情况时也相当谨慎。

Verdict

One blocking concern: the sandbox that gets retained is resolved from the shared SandboxAware.getSandbox() field instead of the per-call RuntimeContext binding, which is precisely the race #2490 fixed — under concurrent distinct sessions the deferral protects the wrong sandbox and the fix is a no-op for the reported scenario.一个需要解决的阻塞问题在于:被保留的“沙箱”实际上是从共享的 SandboxAware.getSandbox() 字段中获取的,而不是从每次调用时单独绑定的 RuntimeContext 字段中获取的。这正是之前所解决的“竞态条件 #2490 ”问题。在多个并发会话的情况下,这种处理方式会错误地保护了错误的“沙箱”;而对于所描述的场景来说,这种修复措施实际上没有任何效果。

Automated review by github-manager-bot由 github-manager-bot 自动完成审核流程

Thanks for the review — agreed on the blocking #2490 concern.

Per-call pin/retain (blocking)
Fixed: pinIfSandbox now resolves the sandbox from SessionTree.fsRc's SandboxAcquireResult first, and only falls back to the shared SandboxAware.getSandbox() field for context-free callers. Added flush_retainsPerCallSandboxFromFsRc_notSharedProxyField to cover the concurrent distinct-session case (shared proxy field points at B while fsRc binds A → retain/defer A, immediate release B).

Lease non-null
Confirmed: SandboxAcquireResult always supplies a non-null lease (SandboxLease.noop() when no guard), including userManaged. Documented on SandboxMirrorReleaseCoordinator and SandboxLifecycleMiddleware.

Stale retain / TTL force-release
submitPinnedMirror already rolls back retain if MIRROR_EXECUTOR.execute fails. A task that never reaches finally (executor shutdown / thread kill) is not covered in this PR — the mirror executor is a process-lifetime single-thread daemon in normal operation. Happy to track a bounded grace-period sweeper as a follow-up if you want it in-tree before merge; otherwise we'll keep it as a known residual.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review after the new commits (75abefb1): the blocking concern from my previous review is resolved. SandboxMirrorReleaseCoordinator.requestRelease(manager, result) now takes the per-call SandboxAcquireResult from RuntimeContext instead of resolving the sandbox from the shared SandboxAware.getSandbox() field, so the deferral protects the correct sandbox and the #2490 per-call-binding invariant is preserved (the middleware javadoc also documents this now). submitPinnedMirror closes the retain/release pairing and moves prepare-side failures before retain, and awaitMirrorQuiescence drains both the mirror executor and the new release executor under one shared deadline. This looks good to me — the remaining notes are hardening/documentation, not blockers.

Verdict: COMMENT (approve-equivalent). CLA is signed ✅; I am leaving the previous CHANGES_REQUESTED state for a maintainer to lift, since the follow-up commits addressed it.

Findings:

  • [Warning] SandboxMirrorReleaseCoordinator.java:245 — a retain() landing after teardown took the releaseNow path leaves pendingMirrors=1, deferred=null, and the next releaseMirror() drops the entry without releasing (potential leaked running sandbox). No guard inside the coordinator today.
  • [Warning] SandboxMirrorReleaseCoordinator.java:232 — duplicate release requests keep only the first deferred result; please confirm two concurrent calls can never share one self-managed sandbox instance.
  • [Info] SandboxBackedFilesystem.java:133 — requireRunningSandbox soft-fails for synchronous callers too, not just async mirrors.

Automated review by github-manager-bot

}
if (releaseNow) {
// No outstanding mirrors: keep historical sync teardown on the call thread.
performRelease(manager, result);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the one branch I would still like pinned down. If a late retain() (line ~169) lands after call teardown already took the releaseNow path here, the map is left with pendingMirrors == 1, deferred == null. The next releaseMirror() then hits the pendingMirrors == 0 branch, removes the entry and schedules nothing — so the self-managed sandbox is never stopped and its lease is never closed. submitPinnedMirror looks like it prevents this today (retain is the first statement inside a synchronous method), but the coordinator itself has no guard. Consider recording a released marker (or dropping the deferred result on the floor with a warn) so a future caller that retains after teardown cannot leak a running sandbox, and/or assert-and-log when releaseMirror finds deferred == null while a release for that sandbox has already been requested.

e);
}
return;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

For the "duplicate release request while mirrors are pending" case the comment says the first deferred result keeps ownership of the destructive release. That is right for a single-call lease, but if a sandbox is shared by two concurrent calls that both reached teardown (same instance, two SandboxAcquireResults), the second call's SandboxManager.release(result) never runs at all — only the first result is released. If that shape cannot happen (one self-managed sandbox per call), it would help to say so in the class javadoc; if it can, the deferred slot should hold a list of pending results so each call's release/lease-close is executed.

public List<FileUploadResponse> uploadFiles(
RuntimeContext runtimeContext, List<Map.Entry<String, byte[]>> files) {
Sandbox active = requireSandbox(runtimeContext);
Sandbox active = requireRunningSandbox(runtimeContext);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

requireRunningSandbox turns "sandbox present but not running" into a warn + per-file fail(...) response instead of the exception requireSandbox throws. That is exactly what the async mirrors need, but it also changes behaviour for synchronous tool calls that happen to hit a stopped sandbox: they now silently receive failed upload/download responses instead of an exception. Could you confirm that mirrors are the only consumers relying on this, or (safer) route the soft-fail through an explicit "mirror/best-effort" flag on the pinned filesystem so a sync-path regression still surfaces loudly?

@xy-ygz

xy-ygz commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

Summary

Re-review after the new commits (75abefb1): the blocking concern from my previous review is resolved. SandboxMirrorReleaseCoordinator.requestRelease(manager, result) now takes the per-call SandboxAcquireResult from RuntimeContext instead of resolving the sandbox from the shared SandboxAware.getSandbox() field, so the deferral protects the correct sandbox and the #2490 per-call-binding invariant is preserved (the middleware javadoc also documents this now). submitPinnedMirror closes the retain/release pairing and moves prepare-side failures before retain, and awaitMirrorQuiescence drains both the mirror executor and the new release executor under one shared deadline. This looks good to me — the remaining notes are hardening/documentation, not blockers.在新提交之后再次进行审查:我之前指出的那个问题已经得到解决。现在, SandboxMirrorReleaseCoordinator.requestRelease(manager, result) 会从 RuntimeContext 那里获取每次调用所需的 SandboxAcquireResult 数据,而不是从共享的 SandboxAware.getSandbox() 字段中获取这些数据。这样一来,延迟处理机制就能确保正确的沙箱环境得到维护,同时 #2490 的每次调用绑定规则也得以保持不变(中间件的文档中也对此进行了说明)。 submitPinnedMirror 负责处理保留/释放的操作顺序,将准备阶段的错误处理放在 retain 之前处理。 awaitMirrorQuiescence 则确保镜像执行器和新版本执行器都在同一个截止时间内完成工作。我觉得这样很好——剩下的问题都只是与代码的完善或文档记录相关,不会影响系统的正常运行。

Verdict: COMMENT (approve-equivalent). CLA is signed ✅; I am leaving the previous CHANGES_REQUESTED state for a maintainer to lift, since the follow-up commits addressed it.结论:评论已通过。CLA 协议已签署✅;我会把之前的 CHANGES_REQUESTED 状态保留下来,等待维护人员来处理,因为后续的提交已经解决了该问题。

Findings:  研究结果:

  • [Warning] SandboxMirrorReleaseCoordinator.java:245 — a retain() landing after teardown took the releaseNow path leaves pendingMirrors=1, deferred=null, and the next releaseMirror() drops the entry without releasing (potential leaked running sandbox). No guard inside the coordinator today.[警告] SandboxMirrorReleaseCoordinator.java:245 ——在解构操作之后, retain() 通过 releaseNow 路径进行着陆,但最终离开了 pendingMirrors=1, deferred=null 。接下来的 releaseMirror() 操作没有正确释放该入口点(可能导致运行中的沙箱被泄露)。今天,协调器内部没有任何保护机制。
  • [Warning] SandboxMirrorReleaseCoordinator.java:232 — duplicate release requests keep only the first deferred result; please confirm two concurrent calls can never share one self-managed sandbox instance.[警告] SandboxMirrorReleaseCoordinator.java:232 —— 对于重复的发布请求,系统只保留第一个延迟处理的结果。请注意,两个同时进行的请求绝不能共享同一个自我管理的沙箱实例。
  • [Info] SandboxBackedFilesystem.java:133 — requireRunningSandbox soft-fails for synchronous callers too, not just async mirrors.[信息] SandboxBackedFilesystem.java:133 — requireRunningSandbox 的软故障也适用于同步调用者,而不仅仅是异步调用者。

Automated review by github-manager-bot由 github-manager-bot 自动完成审核流程

addressed the three hardening notes:

  1. Late retain after releaseNow
    Added a released tombstone. If a late retain shows up after teardown already released, we log it, keep retain/releaseMirror pairing clean, and do not stop the sandbox a second time (it was already released).

  2. Duplicate requestRelease on a shared sandbox
    Deferred releases are now a list: each call’s release + lease close runs when mirrors drain. Usual case remains one-call-one-sandbox; shared-sandbox is covered.

  3. Soft-fail scope
    Soft-fail only on PinnedSandboxFilesystem (async mirrors). Sync SandboxBackedFilesystem tool calls again throw when the sandbox is already stopped.

Tests added/updated for all three. Happy to adjust further if anything still looks off.

@xy-ygz
xy-ygz force-pushed the feature_fix_sandbox_async_npe branch from 75abefb to e243a67 Compare September 12, 2026 05:19

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review after the force-push (new head e243a67f). The deferred-release design is sound: refcount + tombstone pairing, per-call SandboxAcquireResult pinning (fixes the last-writer-wins shared-slot hazard from #2490), lease always closed, soft-fail scoped to pinned async mirrors while sync tool paths keep hard-fail, and both executors drained within one shared deadline in awaitMirrorQuiescence. Test coverage is thorough (deferral ordering, underflow clamping, per-call pinning, hard-fail vs soft-fail matrix). CLA signed.

Verdict: APPROVED — one low-probability race worth a follow-up test (see inline on releaseForCall), plus two non-blocking notes.


Automated review by github-manager-bot

sandboxManager.release(result);
// Hand destructive stop/shutdown (and lease close) to outstanding session mirrors
// when present; otherwise release immediately. Call binding is already cleared above.
SandboxMirrorReleaseCoordinator.requestRelease(sandboxManager, result);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] Deferred-release race worth confirming: when call A's release is deferred behind outstanding mirrors, a call B for the same (userId, sessionId) that starts before the deferred stop()/shutdown() executes can re-acquire the very same self-managed sandbox instance (via persisted session state) — and then A's pending performRelease shuts it down under B, reproducing the original NPE symptom from the other direction. The window is small (requires B to acquire between requestRelease deferral and the executor actually running the release), but a targeted regression test for "new call re-acquires while release is deferred" would close the doubt. Alternatively, have performRelease skip destructive stop/shutdown when a live acquire for the same sandbox/session exists.


private void doRetain(Sandbox sandbox) {
synchronized (lock) {
State state = states.computeIfAbsent(sandbox, ignored -> new State());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] doRetain unconditionally creates a State entry (computeIfAbsent), and a "late retain after released" only logs an error — the entry is removed again when the paired releaseMirror brings the count to zero, so the tombstone path looks GC-safe. One residual case: if a mirror task is discarded without ever running its finally (e.g. executor shutdown drops queued tasks during JVM teardown), the states entry and its Sandbox key leak. Since Sandbox keys are strong references in an IdentityHashMap, consider a periodic sweep or a max-age on non-pending registrations if long-lived JVMs with repeated sandbox churn are a real deployment shape here.

@@ -112,9 +114,15 @@ public class SessionTree {
* @return {@code true} if the mirrors quiesced within the timeout
*/
public static boolean awaitMirrorQuiescence(long timeout, TimeUnit unit) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] Nice fix draining the release executor within a shared deadline. Two small notes: (1) awaitReleaseQuiescence submits an empty task, so it only waits for releases enqueued before the barrier call — releases scheduled by mirror tasks that begin executing after the submit are not covered; that matches the documented "submitted before this call" contract, just make sure graceful-shutdown callers invoke it after awaitMirrorQuiescence returns true (which the current call ordering does). (2) The process-wide singleton coordinator means multi-agent JVMs share one release thread — fine for teardown throughput, but a slow stop() head-of-line blocks other sessions' deferred releases; acceptable given it is off the mirror path.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged (head feature_fix_sandbox_async_npe). Please rebase (or merge main in) and resolve the conflicts:

git fetch upstream
git checkout feature_fix_sandbox_async_npe
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-lease

Once conflicts are resolved, ping @oss-maintainer for a re-review if the head also moves. This is a one-time reminder.


Automated notification by github-manager-bot

@xy-ygz
xy-ygz force-pushed the feature_fix_sandbox_async_npe branch from 124ab50 to 49664e6 Compare September 25, 2026 03:18

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review after the rebase onto main (conflicts from #2555 resolved) and the new head — thanks for the detailed hand-off note.

The deferred-teardown design is sound: retain/releaseMirror are now paired in one place (submitPinnedMirror, including the submission-failure path), the tombstone + negative-count handling covers late retains, the per-call SandboxAcquireResult pin fixes the last-writer-wins binding from #2490, and running persistState after release is the right order for stop-time mutations (#2555). Three review notes are pinned inline.

One blocker before this is ready: CI is not green on the current head — build (windows-latest) is failing and build (ubuntu-latest) reports cancelled. Please push a fix or re-run, then ping for another look.

Head reviewed: 49664e66d7.


Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [WARNING] agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/PinnedSandboxFilesystem.java:42 — [Warning] softFailWhenStopped() == true turns a lost async mirror into a single log.warn plus per-file FileUploadResponse.fail(...) results that SessionTree currently ignores. Divergence between the session tree in the workspace and the persisted/ mirrored copy then becomes invisible except in logs. Since this is a data-durability path, please consider counting these soft failures (metric or an error-level log after N occurrences) so an operator can tell "sandbox was torn down before the last mirror" from "mirrors are being dropped continuously". (line outside diff)

* Serialises deferred sandbox destruction off the mirror upload thread so a slow
* {@code stop}/{@code shutdown} cannot head-of-line block other session mirrors.
*/
private static final ExecutorService RELEASE_EXECUTOR =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] The deferral has no hard upper bound. states is a process-wide IdentityHashMap<Sandbox, State> keyed by sandbox identity, and a deferred stop → persist → lease close only runs when releaseMirror drains the counter. If a mirror task is ever dropped without hitting its finally (rejected/aborted executor task, a mirror that blocks forever on a dead connection), the sandbox is never released and the map entry leaks. Consider a max-deferral watchdog (e.g. schedule a forced flush N minutes after the first requestRelease for that sandbox), or at least document that mirror tasks must be bounded by their own I/O timeouts.

* @param unit time unit of {@code timeout}
* @return {@code true} if deferred releases quiesced within the timeout
*/
public static boolean awaitReleaseQuiescence(long timeout, TimeUnit unit) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] awaitReleaseQuiescence submits a barrier onto a single-thread FIFO executor, so it only waits for work that was already submitted at call time — a release scheduled by a mirror that drains just after the barrier is submitted will not be covered. Worth stating in the javadoc that this method is only meaningful after SessionTree.awaitMirrorQuiescence returned true (which SessionTree now does — the pairing is correct, the contract is just implicit).

@CLAassistant

CLAassistant commented Sep 25, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@xy-ygz

xy-ygz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

⚠️ Merge conflict detected ⚠️ 检测到合并冲突

This PR currently conflicts with main and cannot be merged (head feature_fix_sandbox_async_npe). Please rebase (or merge main in) and resolve the conflicts:该 PR 与 main 存在冲突,因此无法合并(当前分支为 feature_fix_sandbox_async_npe )。请先重新提交该 PR(或合并 main ),以解决这些冲突。

git fetch upstream
git checkout feature_fix_sandbox_async_npe
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-lease

Once conflicts are resolved, ping @oss-maintainer for a re-review if the head also moves. This is a one-time reminder.一旦冲突得到解决,如果“头部”也发生了移动,那就再检查一次吧。这只是提醒一下而已。

Automated notification by github-manager-bot由 github-manager-bot 自动发送通知

Summary: Fix duplicate sandbox creation for subsequent session calls caused by deferred teardown & persist.

#2555 introduced the stop-then-persist sequence to ensure sandbox snapshot states are correctly flushed to disk under E2B scenarios.
When combining this ordering with our current fix: after the first session call completes, mirror file transfers to the sandbox may still be in progress. The sandbox shutdown and persistence are deferred asynchronously while the call already returns.
If a second call for the same session arrives and tries to acquire the sandbox at this point, it cannot see the pending persisted state, and mistakenly creates a new sandbox.

Added the fix: when the second same-session call starts and hits sandbox acquisition, check whether there is pending deferred sandbox teardown/persist on the session slot. If pending cleanup exists, wait for it to finish first. After reading the up-to-date persisted state, resume execution instead of incorrectly creating another sandbox, then proceed with this call.

@xy-ygz
xy-ygz force-pushed the feature_fix_sandbox_async_npe branch from 7c05a7b to 74d1f7e Compare September 25, 2026 04:35
@xy-ygz
xy-ygz force-pushed the feature_fix_sandbox_async_npe branch from 74d1f7e to cffe02c Compare September 25, 2026 04:38

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

The new head resolves the per-call binding concern by reading SandboxAcquireResult from fsRc before the shared SandboxAware fallback, and adds awaitPendingScopeRelease in SandboxManager.acquire so a follow-up call for the same scope cannot resume before the previous call's post-stop persist lands. The deferred-teardown design is sound and the test coverage is broad. I am leaving a comment rather than approving because the previous review's warning about unbounded states retention on dropped mirror tasks remains, and the new single-thread release executor can be head-of-line blocked by one hanging stop()/shutdown().

Previous round's findings

  • Per-call sandbox binding via SandboxAcquireResult vs shared SandboxAware field — resolved (SessionTree.resolveSandboxForPin now checks fsRc first).
  • getLease() non-null on paths reaching requestRelease — resolved (SandboxAcquireResult constructor always substitutes SandboxLease.noop()).
  • Late retain after synchronous releaseNow tombstone handling — resolved (State.released tombstone plus doReleaseMirror clear-tombstone path prevents a second destructive release).
  • Duplicate/second release request while mirrors are pending — resolved (deferred list queues one entry per call and flushes all when the count reaches zero).
  • requireRunningSandbox changing synchronous tool behavior — resolved (softFailWhenStopped() defaults to false; only PinnedSandboxFilesystem overrides to true).
  • Deferred-release race where call B re-acquires the same self-managed sandbox — resolved (SandboxManager.acquire now awaitPendingScopeReleases before loading state).
  • Unbounded IdentityHashMap<Sandbox, State> if a mirror task is dropped before its finally — unresolved (still no timeout/upper-bound/cleanup; releaseMirror remains the only shrink path).
  • Soft-fail async mirror drops with only a warn log and no operator-visible counter/metric — unresolved (still a data-durability blind spot).

Findings

  • [Warning] agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxMirrorReleaseCoordinator.java:478 — The single-thread RELEASE_EXECUTOR serializes all deferred teardowns; one hanging stop()/shutdown() blocks every subsequent release/persist/lease-close, leaking leases and keeping later sandboxes alive.

Verified good

  • retain/releaseMirror pairing covers submission failure and mirror-task finally.
  • Per-call sandbox resolution prefers SandboxAcquireResult on fsRc before the shared proxy field.
  • requestRelease closes the lease on every path, including user-managed and already-released branches.
  • awaitPendingScopeRelease gates same-scope acquire behind post-stop persist.
  • doReleaseMirror clamps negative counts and takes over deferred releases on underflow.
  • Tests exercise deferred release, dual-mirror counting, per-call pin, underflow, and stopped-sandbox soft-fail paths.

Automated review by github-manager-bot

try {
work.manager.release(work.result);
} catch (Exception e) {
log.warn("[sandbox-mirror-release] Sandbox release failed: {}", e.getMessage(), e);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The deferred-release executor is a single daemon thread, so one sandbox whose stop()/shutdown() hangs (e.g. a stuck cloud API call) blocks every subsequent deferred teardown behind it. Leases for later calls stay open and later sandboxes are never released or persisted. Use a bounded thread pool with per-task timeouts, or isolate slow teardowns so one bad sandbox cannot starve the whole release queue.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

4 participants