Skip to content

fix(sandbox): retain active fallback across concurrent calls - #2854

Open
Oxygen56 wants to merge 7 commits into
agentscope-ai:mainfrom
Oxygen56:fix/2849-sandbox-fallback-lifecycle
Open

Oxygen56 wants to merge 7 commits into
agentscope-ai:mainfrom
Oxygen56:fix/2849-sandbox-fallback-lifecycle

Conversation

@Oxygen56

@Oxygen56 Oxygen56 commented Aug 26, 2026 •

Copy link
Copy Markdown

AgentScope-Java Version

2.1.0-SNAPSHOT

Description

Fixes #2849.

When concurrent calls share one agent, releasing the most recently acquired sandbox must not leave a still-running call without a context-free filesystem fallback. This change tracks fallback bindings in acquisition order and removes one matching binding on release, restoring the newest retained binding. Per-call sandbox bindings continue to take precedence.

Fallback history is capped at 1024 entries; exceeding the cap evicts the oldest context-free binding and logs a warning. This bounds abandoned entries rather than guaranteeing immediate cleanup of every abandoned call. Per-call bindings are unaffected by eviction. Null bindings are rejected before any mutation, and the public interface documents that requirement. Failed startup only removes a fallback if that call actually registered it.

The update integrates current main while preserving its shared release-state and once-only cleanup protection across runtime-context copies. The regression coverage includes remaining-call restoration, non-current removal, repeated sandbox bindings, null rejection, failed startup, and abandoned-entry eviction. A combined lifecycle regression also verifies that releasing the latest call restores the earlier fallback while both copies of the released context remain invalid and repeated release leaves the earlier call intact.

This fix addresses the empty-fallback window. Context-free callers still use the newest retained binding; this does not add session routing or isolation to context-free access.

The original Windows job exposed a pre-existing race in WaitAsyncResultsToolTest: its mutable test repository shared an ArrayList between the completion thread and a lookup stream. Both the test and WaitAsyncResultsTool matched base main before this follow-up. Only the mutable fixture now uses CopyOnWriteArrayList; all existing assertions and production behavior are unchanged.

Verification (JDK 17, macOS):

  • mvn -B -T1C -pl agentscope-harness -am verify — passed, including compilation, Spotless, the configured Core/Harness/AG-UI test suites, coverage generation, and Javadoc.
  • mvn -B -T1C -pl agentscope-harness -am spotless:apply — passed with no additional changes.
  • bash .github/scripts/check-shade-and-bom-sync.sh — passed.
  • A latch-controlled probe against the actual compiled test fixture reproduces the original ConcurrentModificationException before the change and completes the same concurrent lookup/add successfully afterward.

The suite's existing platform-specific, disabled, and opt-in tests were skipped by their configuration; Docker integration and the opt-in structured-output race test were not enabled. Full Linux/Windows repository builds and license checks run in GitHub CI. The original Windows failure remains linked above; verification of the updated Windows run is pending.

AI assistance was used in preparing this contribution.

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test; configured relevant reactor suites passed, skips noted above)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (internal lifecycle behavior; contract documented on the interface)
  • Code is ready for review

@CLAassistant

CLAassistant commented Aug 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...s/agent/middleware/SandboxLifecycleMiddleware.java 66.66% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@xiaoyuuuuuupeng

Copy link
Copy Markdown
Contributor

LGTM Fixes the #2849 empty-fallback window: fallbackBindings stack + fallbackBound look correct. Concurrent lifecycle tests pass; per-call binding unchanged. One non-blocking nit on setSandbox(null) clearing the whole stack — doesn't block merge.

@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

Turns the context-free sandbox fallback in SandboxBackedFilesystem from a single last-writer-wins volatile field into an ordered binding stack, so that when one of several concurrent calls sharing an agent releases, the fallback restores a still-active sibling instead of transiently dropping to null (issue #2849). Also stops a failed sandbox.start() from clearing a binding it never registered, via the fallbackBound flag in SandboxLifecycleMiddleware. The stack model is a genuine improvement over compare-and-clear for the reported failure, the identity-based removal keeps #2490's per-call guarantee, and the five new tests (remaining-sandbox restore, non-current release not resurrected, shared-sandbox refcounting, null rejection, failed-start) cover exactly the interesting orderings.

Findings

  • [Warning] SandboxBackedFilesystem.java:68 — the stack only shrinks through clearSandboxIfCurrent, so an acquire whose release never runs leaves a permanent entry that can later be restored as the active fallback (a released sandbox handed to context-free callers). Previously that stale value was simply overwritten by the next acquire.
  • [Info] SandboxBackedFilesystem.java:83 — Objects.requireNonNull tightens SandboxAware#setSandbox, a public interface method that accepted null before; the contract is documented on the implementation only.
  • [Info] SandboxBackedFilesystem.java:112 — the field is reassigned even when nothing was removed, which is safe only while the implicit sandbox == fallbackBindings.tail invariant holds; an early return when no match was found would keep #2490's "only touch it if this call owns it" visible.

Suggestions

For the first point, something as simple as a size guard plus a WARN makes a leak diagnosable instead of silent:

if (fallbackBindings.size() > MAX_TRACKED_FALLBACK_BINDINGS) {
    log.warn("[sandbox-fs] {} fallback bindings still registered for {}, dropping oldest",
            fallbackBindings.size(), fsId);
    fallbackBindings.remove(0);
}

…or pruning on stop/agent close, if a bounded stack is not acceptable for long-lived mirrors. None of these look blocking to me — flagging so the resurrection path gets an explicit decision.

Verified: CLA signed (license/cla success), build (ubuntu-latest) / build (windows-latest) / Check License / Check Module Sync / codecov/patch all passing at head a97c7d13, mergeable=true, mergeable_state=blocked (branch protection, not a conflict).


Automated review by github-manager-bot

@Oxygen56

Copy link
Copy Markdown
Author

The original Windows failure came from an existing race in the test fixture: MutableTaskRepository used an ArrayList while one thread added a task and another streamed it for lookup. Both the test and WaitAsyncResultsTool matched base main before this follow-up.

I changed only that mutable fixture to CopyOnWriteArrayList, preserving all assertions and production behavior. A latch-controlled probe reproduces the same ConcurrentModificationException with the original fixture and succeeds with the updated fixture. The focused tests and full relevant-reactor verify pass locally on JDK 17. The updated Windows check is pending; the original failure is retained above.

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

5 participants