[Bug]: SessionTree mirror NPEs when it outlives the sandbox — PinnedSandboxFilesystem cannot know the pinned sandbox is closed (regression from #2946, v2.0.3)
Versions: agentscope-harness:2.0.3, agentscope-extensions-sandbox-kubernetes:2.0.3
Regressed by: #2946 (merged 2026-09-06, released in v2.0.3 on 2026-09-07)
Same root cause as: #2147 (still open) — different teardown point
Context: #2490 / #2675 (per-call sandbox binding), #2771 (per-call K8s pod termination), #2777 / #2935 (fire-and-forget flush)
Summary
SessionTree mirrors the session log to the agent's filesystem fire-and-forget. When that filesystem is a sandbox, the queued mirror routinely runs after the sandbox has been shut down and dies with a NullPointerException rather than any meaningful error.
Before #2946 this same race degraded to a No active sandbox warning, because the async mirror resolved the sandbox lazily through the shared slot, which release had already cleared. #2946 pinned the Sandbox instance to fix which sandbox the mirror targets — correct in itself — but the pinned reference is now a hard one, so the mirror walks into a dead sandbox instead of failing soft.
Observed
WARN session-tree-mirror i.a.h.a.filesystem.sandbox.SandboxBackedFilesystem
[sandbox-fs] native upload failed for path: agents/<agent>/sessions/<sessionId>.log.jsonl
java.lang.NullPointerException: Cannot invoke
"io.agentscope.extensions.sandbox.kubernetes.client.CommandExecutor.run(String)"
because the return value of
"io.agentscope.extensions.sandbox.kubernetes.client.Sandbox.commands()" is null
at io.agentscope.extensions.sandbox.kubernetes.KubernetesSandbox.uploadFile(KubernetesSandbox.java:272)
at io.agentscope.harness.agent.filesystem.sandbox.SandboxBackedFilesystem.uploadFiles(...)
at io.agentscope.harness.agent.memory.session.SessionTree.mirrorToFilesystem(SessionTree.java:733)
at io.agentscope.harness.agent.memory.session.SessionTree.lambda$scheduleMirror$6(SessionTree.java:593)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
One run, three log lines 78 ms apart: the trace middleware logs POST_CALL, then [sandbox-client] Connection to sandbox claim '<claim>' has been closed., then the mirror fails.
The
SandboxBackedFilesystemframe's line number is omitted because we shadow that class locally for an unrelated reason. The frame is the unmodified native-transfer branch ofuploadFilesthat callsSandboxFileTransfer.uploadFile.
Root cause
SessionTree.flush()→scheduleMirror()wraps the filesystem viapinIfSandbox(...)and hands the work to the static single-threadedMIRROR_EXECUTOR(threadsession-tree-mirror).flush()returns as soon as the task is queued.PinnedSandboxFilesystempins the concreteSandboxin its constructor (setSandbox(sandbox)) and overridesclearSandboxIfCurrentto a no-op. The override is deliberate — it stops release from un-pinning the instance — butclearSandboxIfCurrentis also the only channel through which this object could learn the sandbox was released (#2675). It therefore holds a hard reference to a sandbox it has no way of knowing is dead.SandboxLifecycleMiddleware.releaseForCall→SandboxManager.releasecallsstop()thenshutdown()for every sandbox withisSelfManaged() == true, at the end of every call.KubernetesSandbox.shutdown()reaches the SDK'sSandbox.closeConnection(), which nullscommandsandfilesand setsclosed = true.- The queued mirror then calls
KubernetesSandbox.uploadFile, which doessdkSandbox.commands().run("mkdir -p ...")with no liveness check → NPE.
Steps 1 and 3 are not synchronised in any way.
This is not limited to user-managed sandboxes
#2771 documents the same step 3 for the stock client: "SandboxLifecycleMiddleware … releases the sandbox after every call: SandboxManager.release() (self-managed path) → stop() → shutdown(). KubernetesSandbox.shutdown() sees claimOwned == true and calls terminate(), deleting the claim and the pod — every call." #2771 was closed on the acquire/resume side; release still shuts the sandbox down per call in 2.0.3. So a plain framework-managed Kubernetes sandbox hits this race too.
Why the existing quiescence API doesn't cover it
SessionTree.awaitMirrorQuiescence exists, but across the whole harness jar it is referenced only by SessionTree itself and HarnessAgent.close() — i.e. container shutdown. Nothing on the sandbox lifecycle path drains the queue, and there is no way to wait for one session's mirror; the executor is static and global, so the only available barrier is "wait for every session".
That is consistent with how the API arrived: #2777 made the flush fire-and-forget on purpose, to unblock conversation completion, and #2935 describes awaitMirrorQuiescence as something HarnessAgent#close() already did, reusing it test-side to stop @TempDir teardown flakiness. It was never introduced as a lifecycle contract for resource owners.
#2147 is the same root cause at a different teardown point and has been open since 2026-07-12: there the late session-tree-mirror write lands on a closed Jedis pool (Pool not open) after HarnessAgent.close() returned. Its "Expected" list — stop accepting new mirror jobs on close, drain or cancel accepted ones, close the executor before returning — is exactly what the sandbox path needs as well. Filing separately because the fix location differs (pinned filesystem / sandbox release rather than agent close), but the two should probably be solved together.
Secondary defects
KubernetesSandbox.uploadFile/downloadFiledon't check liveness. The SDK'sSandboxalready exposesisActive(). A closed sandbox should produce aSandboxExceptionnaming the cause, not an NPE from dereferencing a nulled field.isRunning()lies after shutdown.KubernetesSandbox.shutdown()overrides the interface default and only callsterminate()/closeConnection(); it never clearsAbstractBaseSandbox'srunningflag, soSandbox.isRunning()still returnstrueon a shut-down sandbox. Callers wanting to guard defensively have no reliable check on theSandboxinterface and must downcast toKubernetesSandboxforgetSdkSandbox().isActive().
Suggested fixes, roughly in order of value
- Have
PinnedSandboxFilesystem(orSessionTree.mirrorToFilesystem) skip the write and log at debug when the pinned sandbox is no longer alive — the mirror is best-effort by design. - Make
KubernetesSandbox.uploadFile/downloadFilefail with aSandboxExceptionon a closed sandbox instead of an NPE. - Clear the
runningflag inKubernetesSandbox.shutdown()soisRunning()is trustworthy. - Drain the mirror queue in
SandboxManager.releasebeforeshutdown()for self-managed sandboxes, or expose a per-sessionawaitMirror(sessionId, timeout)so lifecycle owners can order the two correctly. This would also address #2147.
SessionTreeMirrorTest, added by #2946, is the natural home for a regression test: schedule a mirror against a sandbox that is shut down before the executor picks the task up.
Workaround
We own our sandbox lifecycle (SandboxContext.externalSandbox), so we call SessionTree.awaitMirrorQuiescence(5, TimeUnit.SECONDS) immediately before shutting the sandbox down. It covers the normal path deterministically — TranscriptMiddleware triggers the flush inside the middleware chain, which completes before the Flux.using cleanup that releases the sandbox — but it relies on internal ordering rather than a contract, it blocks on unrelated sessions queued on the shared executor, and it isn't available at all to anyone using a framework-managed sandbox, since that shutdown happens inside SandboxManager.release.
@larry-zy #3039
I understand the bug you described. During normal session‑writing, the session is first written synchronously to local storage, then asynchronously mirrored to the sandbox. Following the self‑managed: creator‑owns‑destruction principle, the sandbox instance is allocated in the synchronous call phase and will go through stop() + shutdown() to clean up internal connections once the call completes.
Previously, to avoid tying the asynchronous sandbox mirroring logic to the call lifecycle, PinnedSandboxFilesystem was used to map and pass the sandbox instance to the asynchronous thread. However, we failed to account for the scenario where the synchronous call phase invokes shutdown() and tears down sandbox internal connections before the asynchronous sandbox write completes. This leaves the asynchronous thread holding a hard reference to the stale sandbox instance and attempting uploads, which results in an NPE.
I understand your current fix roughly works as follows: you introduced a MirrorGate for the sandbox instance, which combines a read‑write lock and a released flag. Before releasing resources upon call completion, the gate is marked as released. When the asynchronous mirroring task actually writes to the sandbox, it checks this gate; if already released, it aborts the write operation to avoid operating on a sandbox whose internal connections have already been cleared by shutdown(), thus preventing the NPE.
Ongoing upload tasks that have already started will hold the read lock, and the release marker will wait for them to finish before closing. Tasks still sitting in the queue that have not yet started will be skipped directly.
This approach does eliminate the NPE. However, if the asynchronous mirroring fails to start execution before release in the current round, the session mirror will not be persisted on the sandbox side, even though the local copy remains intact.
In my opinion, a more complete solution would be: when the synchronous call is about to exit while pending asynchronous sandbox writes still require the connection, do not tear down the connection synchronously right away. Instead, transfer the release ownership of this sandbox to the asynchronous writer. Only after all asynchronous tasks depending on this connection complete (e.g., when the reference count drops to zero) should we finally invoke stop() + shutdown(). This preserves the self‑managed guarantee that the framework is ultimately responsible for destruction, while preventing in‑flight mirroring work from being prematurely aborted simply because the synchronous call has returned.
Issue Evaluation
Category: bug | Status: Confirmed
Verified against current main (7399ed6) by source-level analysis:
- Root cause:
SessionTree.flush()queues a fire-and-forget mirror on the staticsession-tree-mirrorexecutor (agentscope-harness/.../memory/session/SessionTree.java:326-347, submit at590-594), while per-call teardown runsSandboxLifecycleMiddleware.releaseForCall→SandboxManager.release→stop()/shutdown()(SandboxLifecycleMiddleware.java:151-177,SandboxManager.java:197-211). The two paths are unsynchronized:awaitMirrorQuiescence()is drained only fromHarnessAgent.close()(HarnessAgent.java:465), never before per-call release. Since #2946 the mirror target is pinned throughPinnedSandboxFilesystem, whoseclearSandboxIfCurrent()is intentionally a no-op (PinnedSandboxFilesystem.java:41-44) — the pinned reference can never learn that the sandbox was closed, exactly as reported. - Exact throw site:
KubernetesSandbox.uploadFiledereferencessdkSandbox.commands().run(...)with no liveness check (KubernetesSandbox.java:270-272);client/Sandbox.closeConnection()nullscommands/filesand setsclosed(.../kubernetes/client/Sandbox.java:220-229), andSandbox.isActive()is only consulted by the client cache (SandboxClient.java:226,260), never on the transfer path. The NPE is then swallowed into the reported WARN atSandboxBackedFilesystem.java:154-155— line numbers match the stack trace byte-for-byte. - Not limited to user-managed sandboxes:
claimOwneddefaults to true (KubernetesSandboxState.java:37, set inKubernetesSandboxClient.java:98), so stock self-managed K8s sandboxes reach the same path on every call. - Impact:
agentscope-harnesssession-log mirroring plusagentscope-extensions-sandbox-kubernetes. WARN spam on the mirror thread and silently dropped best-effort mirror uploads; the local session file remains the primary store, so there is no crash and no primary-data loss. - Severity: medium. Fix complexity: low for a typed failure, medium to close the race fully.
Suggested direction: gate the commands()/files() dereferences in KubernetesSandbox.uploadFile/downloadFile/doExec on isActive() and throw a typed SandboxException ("sandbox connection closed") so the best-effort mirror degrades with a meaningful message instead of a raw NPE, plus a regression test (queue mirror → release → assert typed exception). There are currently no tests for PinnedSandboxFilesystem/pinIfSandbox. Draining the mirror executor inside releaseForCall would close the race completely but reintroduces blocking remote I/O into the call path, so it needs a maintainer trade-off.
Existing coverage: PR #3039 (skip mirrors after release + typed exception) and PR #3094 (defer self-managed shutdown until mirrors quiesce) already target this issue, and #2147 tracks the related teardown gap. No automated fix PR will be generated from this evaluation — the change belongs on the existing PRs.
Note: source-level verification only; no build or reproduction was run.
Automated evaluation by github-manager-bot
Issue Evaluation — follow-up (community question awaiting answer)
Category: bug | Status: Confirmed (on record above) | Coordination follow-up. Three load-bearing anchors were re-checked at main @ ed77530a4 — PinnedSandboxFilesystem.clearSandboxIfCurrent is still a no-op override (agentscope-harness/.../filesystem/sandbox/PinnedSandboxFilesystem.java:42, documented at :27), SessionTree.awaitMirrorQuiescence still has exactly one production caller (.../agent/HarnessAgent.java:466, i.e. agent close, not per-call release), and KubernetesSandbox.uploadFile/downloadFile still dereference sdkSandbox.files() with no isActive() guard (agentscope-extensions/.../kubernetes/KubernetesSandbox.java:269, :284, :289). Everything else carries over from the confirmed evaluation earlier on this thread.
@samvallad33 answering your question directly: yes, "fail closed when the pinned sandbox lifetime ends" is the right shape, and it is already what the two in-flight PRs split between them.
The three things a fail-closed mirror needs, in the order they bound the problem:
- A typed liveness failure on the transfer path.
KubernetesSandbox.uploadFile/downloadFile/doExecdereferencecommands()/files()with no liveness check, andcloseConnection()nulls them — that is where the raw NPE comes from, and it is what the mirror thread's WARN swallows. Gating onisActive()and throwing a typed "sandbox connection closed" exception is what turns a silent best-effort drop into a legible one. This is PR #3039 (OPEN) — skip mirrors after release + typed exception. - Making the pin actually observable as dead.
PinnedSandboxFilesystem.clearSandboxIfCurrent()is intentionally a no-op (introduced by #2946), which is precisely why the pinned reference can never learn the sandbox was closed and why recall collapses instead of degrading. Any complete fix has to give the pin a lifetime signal rather than relying on the no-op path. - Ordering release against the mirror queue. Draining the static
session-tree-mirrorexecutor insideSandboxLifecycleMiddleware.releaseForCall(todayawaitMirrorQuiescence()is only reached fromHarnessAgent.close()) closes the race fully, but it puts blocking remote I/O back into the per-call teardown path. That trade-off is a harness-maintainer call, not something the bot should decide by landing a patch. This is PR #3094 (OPEN) — defer self-managed shutdown until mirrors quiesce.
No bot PR will be generated for this issue. #3039 and #3094 are both open and already own the two halves above; a third generated patch would duplicate review effort on the same code, and the reporter of #3036 has stated a preferred direction (items 2–4 of their own fix list) that maintainers should arbitrate. Both PRs are picked up by the scheduled PR review sweep.
If maintainers would rather see (2) — a lifetime-aware pin — prototyped independently of #3039/#3094, say so on this thread and a scoped patch with the SessionTreeMirrorTest regression case will be generated against current main in a later tick. No slash command is being proposed here, to avoid triggering the standard /approve → PR-generation flow while two open PRs already cover this code.
Automated follow-up by github-manager-bot