Repository navigation
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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<>(); |
There was a problem hiding this comment.
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.
1fba495 to
75abefb
Compare
Thanks for the review — agreed on the blocking #2490 concern. Per-call pin/retain (blocking) Lease non-null Stale retain / TTL force-release |
oss-maintainer
left a comment
There was a problem hiding this comment.
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— aretain()landing after teardown took thereleaseNowpath leavespendingMirrors=1, deferred=null, and the nextreleaseMirror()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—requireRunningSandboxsoft-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); |
There was a problem hiding this comment.
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; | ||
| } |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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?
addressed the three hardening notes:
Tests added/updated for all three. Happy to adjust further if anything still looks off. |
75abefb to
e243a67
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
[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()); |
There was a problem hiding this comment.
[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) { | |||
There was a problem hiding this comment.
[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.
|
This PR currently conflicts with git fetch upstream
git checkout feature_fix_sandbox_async_npe
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-leaseOnce 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 |
124ab50 to
49664e6
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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() == trueturns a lost async mirror into a singlelog.warnplus per-fileFileUploadResponse.fail(...)results thatSessionTreecurrently 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 anerror-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 = |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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).
Summary: Fix duplicate sandbox creation for subsequent session calls caused by deferred teardown & persist. #2555 introduced the 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. |
7c05a7b to
74d1f7e
Compare
74d1f7e to
cffe02c
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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
SandboxAcquireResultvs sharedSandboxAwarefield — resolved (SessionTree.resolveSandboxForPinnow checksfsRcfirst). getLease()non-null on paths reachingrequestRelease— resolved (SandboxAcquireResultconstructor always substitutesSandboxLease.noop()).- Late retain after synchronous
releaseNowtombstone handling — resolved (State.releasedtombstone plusdoReleaseMirrorclear-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).
requireRunningSandboxchanging synchronous tool behavior — resolved (softFailWhenStopped()defaults tofalse; onlyPinnedSandboxFilesystemoverrides totrue).- Deferred-release race where call B re-acquires the same self-managed sandbox — resolved (
SandboxManager.acquirenowawaitPendingScopeReleases before loading state). - Unbounded
IdentityHashMap<Sandbox, State>if a mirror task is dropped before itsfinally— unresolved (still no timeout/upper-bound/cleanup;releaseMirrorremains 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-threadRELEASE_EXECUTORserializes all deferred teardowns; one hangingstop()/shutdown()blocks every subsequent release/persist/lease-close, leaking leases and keeping later sandboxes alive.
Verified good
retain/releaseMirrorpairing covers submission failure and mirror-taskfinally.- Per-call sandbox resolution prefers
SandboxAcquireResultonfsRcbefore the shared proxy field. requestReleasecloses the lease on every path, including user-managed and already-released branches.awaitPendingScopeReleasegates same-scope acquire behind post-stop persist.doReleaseMirrorclamps 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); |
There was a problem hiding this comment.
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.
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:
‑ 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
SessionTree, prepare data before enqueuing asynchronous mirror tasks and then invokeretain(). Roll back the reference count upon submission failure. Decrement the count inside thefinallyblock.stop()/shutdown()runs on a dedicated cleanup thread, preventing slow‑teardown operations from blocking the global mirror queue.‑ 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).
‑ 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 testmvn -pl agentscope-harness -am -DskipITs -Dtest=SandboxBackedFilesystemTest -Dsurefire.failIfNoSpecifiedTests=false testsession-tree-mirror