agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[Bug]:会话 journal 重放与体积放大

Open oyx888 opened this issue 1 month ago • 4 comments

问题描述

用户点发送后要干等 20~30 秒才看到第一个字,但前端显示的「用时」只有 3~4 秒。

排查后确认 不是模型慢:模型整轮只花 0.95 秒,慢的是 SDK 在「收到命令 → 首次调用模型」之间做的 journal 重放,其中单独一项 SessionInteractions.pending() 就占 12.7 秒。

这个问题由两部分构成,两者互相放大:

  1. 读放大:一次 turn 的运行前阶段要做 7 次左右全量重放(每次重放都要把整条 commit 链读完并解析),而 SessionInteractions.pending() 内部是 O(n²)——循环调用 readAfter(cursor, 256),而每次 readAfter 都会重新遍历整条 commit 链。事件量越大,差距越大。
  2. 写放大:journal 体积按轮线性膨胀。我们的测试会话只有 12 轮对话,journal 已经 14.35 MB / 15,252 个事件 / 506 次提交——而模型实际输出的内容块(正文 + 思考 + 工具参数)合计只有 0.83 MB,整体放大 14~17 倍。体积越大,每次重放越慢,形成正反馈。

因为读放大是 O(n²)、写放大是线性,长会话的体验是持续退化的:同一会话前几轮的「提交 → 首个 token」间隔是 0.06 秒,第 10 轮已经是 23 秒(见 3.4 的退化曲线)。


调用链

1. 主导项:SessionInteractions.pending() 是 O(n²)

SessionExecution.prepare()(agentscope-core/.../session/SessionExecution.java L51-55)在每次调用模型前都会执行:

var view = SessionTurns.read(log);              // 全量重放 #1
...
var pending = SessionInteractions.pending(log); // 全量重放 #2(且是 O(n²))

而 SessionInteractions.pending()(agentscope-core/.../session/SessionInteractions.java L46-62)是:

public static Map<String, SessionEvent> pending(SessionLog log) {
    long upper = log.head().seq(), cursor = 0;
    var result = new LinkedHashMap<String, SessionEvent>();
    while (cursor < upper) {
        var batch = log.readAfter(cursor, 256);   // ← 每次都重走整条 commit 链
        if (batch.isEmpty()) throw new SessionLogException("Missing interaction prefix");
        for (var event : batch) {
            if (event.seq() > upper) break;
            if (event.type().equals("interaction/requested")) ...
            if (event.type().equals("interaction/resolved")) ...
            cursor = event.seq();
        }
    }
    return Collections.unmodifiableMap(result);
}

readAfter(after, limit)(JournalSessionLog.java L378)实际是 scan(after, Math.min(head.seq(), after + limit)),而 scan(L321)总是从 head 沿 parent 链往回走,直到 expected > after 为止——它没有利用 through 上界做剪枝,也就是说读一个 256 条的窗口和读整个 journal 的代价是同一个量级。

结果:本会话 15,252 个事件 / 256 ≈ 60 次 readAfter,每次都要走约 506 个 commit,合计约 6 万次存储读。实测 12.696 秒,而同样数据做一次完整 scan(0, head) 只要 0.786 秒(见 3.2)。

2. scan 对每个 commit 读两次、解析两次

scan() 里:

  • L330 为了探测分段边界,storage.read(path("commits/" + id + ".json")) 读一次;
  • 迭代器里 L363 又通过 readCommit(segments.next())(L274)读 同一个文件并再次 parse。

即每个 commit 在整个重放过程中被读 2 次、JSON 解析 2 次,SessionEvent 的构造还会再解析一次 payloadJson。

3. Windows 上每次 read 都新建一条 SQLite 连接

agentscope-harness/.../session/LocalSessionStorage.java L48-51 在路径分隔符为 \ 时委托给 SqliteSessionStorage,而 SqliteSessionStorage.read()(L77-90)每次读取都新建连接:

private Connection connect() throws SQLException, IOException {
    // 1) 逐段符号链接检查  2) Files.createDirectories
    // 3) Files.createFile(首次抛 FileAlreadyExistsException)
    // 4) DriverManager.getConnection
    // 5) PRAGMA synchronous=EXTRA + CREATE TABLE IF NOT EXISTS
}

一次 scan 对 467 个 commit 读 934 次 = 934 次连接建立 + 934 次 DDL。实测单次 read 0.69 ms(复用连接 0.053 ms,13 倍)。

4. 一次 turn 的运行前重放点(合计 7 次)

位置 重放内容
AgentSession.dispatch()(L410) SessionTurns.read(log)
AgentSession.receipt()(L363-369) log.scan(0, head.seq())
new SessionRecorder(...) 构造 SessionProjection.read(log) + log.scan(0, durableSeq) + SessionViews.transcript(log) = 3 次
SessionExecution.prepare() SessionTurns.read(log) + SessionInteractions.pending(log)
SessionExecution.beforeStep() / continueOrClose() 各一次 SessionTurns.read(log).applied()

且 AgentSession 的 dispatcher 是 schedulePeriodically(this::dispatch, 0, 100, MILLISECONDS)——每 100 ms 醒一次,只要有一条待处理命令,这套重放就完整跑一遍。

5. 写入侧:每个流式分片一条事件,每轮把同一份上下文存 5 遍

SessionModels.java L88-98,模型流的每一个 chunk 都直接落库:

Flux.defer(() -> delegate.stream(messages, tools, options))
    .doOnNext(chunk -> {
        last.set(chunk);
        recorder.append("model/chunk", Map.of(
                "modelCallId", id, "purpose", purpose, "chunk", chunk));
    })

而 journal 是 append-only、没有任何裁剪/保留机制(session 包里没有 prune/retention 实现,AtomicSessionStorage 只有 read/CAS)。同时每一轮还会重复存多份上下文快照:request/prepared(整份 prompt)、state/checkpoint(整份 AgentState)、context/build、context/replaced、compaction/start。


实测数据(Measurement)

3.1 环境与测量方法

  • 业务侧:Spring Boot 3 / JDK 21 集成层,AgentSession + EVENT_LOG + 本地 journal,模型为 DeepSeek 推理模型(deepseek-v4.1-flash)。
  • 测量机:Windows 11 + JDK 21,journal 为真实生产会话的只读副本,未改动任何数据。
  • 方法:直接调用 SDK 的公开类(JournalSessionLog / SessionTurns / SessionProjection / SessionViews / SessionInteractions)对同一份 journal 计时;POSIX 分支的耗时用「按 LocalSessionStorage 的 POSIX read() 语义(逐段 isSymbolicLink + exists + readAllBytes + 8 字节头解析)读同样 467 个 commit 文件」的方式在 NTFS + page cache 上模拟(对 Linux ext4 属偏保守估计)。
  • 另有业务侧打开 DEBUG 后的完整时间线(3.2 表 A),可与基准数据互相印证。

3.2 表 A:一次真实 turn 的时间线(业务日志)

时刻 阶段 耗时
21:02:17.724 业务侧收到 HTTP 提交 —
21:02:19.281 业务侧自己的 journal 重放(assertLatestTurnSettled / reconcileIfNeeded 等) 1.54 s
21:02:20.739 SDK dispatch() 里 SessionTurns.read 完成(PRE_CALL) 1.45 s
21:02:20.907 submit() 返回(HTTP 请求耗时 3,183 ms) —
21:02:43.435 首次调用模型(PRE_REASONING) 22.5 s ← 用户干等在这里
21:02:43.482 → 21:02:44.436 模型流式返回 0.95 s(prompt 14,473 tokens / 10,240 cached / completion 33)
21:02:45.795 state/checkpoint 落库 1.36 s

前端显示的「用时 4 秒」= run/start → run/end = 3.73 s,对应上表最后三行;用户实际承受的 22.7 秒死等完全不在这段统计里。

3.3 表 B:单个 SDK 调用在真实 journal 上的耗时

journal 快照:约 15.2k 事件 / 506 commit / 14.35 MB(各项测量在不同时刻采样,事件数差异 <1%)。

调用 Windows(SQLite 后端) POSIX 本地盘(模拟)
log.head() 0.002 s —
readAfter(head-128, 128) 0.027 s —
SessionInbox.snapshot() 0.043 s —
log.scan(0, head)(全量重放) 0.786 s 0.105 s
SessionTurns.read(log) 0.790 s ~0.11 s
SessionProjection.read(log) 0.801 s ~0.11 s
SessionViews.transcript(log) 0.786 s ~0.11 s
SessionInteractions.pending(log) 12.696 s 3.94 s
运行前阶段合计(模拟) ≈17.0 s ≈5 s
用户感知死等 ≈22.7 s ≈6 s

模拟值(≈17 s)与真实 turn 的 22.5 s 之间有约 5 s 差额:真实运行时同一 Schedulers.boundedElastic() 线程池上还有记忆整理等其它模型调用在跑,叠加 16 MB 级 JSON 的分配/GC 抖动。

存储层微基准:单次 read 连接复用 0.053 ms vs 每次新建连接 0.69 ms(13×);467 个 commit 的 Jackson 解析合计 0.086 s。

3.4 表 C:同会话随轮次退化(accepted → opened 间隔)

轮次 1 2 3 4 5 6 7 8 9 10 11
0.06 s 3.06 s 7.24 s 11.83 s 15.60 s 17.93 s 19.05 s 20.20 s 22.61 s 22.15 s 23.00 s

前几轮几乎无感,第 10 轮已 20 秒+。这与 journal 体积线性相关的结论一致。

3.5 表 D:journal 体积构成(12 轮会话,14.35 MB)

对象/事件类型 条数 占用 备注
model/chunk 14,588 7.97 MB 每个流式分片一条事件,平均 0.6 KB
state/checkpoint 69 2.20 MB 每条内嵌整份 AgentState.stateJson(平均 32.7 KB,最大 42.8 KB)
request/prepared 57 0.79 MB 每条内嵌整份 prompt(平均 14.1 KB,最大 60.4 KB)
compaction/start 15 0.38 MB 压缩输入快照(平均 25.7 KB)
context/build 27 0.32 MB 上下文构建快照
context/replaced 14 0.31 MB 上下文替换快照
message/user 26 0.09 MB 12 轮 + 14 条压缩摘要
message/assistant 27 0.06 MB 真正的对话正文
model/end / action/end / tool/* ~130 ~0.1 MB
blobs(>64 KB 载荷单独落地) 17 1.16 MB

平均 每轮 1.2 MB / 1,271 个事件 / 42 次提交。

3.6 表 E:model/chunk 的信封放大(同会话)

内容块类型 块数 实际内容 journal 占用 放大
text 8,597 304 KB 4.50 MB 15.2×
tool_use 2,824 332 KB 1.72 MB 5.3×
thinking 3,088 198 KB 1.70 MB 8.8×
合计 14,509 834 KB 7.93 MB 9.7×

单条 chunk 事件的固定信封开销约 550 字节:

{"schemaVersion":1,"eventId":"94170b34-...","seq":16,"occurredAt":1793082971715,
 "type":"model/chunk","executionRunId":"cd031c9c...","turnId":"59c03ddd-...",
 "required":true,"payloadJson":"{\"purpose\":\"REASONING\",\"chunk\":{\"id\":\"02179308...\",
 "content\":[...],\"usage\":null,\"metadata\":null,\"finishReason\":null},
 \"modelCallId\":\"24c06ccc-...\"}"}

三个 36~40 字符的 UUID/ID、恒为 null 的 usage/metadata/finishReason 都在每条 chunk 上重复。8,597 条 text 分片合计只携带约 300 KB 正文,平均每条约 35 个字符(按内容块 JSON 折算)。

3.7 表 F:平台差异(同一份 journal)

Windows(SQLite 后端) Linux 本地盘(POSIX 分支) Linux 网络存储(NFS/CephFS PVC,推算)
单次全量重放 0.786 s 0.105 s 1~3 s
pending() 12.7 s 3.9 s 60 s+
运行前合计 ≈17 s ≈5 s 分钟级

POSIX 分支没有 JDBC 连接开销,但 path() 对每次 read 都要逐段 isSymbolicLink(每个 commit 约 10 次 syscall),在本地盘上是被 page cache 遮住的;一旦 journal 放在网络文件系统(K8s PVC 很常见),每次 read 的 RPC 延迟会让重放成本回到甚至超过 Windows。

结论:这不是 Windows 专属问题,只是 Windows 的常数更大。


复现步骤(To Reproduce)

  1. 用 agentscope-harness 的 AgentSession + sessionHistoryMode = EVENT_LOG + 本地文件 journal(Windows 走 SQLite)。
  2. 选一个会输出 thinking 的推理模型,进行约 10 轮带工具的对话(每轮有思考、工具调用、压缩检查点)。
  3. 观察 journal.sqlite3 / journal/ 体积:model/chunk 会占到 90%+ 的事件数与 50%+ 的体积。
  4. 在业务侧记录「提交命令」到「首个模型 token」的间隔,或在 SDK 内直接计时:
    long t0 = System.nanoTime();
    SessionInteractions.pending(log);          // 12.7 s(本会话)
    System.out.println((System.nanoTime() - t0) / 1e6 + " ms");
    
  5. 同一 journal 上对比 log.scan(0, log.head().seq()):0.786 s。pending 比完整重放还慢 16 倍,因为它把完整重放做了 60 次。

oyx888 avatar Oct 27 '26 13:10 oyx888

I would like to take the focused SessionInteractions.pending() read-amplification fix.

I verified current main (4100c864c): pending() pages through readAfter(cursor, 256), while JournalSessionLog.readAfter() starts a new commit-chain scan() for each page. A deterministic 600-event regression currently observes three readAfter() passes and no stable-prefix scan.

My scope will stay deliberately narrow:

  • capture head.seq() once and traverse log.scan(0, upper) once;
  • preserve requested/resolved interaction semantics and the stable-prefix boundary;
  • add a contract regression proving one scan and no paged restart;
  • leave chunk persistence, checkpoint payloads, SQLite connection reuse, and retention/compaction to separate changes.

The regression fails on current main and passes with the local candidate; the adjacent session tests also pass (14 tests total). I will run the full core suite before opening the PR.

wahllllll avatar Oct 28 '26 03:10 wahllllll

Opened #3823 for the single-pass pending() fix.

Evidence on the branch:

  • The new regression fails on unmodified main (expected: <1> but was: <0> for the stable-prefix scan counter) and passes with the change.
  • Focused session tests: 14 tests, 0 failures.
  • Full core suite: 2831 tests, 0 failures, 0 errors apart from two pre-existing DangerousPathBypassTest symlink cases that need Windows symlink privileges (they also fail on unmodified main).
  • spotless:check passes.

Scope stays narrow: read amplification in pending() only. Chunk envelope size, repeated context snapshots, and per-read SQLite connections are untouched and remain open for separate changes.

wahllllll avatar Oct 28 '26 03:10 wahllllll

Opened #3823 for the single-pass pending() fix.已为 pending() 的单向修复问题打开了 #3823 。

Evidence on the branch:关于该分支的证据:

  • The new regression fails on unmodified main (expected: <1> but was: <0> for the stable-prefix scan counter) and passes with the change.新的回归方法在未经修改的 main 情况下无法运行(对于带有稳定前缀的扫描计数器,即 expected: <1> but was: <0> ),而经过修改后则能够正常运行。
  • Focused session tests: 14 tests, 0 failures.专注的测试过程:共进行了 14 次测试,没有失败。
  • Full core suite: 2831 tests, 0 failures, 0 errors apart from two pre-existing DangerousPathBypassTest symlink cases that need Windows symlink privileges (they also fail on unmodified main).完整的核心组件套件包含:2831 次测试,没有一次失败,也没有出现错误。不过,有兩个案例需要 Windows 的符号链接权限才能正常运行,这些案例在未经修改的 main 路径上也会失败。
  • spotless:check passes.   spotless:check 通过了。

Scope stays narrow: read amplification in pending() only. Chunk envelope size, repeated context snapshots, and per-read SQLite connections are untouched and remain open for separate changes.范围仍然比较窄:仅对 pending() 中的读取操作进行了扩展。块大小、重复使用的上下文快照以及每个读取操作的 SQLite 连接均未发生变化,可以继续进行单独的调整。

我合并你的修改经过验证,并没有改善多少,submit->openclient发出,进行一次长任务3轮对话,,完结之后发一句谢谢,卡住39秒,估计还是新的session性能是有问题的

oyx888 avatar Oct 28 '26 15:10 oyx888

Thanks for measuring this — that is very useful, and the observation is real. #3823 only removes one of several replays, so it cannot explain or fix the 39 s you are seeing.

To make the effect measurable rather than anecdotal, I instrumented the storage layer with a read counter over a synthetic journal (500 commits x 30 events = 15,000 events) replayed through JournalSessionLog:

  • one full replay, log.scan(0, head.seq()) = 1002 storage reads, i.e. 2.004 reads per commit — scan() reads each commit twice (once walking the parent chain, once inside readCommit), parses it twice, and recomputes the SHA-256;
  • SessionInteractions.pending() now costs 1004 reads, i.e. exactly one replay, where it previously issued ~60 passes.

So the patch does what it claims, but on a turn start these full replays still remain:

  1. AgentSession.submit() -> receipt(command) -> log.scan(0, head.seq())
  2. AgentSession.start() -> immediate dispatch() -> SessionTurns.read(log)
  3. SessionExecution.prepare() -> SessionTurns.read(log)
  4. new SessionRecorder(...) -> SessionProjection.read(log)
  5. the same constructor -> log.scan(0, durableSeq)
  6. the same constructor -> SessionViews.transcript(log)
  7. SessionExecution step paths -> SessionTurns.read(log).applied() (twice)

That is 7-9 independent full replays per turn start, each paying the 2x per-commit amplification. With your Windows figure of ~0.69 ms per read, 500 commits already cost ~0.7 s per replay, so ~5 s for the replays alone before the journal grows — which is consistent with 39 s once three long rounds have made it several times larger.

I am continuing to work on this, and the next changes I intend to make are:

  • Collapse the per-turn replays into one. All of the call sites above replay the same committed prefix. Since the journal is append-only and the prefix is fully determined by head.seq(), one shared prefix replay per turn can serve turns, pending interactions, projection and transcript, turning 7-9 replays into 1.
  • Stop paying for each commit twice. If it can be done without materializing the whole journal in memory, scan() should reuse what the parent-chain walk already parsed instead of reading and hashing each commit again. I will coordinate this with #3673 (perf(session): reuse scoped reads within journal scans), which already touches JournalSessionLog.scan.

If you can share the per-phase breakdown behind the 39 s (timers around receipt(), the immediate dispatch(), SessionExecution.prepare() and the SessionRecorder constructor), that would let me confirm which of the two above dominates in your journal before I write the code.

Please feel free to comment here at any time with objections or with your own measurements, especially if you think the shared-replay approach is the wrong direction.

wahllllll avatar Oct 28 '26 15:10 wahllllll