Repository navigation
fix(sandbox): scope the execution guard key by agent for USER isolation - #4441
Conversation
A declared subagent spawned inside a sandboxed call acquires its own sandbox,
but SandboxIsolationKey#resolve drops agentId for USER scope: the guard key is
just userId while the persisted slot is sandbox/user/{agentId}/{userId}. The
parent holds the guard for the whole call window, so the nested subagent waits
on the same key forever.
Derive a guard-only key that mirrors the slot granularity:
- USER scope now locks on {agentId}/{userId};
- SESSION/AGENT already discriminate parent from child;
- GLOBAL shares one slot by definition and is documented as unsupported with
subagents.
The persisted slot key is unchanged, so existing sandbox state and snapshots
are untouched. Lock names change for USER scope (ephemeral leases; rolling
upgrade sees a one-lease-TTL window).
Tests: SandboxIsolationKeyTest (agent dimension, stability, non-USER scopes)
and SandboxManagerIsolationTest (nested parent/child keys differ while the
state-store key stays identical).
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
ningmao-hlyz
left a comment
There was a problem hiding this comment.
Verified on ee50e85: reverting just the SandboxManager hunk turns both new assertions red, full harness suite 2279/0. The need is real — scope defaults to USER and every distributedStore(...) injects a real guard.
[P1] The upgrade window is the whole mixed-version period, not one lease TTL. Every built-in guard composes the lock name from scope:value, so an old node keeps taking user:<uid> while a new one takes user:<agent>/<uid>. The names never meet, and the TTL only expires the old key for its own holder. "Until every node runs the new code" is right; the parenthetical contradicts it and would undersell release notes.
[P2] {agentId}/{userId} is composed twice, here and in SessionSandboxStateStore#slotSessionId, held together by a comment. A test pinning slot to end with /{guardValue} would catch drift.
[P2] forExecutionGuard returns this on a null or blank agentId — unreachable from SandboxManager, but external callers get exactly the key that deadlocks.
[P2] The paragraph you edited still says two replicas serving one user write the same slot; true per agent, not across agents, which the new sentence below contradicts. Same for GLOBAL "still serialises" — the child actually blocks.
…uard lockstep - forExecutionGuard throws IllegalArgumentException for USER scope with a null/blank agentId instead of returning the deadlock-prone slot key - SessionSandboxStateStoreTest pins the slot id to end with the guard key's value, catching drift between the two compositions - docs: the mixed-version window is the whole rollout, not one lease TTL; GLOBAL subagent behaviour described accurately (child blocks on the parent's lease)
Ernest-L
left a comment
There was a problem hiding this comment.
Thanks for the review and for verifying on ee50e85 — all four points are addressed in 4598479:
[P1] Agreed, the parenthetical was wrong. The PR body now says the lock-name mismatch lasts the whole mixed-version period (until every node runs the new code), not a single lease TTL, and flags it for the release notes.
[P2] composition drift — SessionSandboxStateStoreTest#userScope_slotEndsWithGuardValue_compositionsStayInLockstep now drives a real InMemoryAgentStateStore, records the raw slot id written for a USER-scope key, and asserts it ends with /{guardValue}. Either composition changing turns it red.
[P2] null/blank agentId — forExecutionGuard now throws IllegalArgumentException for USER scope instead of returning this; the javadoc @throws states why (returning the slot key would hand back exactly the key that deadlocks nested calls). One note: an execution constructed with a blank agent id that previously acquired silently would now fail fast at acquire — we consider that the better failure mode, and SandboxManager already requires a non-null agentId at construction.
[P2] doc contradictions — both paragraphs reworked in en + zh: the slot-race sentence is now "the same user and agent", and the GLOBAL wording no longer claims "still serialises" — it says a subagent spawned inside a call blocks on the lease the parent holds until that call ends. (Same correction applies to the wording in #4440's thread above.)
Full harness suite 2280/0 plus the extension guard suites (PostgreSQL 20, MongoDB 24, JDBC 6).
ningmao-hlyz
left a comment
There was a problem hiding this comment.
[P2] The guard key and the slot are now a 1:1 map — equal slot ⇒ equal lock and vice versa — so there's no new collision surface. That only holds while SandboxManager and SessionSandboxStateStore get the same agentId. AGENT already carried that coupling; this change extends it to USER, and nothing checks it. Taking the id from the store (or asserting equality in the constructor) would let the drift test cover the wiring, not just the string format.
[P2] acquire derives the key before it knows whether a guard exists, so a blank agentId now throws on the default noop() path — a configuration that previously worked. Rejecting a blank id in the constructor would move that to build time instead of the first call. (Also worth extending the drift test to SESSION/AGENT: SESSION is self-consistent because both sides use getValue(), AGENT has the same two-source coupling.)
[P2] Compatibility, two additions: during the mixed-version window old and new nodes don't merely fail to serialise, they write the same slot concurrently; and ensureSessionDefaults prefers the parent's SandboxContext, so once the deadlock is gone a declared ISOLATED child runs against the parent's projection and persists into its own snapshot — the gap your "Not covered" section mentions becomes reachable, with writes that don't land where the declaration says.
- SandboxManager constructor rejects a null/blank agentId and asserts it matches the state store's agent id, so guard keys and persisted slots cannot silently drift apart; SessionSandboxStateStore exposes getAgentId() for the check - drift test extended to SESSION and AGENT scopes (AGENT has the same two-source coupling between store id and resolve() id); the nested parent/child test now wires each manager to its own agent-scoped store, mirroring HarnessAgent.build - forExecutionGuard keeps its USER-scope blank check as a guard for direct callers; javadoc notes the constructor already covers SandboxManager users Full harness suite 2284/0 plus extension guard suites (PostgreSQL 20, MongoDB 24, JDBC 6).
Ernest-L
left a comment
There was a problem hiding this comment.
All three addressed in 0c67542:
[P2] wiring coverage — SessionSandboxStateStore exposes getAgentId(), and the SandboxManager constructor now asserts the two ids match, failing at build time with a message naming both values ("equal slots would no longer imply equal locks"). Real instances can never return null (the store's own constructor requires a non-null id), so the check only skips the comparison for test mocks. The nested parent/child test was also reworked to wire each manager to its own agent-scoped store, mirroring what HarnessAgent.build constructs — so the drift test now covers the wiring, not just the string format.
[P2] blank agentId at build time — the same constructor rejects a null/blank id before any acquire, so the noop path can't regress from "worked" to "throws on first call". The drift test gained SESSION and AGENT cases too (AGENT has the same two-source coupling; SESSION is pinned for self-consistency).
[P2] compatibility additions — both folded into the PR body's Compatibility section: (1) during the mixed-version window the two lock names never meet, so the same slot is written concurrently (last-write-wins), not merely unserialised; (2) with the deadlock gone, the SandboxContext-inheritance gap in ensureSessionDefaults becomes reachable — an ISOLATED child runs against the parent's projection while persisting into its own snapshot. I'll file that as a separate issue since it needs its own design discussion (strip the framework-default SandboxContext in childContext while preserving externalSandbox/externalSandboxState and SandboxAcquireResult).
|
LGTM — the wiring check plus the three drift pins cover what I asked for. Nothing blocking; three small things, all optional. storeAgentId != null && can only be reached by a mock (getAgentId() returns a final field the constructor already requires non-null), so the comment ends up saying tests are exempt from the invariant it exists to enforce. |
…-USER null path Per review follow-up (all three optional items): - the guard-key/slot consistency check no longer tolerates a null store id: getAgentId() returns a final field the store's constructor requires non-null, so the comparison holds unconditionally; test mocks are stubbed accordingly (SandboxManagerIsolationTest setUp + middleware lifecycle tests) - sandbox.md (en + zh) states the rolling-upgrade consequence of the USER lock-name change: peers of different versions do not serialise and can write the same slot concurrently until the rollout completes - SandboxIsolationKeyTest pins that forExecutionGuard(null/blank) on non-USER scopes returns this and never throws — the path a refactor hoisting the check above the scope switch would break Full harness suite 2284/0.
Ernest-L
left a comment
There was a problem hiding this comment.
Took all three despite the LGTM — all cheap, and the first one was a real smell. Pushed as 8e06e76:
-
The null tolerance is gone:
requireConsistentAgentIdnow compares unconditionally (the comment statesgetAgentId()returns a final field the store's constructor requires non-null). The mocks that relied on it are stubbed instead —SandboxManagerIsolationTest#setUpand the middleware lifecycle tests. -
sandbox.md(en + zh) now carries the upgrade consequence: during a rolling upgrade old nodes lockuser:<uid>while new ones takeuser:<agent>/<uid>, the names never meet, peers of different versions don't serialise and can write the same slot concurrently (last write wins) — complete the rollout before relying on the guard. -
SandboxIsolationKeyTest#nonUserScopes_guardKeyIsUnchangednow pinsforExecutionGuard(null)/(" ")on SESSION, AGENT and GLOBAL — returnsthis, never throws — with a comment naming the refactor it guards against (hoisting the blank check above the scope switch).
Full harness suite 2284/0.
The e2b and kubernetes sandbox modules construct SandboxManager with unstubbed SessionSandboxStateStore mocks, whose getAgentId() returns null — the constructor's consistency check now rejects that, breaking both CI platforms. Stub each mock with the id its manager is built with, matching real wiring. Verified with a full-reactor 'mvn clean verify' (114 modules, 13531 tests, 0 failures) using the CI Windows flags; durable-sandbox stays covered by the ubuntu job as before.
Ernest-L
left a comment
There was a problem hiding this comment.
One follow-up: the CI failure on 8e06e76 was mine — the constructor consistency check is repo-wide, and two extension modules I had not run locally (agentscope-extensions-sandbox-e2b, -kubernetes) build SandboxManager with unstubbed SessionSandboxStateStore mocks whose getAgentId() returns null. Stubbed with the id each manager is built with, in 4334ed6.
Local verification is now CI-equivalent: full-reactor mvn clean verify with the CI Windows flags — 114 modules, 13,531 tests, 0 failures (durable-sandbox stays with the ubuntu job, as before).
HarnessContextRegressionTest timed out on 10s blocking reads on the hosted Windows runner for 3223627; the same commit passes locally on Windows (35/35 in 22s) and on ubuntu CI.
…dbox subagents at build
aa94d24 to
3181063
Compare
…on (backport to 2.0.x) (#4520) ## AgentScope-Java Version `2.0.x` (2.0.6-SNAPSHOT at bab86b1). Backport of #4441 for the 2.0.x line — ships with 2.0.6. ## Description Backport of #4441 (fix(sandbox): scope the execution guard key by agent for USER isolation). A sandboxed agent that spawns a declared subagent (`subagents/*.md`, default `ISOLATED`) self-deadlocks on `SandboxExecutionGuard` because the guard key drops `agentId` while the persisted slot keeps it. The guard now keys on `{agentId}/{userId}` for `USER` scope; `SandboxManager`'s constructor validates the wiring (blank/mismatched agentId fails at build time); `forExecutionGuard` throws for USER scope with a null/blank agentId instead of returning the deadlock-prone slot key. Cherry-picked from #4441 (commits ee50e85 → 8e06e76). One conflict resolved: `SandboxLifecycleMiddlewareProjectionNarrowingTest` does not exist on 2.0.x — its hunk (a test-mock stub) was dropped with the file. Two 2.0.x-specific construction sites were additionally stubbed, since the constructor check is repo-wide: - `AgentRunSandboxWorkspaceRootTest` (agentrun module) - `SessionTreeMirrorIsolationTest` (2.0.x-only session-mirror test) ## Tests Full-reactor `mvn clean verify` on this branch with the CI Windows flags (`-Djacoco.skip=true -DskipDurableWindowsTests=true`, javadoc/source skipped as in PR builds): - 114 modules, **11,871 tests, 0 failures, 0 errors** - Key modules confirmed in-run: harness 165 test classes (1638 tests), e2b, kubernetes, agentrun - `durable-sandbox` remains covered by the ubuntu job, as before (#4273-era layout) ## Compatibility - Additive public API only (`SandboxIsolationKey#forExecutionGuard`, `SessionSandboxStateStore#getAgentId`); `SandboxManager` constructor now rejects blank/mismatched agentIds (framework wiring always passes a consistent non-blank id). - `USER`-scope lock names change (`...:user:<uid>` → `...:user:<agent>/<uid>`); during a rolling upgrade old and new nodes do not serialise and can write the same slot concurrently — complete the rollout promptly. Ephemeral leases; no data migration. ## Checklist - [x] Code has been formatted with `mvn spotless:apply` - [x] All tests are passing (`mvn clean verify` — full reactor) - [x] Javadoc comments are complete and follow project conventions - [x] Related documentation has been updated (`sandbox.md` / `subagent.md`, en + zh) - [x] Code is ready for review
AgentScope-Java Version
2.1.0-SNAPSHOT (
mainat 80926f9); also present in 2.0.4 / 2.0.5 / v2.1.0-BETA1.Description
A sandboxed agent that spawns a declared subagent (
subagents/*.md, defaultISOLATED) can deadlock when an execution guard is configured — including thedistributedStore(...)setup recommended insandbox.md:acquire → start → (call) → stop → release → lease.close());SandboxExecutionGuard.tryEnter(...);USERscope both resolve the same guard key (userId), so the child waits on a lease its parent cannot release until the child returns.The default guard is
noop(), which is why this only surfaces with a real guard (Redis / JDBC / MongoDB / PostgreSQL distributed stores all inject one).Root cause
SandboxIsolationKey.resolve(USER, ...)dropsagentId, while the persisted slot does not:SessionSandboxStateStore)sandbox/user/{agentId}/{userId}SandboxIsolationKey)userIdParent and child use different slots but the same guard key, so the guard serialises executions the state layer treats as independent.
Fix
Derive a guard-only key that mirrors the slot granularity:
USER:{agentId}/{userId}SESSION/AGENT: unchanged (they already discriminate parent from child)GLOBAL: unchanged (single shared slot; serialisation is required)SandboxIsolationKey#forExecutionGuard(agentId)throwsIllegalArgumentExceptionforUSERscope with a null/blank agentId — silently returning the slot key would hand back exactly the key that deadlocks nested calls.The persisted slot key is untouched, so existing sandboxes and snapshots need no migration — the state store keeps receiving the original key, only
tryEntergets the derived one.SandboxManager's constructor additionally validates the wiring: it rejects a null/blank agentId and asserts the id matches the state store's (SessionSandboxStateStore#getAgentId()), so guard keys and persisted slots cannot silently drift apart — both fail at build time.Tests
SandboxIsolationKeyTest: guard key carries the agent dimension, is stable for the same agent, is unchanged for non-USER scopes, and throws for USER with a null/blank agentId.SandboxManagerIsolationTest: a nested parent/child pair (each wired to its own agent-scoped store, asHarnessAgent.builddoes) uses distinct guard keys while the state store still receives the identical slot key. Constructor cases: agent-id mismatch with the store and a blank agentId both fail at build time.SessionSandboxStateStoreTest: pins the slot id to end with the guard key's value forUSERandAGENTscopes (two-source coupling) and to match forSESSION, catching drift between the two compositions (slotSessionIdvsforExecutionGuard).agentscope-harnesssuite: 2284 tests, 0 failures, 50 skipped.Compatibility
SandboxIsolationKey#forExecutionGuard,SessionSandboxStateStore#getAgentId; both new in this PR). TheSandboxManagerconstructor now rejects a blank/mismatched agentId — the framework wiring always passes a consistent, non-blank id.USERscope (...:user:<uid>→...:user:<agent>/<uid>). Leases are ephemeral, so no data migration — but during a rolling upgrade the lock-name mismatch lasts the whole mixed-version period (until every node runs the new code), not a single lease TTL: old nodes keep takinguser:<uid>while new ones takeuser:<agent>/<uid>, the names never meet, and the same slot is written concurrently (last-write-wins) rather than merely unserialised. Worth reflecting in the release notes; complete the rollout promptly.SandboxExecutionGuardimplementations that parsekey.getValue()will see the new value forUSER; the built-in guards treat it as an opaque string.Not covered
GLOBALscope still takes one guard key: a subagent spawned inside a call blocks on the lease the parent holds until that call ends. Documented as unsupported with subagents.SandboxContext-inheritance gap becomes reachable: a declared ISOLATED child runs against the parent's workspace projection (viaensureSessionDefaultspreferring the caller'sSandboxContext) while persisting into its own snapshot — writes don't land where the declaration says. Separate issue, not touched here.Related: #4440 (report), #2845 / #2846 (sibling same-key concurrency; the proposed default in-process guard would turn this deadlock into a 30-minute timeout, so the key fix is still needed).
Checklist
mvn spotless:applymvn test— full harness suite + extension guard suites)sandbox.md/subagent.md, en + zh)