Skip to content

fix(sandbox): avoid session mirrors after sandbox release - #3039

Merged
jujn merged 15 commits into
agentscope-ai:mainfrom
larry-zy:fix/session-tree-sandbox-mirror-lifecycle
Oct 27, 2026
Merged

jujn merged 15 commits into
agentscope-ai:mainfrom
larry-zy:fix/session-tree-sandbox-mirror-lifecycle

Conversation

@larry-zy

@larry-zy larry-zy commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Summary

  • skip best-effort SessionTree mirrors when their pinned sandbox has been released
  • report a clear sandbox exception when Kubernetes file transfer uses a closed connection
  • add regression coverage for both cases

Testing

  • mvn -pl agentscope-harness -am -DskipITs -Dtest=SessionTreeMirrorTest -Dsurefire.failIfNoSpecifiedTests=false test
  • mvn -pl agentscope-extensions/agentscope-extensions-sandbox/agentscope-extensions-sandbox-kubernetes -am -DskipTests package

Fixes #3036

@larry-zy larry-zy changed the title fix(harness): avoid session mirrors after sandbox release fix(sandbox): avoid session mirrors after sandbox release Sep 8, 2026
@codecov

codecov Bot commented Sep 8, 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

Guards the best-effort session mirror against races with self-managed sandbox release: a new static Sandbox → MirrorGate (ReentrantReadWriteLock) in PinnedSandboxFilesystem blocks release until in-flight uploads finish and rejects new ones afterwards, SandboxLifecycleMiddleware marks the gate before sandboxManager.release(...), SessionTree skips mirrors for a released sandbox, and ObjectStoreTranscriptStore.appendSegment / mirrorToFilesystem now fail loudly instead of ignoring a returned failure response. The problem is real (#3036) and the "stop reporting a mirror as done when the upload actually failed" part is a genuine improvement — compact() in particular was previously free to delete the input segments after a lost upload.

Findings

  • [Critical] PinnedSandboxFilesystem.java:81 — the read lock spans the whole remote upload while release takes the write lock, so call teardown now waits on an unbounded network transfer; one stalled upload hangs releaseForCall (and the lease close) on the agent's completion path.
  • [Warning] PinnedSandboxFilesystem.java:44 — released is a one-way latch keyed on the Sandbox instance with no reset path (resume/reconnect rebinds instances), and WeakHashMap key equality is not identity-based.
  • [Warning] SessionTree.java:745 — the new early return also skips the local index.upsertFromLocalFile, so a failed mirror leaves the workspace index stale for a file that exists on disk.
  • [Warning] ObjectStoreTranscriptStore.java:91 — appendSegment now throws, which scheduleSegmentMirror logs and compact() propagates; the interface documents no failure contract, and the "released" case becomes a WARN storm instead of a distinguishable skip.
  • [Warning] SessionTreeMirrorTest.java:213 — both new tests exercise isRunning() == false (the pre-existing liveness check); markSandboxReleased and the gate interaction are untested.
  • [Info] KubernetesSandbox.java:289 — solid addition; exec/persistWorkspace/hydrateWorkspace remain unguarded and WORKSPACE_STOP_ERROR is reused for a closed connection.

Suggestions

The blocking-teardown item is the one I'd like resolved before merge — a bounded tryLock on the gate keeps the intended ordering for new mirrors without letting an un-timed remote write stall call release. The rest are contract/test hardening: name the "skipped because released" outcome so callers can treat it as normal, state the throws contract on TranscriptStore#appendSegment, keep the local index update independent of the remote copy, and add one test that drives the gate itself.

Also related for the maintainer's eye: #3094 (defer self-managed sandbox shutdown via a retain/release counter) and #3106 (move transcript persistence off the completion path) are attacking the same lifecycle window from three directions with three different mechanisms — worth converging on one owner for "async write vs. sandbox release" before all three land.


Automated review by github-manager-bot

@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 author's follow-up commit e0fe07df01 (address sandbox mirror review findings). The MirrorGate design holds up: released is published before waiting for the write lock, so new mirror uploads are rejected even when an existing transfer is wedged, and release stays bounded because mirrors are best-effort. The per-sandbox generation is replaced (not reopened) on markSandboxAcquired, which correctly stops a previous call's mirror from attaching to the new call's lifecycle, and gateFor keeps the shared MIRROR_GATES map under synchronized with weak-key expunge so gates do not outlive their sandbox. The added tests (flush_skipsMirrorWhenPinnedSandboxWasReleased, flush_skipsTranscriptSegmentWhenPinnedSandboxWasReleased, and the "released sandbox must not execute / persist / hydrate / download" guards) target the use-after-release failure the PR exists for.

One concern inline: the hardcoded 1 s gate cap.


Automated review by github-manager-bot

@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 of the new commit 560861f. The release-gate design is sound: released is published before the write-lock wait, a gate is replaced (not reopened) per acquire generation, KubernetesSandbox.requireActiveConnection() now turns use-after-close into a clear SANDBOX_CONNECTION_CLOSED instead of an opaque SDK failure, and moving index.upsertFromLocalFile ahead of the upload is right — the index describes the authoritative local file, not the best-effort mirror. The new tests cover both the released-sandbox guards and the never-execute/never-persist contract.

Three points inline: the plain released read in isSandboxReleased() is the only carrier of the release reason and can mis-warn on every post-release flush; the 1 s gate cap should be configurable rather than a compile-time constant (this was the open item from last round); and the identity-keyed gate map deserves a note on its one-generation-per-instance assumption. CLA signed.


Automated review by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR conflicts with main and cannot be merged (mergeable_state=dirty on head 560861f5). main has advanced substantially since your last commit (2026-09-14), so a rebase should pick up the sandbox and session-mirror changes it now depends on:

git fetch origin
git checkout fix/session-tree-sandbox-mirror-lifecycle
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Once the conflict is cleared, comment @oss-maintainer please re-review and this PR goes back into the review queue. This is a one-time reminder.


Automated notification by github-manager-bot

@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 of the two commits since 560861f: dab48dba (configurable mirror drain budget) and the merge of main. The drain-budget knob does what I asked for and the javadoc is candid about the remaining hole ("an upload still in flight when the wait expires may fail during shutdown") — good. Two things need attention before this is ready:

  1. CI is red on this head. The requireActiveConnection() guard added to doHydrateWorkspace breaks KubernetesSandboxColdRestoreTest.persistedSnapshotSurvivesAcquireStartAndStop (3/3 parameterised cases) because that test's mocked SDK sandbox never stubs isActive() — see the inline comment for the stack trace. build (ubuntu-latest) was cancelled, so only the Windows job surfaced it.
  2. The new system property is undocumented and process-global. agentscope.state.home sets the precedent for a root-path override and is documented in both the en and zh docs; a timing tunable read on every release arguably belongs on the spec/builder with the property as a fallback.

Non-blocking note on the stall test's wall-clock bands — on the same runner class that just failed, a 900 ms ceiling against a 1000 ms default is a thin margin.

Everything from the previous round that I asked about (release latch ordering, gate replacement per generation, index.upsertFromLocalFile ahead of the upload) still holds after the rebase.


Automated review by github-manager-bot

@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 on head 7a192fe5. The single new commit is the test stub the previous round asked for, and it does close the CI finding: build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync and codecov/patch are all green and license/cla reports signed. Fail-closed on a released sandbox is the right shape for #3036, and the generate-side ordering (release latch before drain, gate replaced per generation, index.upsertFromLocalFile ahead of the upload) still holds after the rebase.

Not converting to an approval, for one reason only: item 2 of the previous round — the new agentscope.sandbox.mirror.release-timeout-millis knob is process-global and not documented anywhere operators will look — is unchanged by this push. Everything in the code itself is fine; this is a one-file docs/config decision. If you document it next to agentscope.state.home (en + zh), or move the budget onto the filesystem spec/builder with the property as fallback, this is an approval on the next tick without any further code changes.

Findings

  • [Warning] PinnedSandboxFilesystem.java:55 — new public, process-global JVM property with no presence in docs/** (en or zh); discoverability gap for the exact failure mode this PR fixes.
  • [Warning] PinnedSandboxFilesystem.java:100 — the wait is synchronous on the release path and is per release, not a global bound; worth stating in the property doc so nobody sets it expecting a shutdown deadline.
  • [Info] PinnedSandboxFilesystem.java:153 — property read + Long.parseLong on every release, with a NumberFormatException branch that only exists because the value has no other home.
  • [Info] KubernetesSandboxColdRestoreTest.java:107 — previous round's CI blocker confirmed fixed on this head.

Notes for a maintainer

mergeable is true but mergeStateStatus is blocked, which here means branch protection still wants a human approval, not that CI is failing. 8 of 13 review threads are resolved; the other 5 are all from this bot's earlier passes and the two design questions among them (unlocked read of MirrorGate.released, and one-live-generation-per-Sandbox-instance being an assumption rather than an enforced invariant) are worth a maintainer's judgement before merge.


Automated review by github-manager-bot

@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 on head 32911482. Both open findings from the previous round are resolved by this push, so this is the approval that round promised.

  • Process-global knob now documented (en + zh). docs/v2/en/docs/building-blocks/context.md and its zh twin gained a "Sandbox mirror release wait" / "沙箱镜像的释放等待" section next to the agentscope.state.home discussion: property name, process-wide JVM scope, read at each release, 1000 default, 0 = no wait, malformed/negative fallback, the exact warning string to grep for, and the tuning trade-off. The claims match the implementation in releaseGateTimeoutMillis() — the fallback branches were checked, not just the prose.
  • Per-release vs. total-deadline ambiguity removed. The RELEASE_GATE_TIMEOUT_PROPERTY javadoc now states "Each consecutive release has its own budget; this is not a total shutdown deadline", which is what the code does (gateFor(sandbox).markReleased(releaseGateTimeoutMillis()) per release), and both doc languages repeat it.
  • Timing-band assertions dropped. releaseDoesNotWaitIndefinitelyForStalledUpload pins the configuration directly and bounds the release with release.get(5, TimeUnit.SECONDS) instead of measuring wall-clock inside [50ms, 900ms), so the release path no longer depends on scheduler latency. Right trade-off — no request to bring the band back; one non-blocking note is left on the test about what the weaker assertion no longer covers.

CI is green on this head (SUCCESS=7), license/cla is signed, and mergeable is MERGEABLE.

Still for a human maintainer, unchanged from last round: mergeStateStatus is blocked because branch protection wants a human approval, and the two design questions from earlier threads are judgement calls rather than defects — the unlocked read of MirrorGate.released, and one-live-generation-per-Sandbox being an assumption rather than an enforced invariant. Related: #3036's fail-closed expectation is met.


Automated review by github-manager-bot

@mintlify

mintlify Bot commented Oct 27, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 75f1367.

Approve preview

@jujn
jujn merged commit 19fdc9e into agentscope-ai:main Oct 27, 2026
6 checks passed
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified fix to the 2.0.x implementation and retain its existing public contracts where the upstream kernel differs.

(cherry picked from commit 19fdc9e)
Backport-review-patch: b97c27341bc3ccac1fe82dd179465887d8f997b9
Constraint: No AgentScope Service or SDK migration
Confidence: high
Not-tested: Whole-repository verification pending after lane integration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants