Skip to content

[harness] 沙箱模式下会话镜像按 agent 级兜底字段钉沙箱,同一 agent 多用户并发时会话日志可能写入他人沙箱 #4273

Done

Description

@chenrongquan

版本

项目 版本
使用版本 io.agentscope:agentscope-harness:2.0.5(Maven Central),同时依赖 agentscope-core / agentscope-extensions 2.0.5
同样存在 2.0.x 分支(提交 29952baf6,2026-11-19 核对,SessionTree#pinIfSandbox 代码相同)
未核对 main(f4e6a076b):#3441 已删除 SessionTree,新设计下是否有同类问题未核对
运行环境 JDK 21,DockerFilesystemSpec,IsolationScope.USER,同一个 HarnessAgent 实例服务多个用户

官方文档的描述

同一 userId 的多次 call() → 自动复用同一沙箱(或从快照恢复);不同 userId → 各自独立。
—— https://java.agentscope.io/v2/zh/docs/harness/sandbox (「一个最小例子」)

工作区数据(记忆、会话、任务、技能、沙箱状态)由单一的 IsolationScope 分桶……单个 HarnessAgent 实例可服务数千并发用户,用户间数据零泄漏。
—— https://java.agentscope.io/v2/zh/docs/harness/workspace (「设计理念」第 3 条)

运行时产物:MEMORY.md、memory/、agents//... 都落在沙箱内。
—— 同页「模式 2 · 沙箱」

即:沙箱模式下会话日志(agents/<agentId>/sessions/)应落在本用户的沙箱内,不同用户互不可见。

实际行为

会话日志的主副本先写宿主本地,再由 SessionTree 异步镜像进 agent 文件系统(沙箱模式下即 SandboxBackedFilesystem 代理)。镜像前用 pinIfSandbox 钉住目标沙箱:

// SessionTree.java:601-608(2.0.5)
private static AbstractFilesystem pinIfSandbox(AbstractFilesystem fs) {
    if (fs instanceof SandboxAware aware) {
        Sandbox sb = aware.getSandbox();          // ← 读 agent 级兜底字段
        if (sb != null) {
            return new PinnedSandboxFilesystem(sb);
        }
    }
    return fs;
}

getSandbox() 返回的是 SandboxBackedFilesystem 上 volatile Sandbox sandbox 字段(SandboxBackedFilesystem.java:65、77)。该类 Javadoc 已说明:每个 agent bean 只有一个这样的代理,该字段是给无调用上下文的调用方用的兜底,"last-writer-wins under concurrency and must not be relied on for isolation"。

但 SessionTree 手里其实已经有本次调用的上下文:

  • SessionTranscriptWriter.java:103-109 每次调用新建 SessionTree,并 .setRuntimeContext(rc) 绑定本次调用的 RuntimeContext;
  • SessionTree.java:86 的 fsRc 注释说明它就是为异步镜像线程保留调用身份;
  • SandboxLifecycleMiddleware.java:122 在 acquire 时把 SandboxAcquireResult 放进同一个 RuntimeContext。

pinIfSandbox 没有用 fsRc.get(SandboxAcquireResult.class),而是读了兜底字段。

后续上传走 PinnedSandboxFilesystem.uploadFiles → SandboxBackedFilesystem.uploadFiles → requireSandbox(fsRc)(SandboxBackedFilesystem.java:125、239-249):

  • 本次调用尚未释放时:fsRc 里还有本次绑定,优先用它,落点正确;
  • 本次调用已释放后(SandboxLifecycleMiddleware.java:164 把绑定置为 null):退回被钉的沙箱。若钉住时兜底字段指向的是另一个用户后 acquire 的沙箱,且该沙箱仍在运行,就会通过 PinnedSandboxFilesystem 的释放门检查(检查的是被钉沙箱的门),把本用户的会话日志 / transcript 分段写进他人沙箱。

镜像是异步的(MIRROR_EXECUTOR),而调用结束后立即释放,因此"上传发生在释放之后"是常见时序,不是极端情况。scheduleMirror(SessionTree.java:583-595,<sessionId>.log.jsonl 与 context 文件)和 scheduleSegmentMirror(SessionTree.java:549-556,transcript 分段)都走这条路径。

后果:

  1. 跨用户泄漏:用户 B 在自己的沙箱里用 execute / read_file 能看到用户 A 的 agents/<agentId>/sessions/<A 的 sessionId>.log.jsonl;若开启快照,该文件还会随 B 的快照持久化。
  2. 本用户副本丢失:若被钉的他人沙箱已释放,上传被拒(Sandbox has been released),本用户沙箱里的会话副本缺这一次更新。
  3. 释放门失效:本用户沙箱的 release gate 管不到这次上传,上传持有的是被钉沙箱的门锁。

复现(示意,源码推导)

HarnessAgent agent = HarnessAgent.builder()
    .name("shared").model(model).workspace(ws)
    .filesystem(new DockerFilesystemSpec().image("ubuntu:24.04"))   // 默认 USER
    .build();

// T0  A: call(userId=alice) 开始 → acquire sbA,兜底字段 = sbA
// T1  B: call(userId=bob)   开始 → acquire sbB,兜底字段 = sbB(覆盖)
// T2  A: 本轮写会话日志 → scheduleMirror → pinIfSandbox 读到 sbB → Pinned(sbB)
// T3  A: call 结束 → release,fsRc 中的 SandboxAcquireResult 置 null
// T4  镜像线程执行:requireSandbox(fsRc) 取不到绑定 → 回落 Pinned 字段 sbB
//     sbB 仍在运行(B 未结束)→ alice 的会话日志写入 bob 的沙箱
// 验证:在 bob 的下一轮让 agent 执行 `ls agents/shared/sessions/`,可见 alice 的 sessionId

我们在自己的平台上已通过路由绕过(见下),上述时序依据源码推导,未在原生配置下单独复现。

期望

按文档所述"不同 userId → 各自独立""用户间数据零泄漏",异步镜像应始终写入发起本次写入的那次调用所绑定的沙箱;该沙箱已释放时放弃(best-effort),而不是回落到 agent 级共享字段指向的其他沙箱。

修复建议

pinIfSandbox 优先使用 fsRc 中本次调用的绑定,取不到时不回落兜底字段(镜像本就是 best-effort):

private AbstractFilesystem pinIfSandbox(AbstractFilesystem fs) {
    if (fs instanceof SandboxAware) {
        SandboxAcquireResult bound = fsRc != null ? fsRc.get(SandboxAcquireResult.class) : null;
        if (bound != null && bound.getSandbox() != null) {
            return new PinnedSandboxFilesystem(bound.getSandbox());
        }
        return null; // 或返回一个直接跳过上传的空实现,调用方据此不调度镜像
    }
    return fs;
}

(需改为实例方法以读取 fsRc;调用方对返回值为空时跳过镜像。)

另外说明:PR #2854(修 #2849)把兜底字段改为按获取顺序保留绑定,解决的是"字段被提前清空";无上下文调用方仍取最新一个绑定,不能修复本问题。

相关

Activity

  1. aiyili commented on Nov 27, 2026

    @aiyili
    Contributor

    I'd like to take this one, against 2.0.x.

    Confirmed at the tip of 2.0.x (50886798). SessionTree.pinIfSandbox is exactly as you quote: it reads the agent-level fallback (SandboxAware#getSandbox()) and both mirror paths go through it — scheduleMirror for the session log / context files and scheduleSegmentMirror for transcript segments. The upload then goes PinnedSandboxFilesystem.uploadFiles → SandboxBackedFilesystem.uploadFiles → requireSandbox(fsRc), so once the owning call has released, it lands in whatever sandbox was pinned.

    main is not affected, for what it is worth. I checked before choosing the target branch:

    • the session-log mirror is gone — feat: redesign Harness context and unify Service sessions with JEV #3441 removed SessionTree and pinIfSandbox together;
    • nothing on main pins a filesystem to the fallback field, and the fallback getter has no caller left in the repository's main sources;
    • the sandbox filesystems do not implement journalStorage, so on main session logs are not stored in a sandbox at all.

    What I plan to change. The tree already holds the owning call's RuntimeContext (fsRc), and the middleware binds the call's sandbox on it. pinIfSandbox will pin that sandbox — fsRc.get(SandboxAcquireResult.class) — instead of the shared field, which keeps the purpose of the pin (async upload surviving the call's unbind) while making the target the right sandbox. When the owning call has no binding of its own, the mirror will be skipped rather than sent to whatever sandbox the fallback happens to point at.

    Regression test: two concurrent calls on one agent, B acquiring after A, A's mirror scheduled and then A released — A's files must reach A's sandbox and nothing must reach B's.

    One boundary, so nobody expects it from this PR: requireSandbox still falls back to the shared field for callers that have no per-call context (WorkspaceMessageBus and the like). That is the same last-writer-wins field under a different caller and is what #2849 is about; this fix is about the session-log mirror.

  2. aiyili commented on Nov 27, 2026

    @aiyili
    Contributor

    Opened #4447 against 2.0.x.

    The mirror now pins the sandbox that SandboxLifecycleMiddleware bound to the owning call's RuntimeContext, which SessionTree already held, instead of the agent-level slot of the shared proxy. A call that has no sandbox of its own gets no mirror target, so nothing is written into whichever sandbox the slot points at.

    SessionTreeMirrorIsolationTest (3 cases, using the real SandboxLifecycleMiddleware with two calls on one proxy) fails on unmodified 2.0.x with alice's session files and transcript segment under /ws-bob/, and passes with the change. The full agentscope-harness suite has the same failing list before and after on Windows and in a Linux container; the four Linux failures are python3: not found in the image and one root-user permission case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions