Skip to content

perf(agent-state): stop storing session content ~13× in the runtime database #7272

In progress

Description

@Astro-Han
English

Problem

After two weeks of daily use, my runtime-rust.sqlite is 1.7 GB (38 sessions, 360 runs, ~94k recall messages). The data the sessions actually contain is about 130 MB: user and assistant text, tool arguments, and tool output. On disk, every byte of conversation content costs about 13 bytes.

Session length is not the reason. Maka sessions are long, so I compared the ratio of disk size to content size, which does not depend on session length. Content is the same in every case: user/assistant text, tool arguments, and tool output, excluding images. All figures were measured on one machine.

Product Format Disk Content Ratio
Maka SQLite 1715 MB ~130 MB ~13×
Claude Code (screenshots excluded) JSONL 603 MB 74 MB 8.2×
Devin CLI SQLite 2715 MB 443 MB 6.1×
Pi JSONL 761 MB 142 MB 5.3×
OpenCode SQLite 480 MB 116 MB 4.1×
Codex rollouts JSONL (zstd) 160 MB 177 MB 0.9× (1.7× uncompressed)

Breakdown of the Maka database (dbstat):

Area Size Kind
Recall (agent_recall_messages, agent_recall_terms, indexes) 689 MB derived
contents 604 MB authoritative
agent_session_history* 176 MB derived
everything else 226 MB mixed

Four causes, in order of how clearly they are defects:

  1. Recall indexes cell lifecycle receipts and indexes cell output twice. Rule::Cell in recall/index.rs turns every CellEvent into a searchable tool_result message. Its serialized JSON is stored as a non-internal Receipt field.
    • Bookkeeping events such as started, vm_bound, child_prepared, child_display_recorded, child_admitted, child_bound and loaded_tools_published each become a message. Their text consists of UUIDs, digests and deployment references: about 15 MB.
    • ChildObserved inlines the whole operation reply, including the tool output, as escaped JSON. ChildResultRecorded for the same operation then indexes the same output again as plain text: about 34 MB. For example, the stdout of one Shell call appears in both messages.
    • Together that is about 27% of all recall text (49 of 181 MB). Cells account for 75% of recall text (66.5k messages from 4,502 cells), so this pattern dominates the index. The receipts and the duplicate are also stored again in folded and in the gram index.
  2. Recall stores every body twice. agent_recall_messages.body and folded are 175 MB each. folded caches fold(&body), which recall/query.rs already recomputes on another path, and a query page checks at most 128 candidates.
  3. Long text keys repeat in every row and index. Every agent_session_history row stores owner (a 106-byte JSON string) and session (100 bytes). Seven of its indexes start with (owner, session). As a result, 125k rows take 183 MB, about 1.5 KB per row. The recall unique and order indexes follow the same pattern.
  4. contents is uncompressed and repeats static text per record. The 544 MB of payloads compress to 52 MB with zstd-3. Content addressing cannot deduplicate the repeated parts because they are embedded in records that otherwise differ:
    • every request composition carries the full systemPrompt and tools: 31 MB over 1,086 steps, next to toolCatalogDigest;
    • every tool operation carries the full tool definition: 33 MB over 3,871 calls;
    • every external-agent prompt carries the full system and instructions: 51 MB over 1,085 rows.

Desired outcome

Storage grows with the content it holds, at a ratio comparable to other coding agents (roughly 3–5×). Recall keeps finding the same conversations. Existing databases upgrade in place, and no state is lost.

Direction

  1. Recall indexes each tool call once. Drop lifecycle receipts from recall. Index a cell child's output only from its settled result (ChildResultRecorded / LocalChildReturned), not from the inlined ChildObserved reply. If some receipt fields must stay searchable, such as a shell command line, index those fields alone.
  2. Drop agent_recall_messages.folded and fold the candidates at query time.
  3. Replace the (owner, session) text keys in derived history and recall tables and indexes with an integer surrogate.
  4. Compress contents at the storage layer, for example with zstd and a trained dictionary. Digests stay computed over the uncompressed bytes, so every ContentRef and cross-record reference stays valid, and only the encoding is migrated in place. SQL views that json_extract from payload read through a registered decode function.

Steps 1–3 touch only derived state and ship as versioned drop-and-rebuild migrations. Step 4 is a forward migration of authoritative data. Step 1 can land on its own and removes the largest share of noise.

Why this direction

  • VACUUM does not help. The freelist is empty, and the space is live data. design(storage): decide where runtime.sqlite's one-time full VACUUM runs before converting it to incremental vacuum #6000 tracks vacuum strategy separately.
  • Splitting static text out of contents records saves about as much as step 4. However, it changes authoritative payload shapes and their digests, which forces cascading rewrites of every referencing fact.
  • Per-row zstd without a dictionary is simpler, but it cannot remove repetition across rows, which is where most of the redundancy lives.
  • Capping or skipping large tool output in recall would shrink the index further. Devin CLI, for example, indexes only assistant and user text. That choice changes what users can find, so it should be decided separately after steps 1–3 show how much remains.

Acceptance criteria

  • Each tool call contributes its output to recall once. Lifecycle receipts are not indexed.
  • agent_recall_messages no longer stores folded, and existing recall search and ranking tests still pass.
  • Derived history and recall tables key sessions by an integer surrogate instead of repeated owner/session text.
  • contents payloads are stored compressed. Digests, ContentRefs and SQL views keep working unchanged.
  • Existing databases upgrade in place. upgrade_compat.rs covers the rebuilt indexes and the compressed contents, and the compat capsules replay.
  • The PR reports before/after database size on a real database.
中文

问题

日常使用两周后,我的 runtime-rust.sqlite 有 1.7 GB,对应 38 个会话、360 个 run、约 9.4 万条 recall 消息。这些会话里真正的内容约 130 MB,包括用户和助手的文字、工具参数和工具输出。也就是说,每 1 字节对话内容在磁盘上约占 13 字节。

这不是会话长短造成的。Maka 的会话普遍较长,所以这里不按会话比较,而是比较"磁盘占用 ÷ 内容大小",这个比值与会话长度无关。各产品的内容口径一致:用户和助手文字、工具参数、工具输出,不含图片。所有数字都在同一台机器上实测。

产品 格式 磁盘 内容 放大倍数
Maka SQLite 1715 MB 约 130 MB 约 13×
Claude Code(不含截图) JSONL 603 MB 74 MB 8.2×
Devin CLI SQLite 2715 MB 443 MB 6.1×
Pi JSONL 761 MB 142 MB 5.3×
OpenCode SQLite 480 MB 116 MB 4.1×
Codex 会话文件 JSONL(zstd) 160 MB 177 MB 0.9×(未压缩 1.7×)

Maka 数据库构成(dbstat):

部分 大小 性质
Recall(agent_recall_messages、agent_recall_terms 及索引) 689 MB 派生
contents 604 MB 权威
agent_session_history* 176 MB 派生
其余 226 MB 混合

四个原因,按"是缺陷"的明确程度排序:

  1. Recall 收录了 cell 生命周期回执,并把 cell 输出收录了两次。 recall/index.rs 中的 Rule::Cell 会把每个 CellEvent 变成一条可搜索的 tool_result 消息,事件序列化后的 JSON 作为非 internal 的 Receipt 字段写入。
    • started、vm_bound、child_prepared、child_display_recorded、child_admitted、child_bound、loaded_tools_published 等簿记事件各自成为一条消息,文本全是 UUID、摘要和部署引用,约 15 MB。
    • ChildObserved 会把整个 operation 回复(包括工具输出)以转义 JSON 的形式内联,同一 operation 的 ChildResultRecorded 又把这份输出以纯文本再收录一次,约 34 MB。例如同一次 Shell 调用的 stdout 会同时出现在这两条消息里。
    • 两者合计约占 recall 文本的 27%(181 MB 中的 49 MB)。cell 占 recall 文本的 75%(4,502 个 cell 产生 6.65 万条消息),所以这种模式主导了索引。这些回执和重复内容还会在 folded 和 gram 索引里再存一次。
  2. Recall 的每条正文存了两份。 agent_recall_messages 的 body 和 folded 各 175 MB。folded 只是缓存了 fold(&body),而 recall/query.rs 在另一条路径上本来就会现算;每页查询最多也只核对 128 个候选。
  3. 长文本键在每行、每个索引里重复。 agent_session_history 每行都存 owner(106 字节的 JSON 字符串)和 session(100 字节),7 个索引都以 (owner, session) 开头,结果 12.5 万行占了 183 MB,平均每行约 1.5 KB。recall 的唯一索引和排序索引也是同样的情况。
  4. contents 没有压缩,每条记录都重复携带静态文本。 544 MB 载荷用 zstd-3 能压到 52 MB。按内容寻址去重不起作用,因为重复部分嵌在本身各不相同的记录里:
    • 每次请求组装都带着完整的 systemPrompt 和 tools(1,086 步,31 MB),旁边已经有 toolCatalogDigest;
    • 每次工具调用都带着完整的工具 definition(3,871 次,33 MB);
    • 每条外部 agent 提示都带着完整的 system 和 instructions(1,085 条,51 MB)。

期望结果

存储增长与实际内容成正比,放大倍数与其他编码 agent 相当(约 3–5 倍)。Recall 仍能搜到同样的对话,已有数据库原地升级,不丢任何状态。

方向

  1. Recall 每次工具调用只收录一次。 不再收录生命周期回执;cell 子调用的输出只从已落定的结果(ChildResultRecorded / LocalChildReturned)收录,不再从内联的 ChildObserved 回复收录。如果回执里个别字段(例如 shell 命令行)需要能被搜到,只收录这些字段。
  2. 删掉 agent_recall_messages.folded,查询时对候选现算。
  3. 派生的 history 和 recall 表及索引改用整数代理键,替代 (owner, session) 长文本键。
  4. 在存储层压缩 contents,例如用 zstd 加训练好的字典。摘要仍对未压缩字节计算,因此所有 ContentRef 和跨记录引用保持有效,原地迁移的只有存储编码。对 payload 调用 json_extract 的 SQL 视图改为经由注册的解码函数读取。

第 1–3 步只涉及派生状态,用带版本的删除重建迁移交付;第 4 步是权威数据的前向迁移。第 1 步可以单独合入,它去掉的噪声最多。

为什么选这个方向

  • VACUUM 没用。 freelist 是空的,占用的都是活数据。vacuum 策略由 design(storage): decide where runtime.sqlite's one-time full VACUUM runs before converting it to incremental vacuum #6000 单独跟踪。
  • 把静态文本从 contents 记录里拆出去,省下的空间和第 4 步差不多。但它会改变权威载荷的结构和摘要,迫使所有引用它的 fact 连锁改写。
  • 不带字典的逐行 zstd 更简单,但消除不了跨行重复,而大部分冗余恰恰在跨行重复里。
  • 对 recall 中的大段工具输出设上限或不收录,还能进一步缩小索引。例如 Devin CLI 只索引助手和用户文字。但这会改变用户能搜到的内容,应在第 1–3 步完成、看清剩余规模后单独决定。

验收标准

  • 每次工具调用只向 recall 贡献一次输出,生命周期回执不进索引。
  • agent_recall_messages 不再存 folded,现有 recall 搜索和排序测试仍然通过。
  • 派生的 history 和 recall 表用整数代理键区分会话,不再重复存 owner/session 文本。
  • contents 载荷压缩存储,摘要、ContentRef 和 SQL 视图照常工作。
  • 已有数据库原地升级;upgrade_compat.rs 覆盖重建后的索引和压缩后的 contents,兼容性测试数据集能正常回放。
  • PR 中给出在真实数据库上改动前后的大小对比。

Activity

  1. added
    enhancement
    on Nov 25, 2026
  2. M4n5ter commented on Nov 25, 2026

    @M4n5ter
    Member
    English

    Adding a much larger real-world sample (~12–13× the DB size in the issue) from 15 days of heavy daily use (Nov 10–25, including heavy Code Mode + external-agent workloads). Because this DB spans both before and after #7102 (32 KiB prompt chunks) and #7115 (RequestComposition dedup), splitting full-DB vs. post-#7102/#7115 steady-state growth (Nov 22–25) also surfaces a few additional defects and an empirical check on Direction 4.

    Dataset & dbstat breakdown

    • Full DB (15 days, Nov 10–25): 21.46 GiB (21,971 MiB, page_size=4096, freelist_count=31) — 285 active sessions, 2,196 runs, 1.30M facts, 939k recall rows, 2.03M contents rows.
    • Deduplicated conversation content (same definition: user + assistant + reasoning + tool args + deduplicated tool outputs, excluding images): ~884–1,106 MiB → ~20–25× overall.
    • Post-#7102/#7115 steady-state (Nov 22–25, 4 days, current main): 137 sessions, 969 runs, 514k facts, 397k recall rows, ~362–491 MiB true content, ~6.4 GiB new DB growth (~1.5 GiB/day) → still ~13–18×.
    Area Full DB (15d) Share Breakdown
    contents (authoritative) 10,438 MiB 47.5% table 10,260 + index 178
    Recall (agent_recall_*, derived) 7,411 MiB 33.7% messages table 5,090 + 7 indexes 1,287 + terms FTS 1,033
    agent_session_history (derived) 2,037 MiB 9.3% table 594 + 13 indexes 1,443
    Everything else 2,084 MiB 9.5% agent_facts 352, agent_usage_calls/results 392, application_intents 231, agent_cells 228, agent_content_pins 220, application_operations 164

    Additional findings beyond the 4 causes listed

    1. Recall: three more amplification sources alongside CellEvent receipts / ChildObserved

    The issue's observations hold at 10× scale (body = folded = 2,057 MiB each; cell = 72.5% of recall body; child_observed 377 MiB duplicates child_result_recorded 333 MiB; pure cell bookkeeping receipts without started/child_prepared are 355k rows / 37.8% of all rows, or 483k / 51.4% including them). In addition:

    • Non-cell tool results are also indexed twice: recall/index.rs indexes LocalToolReturned (116 MiB, 19.3k rows) and HostToolResultRecorded (5.4 MiB, 685 rows) via Rule::Returned, and then indexes the exact same ToolReturn again via Rule::Accepted (ToolResultAccepted, 123.3 MiB, 20.0k rows). Across 19,302 paired (local_tool_returned, tool_result_accepted) rows, 13,593 are byte-for-byte identical and the rest differ only by a ~115 B wrapper.
    • External-agent exec quad-indexing & streaming-delta row explosion:
      • When an external agent invokes Maka's exec, the same output is indexed across child_observed → child_result_recorded → cell.completed (347 MiB) → external_effect tool_result (220 MiB). (E.g. an 11.57 MiB output appears verbatim in both cell.completed and the immediately following external_effect.)
      • Rule::External turns every OutputDelta / ThinkingDelta into a standalone recall row: external_task_observed contributes 123,418 rows (47.9k visible rows averaging 72 B, 75.5k internal rows averaging 267 B) for only 22.6 MiB of text — paying ~170 MiB of (owner, session) 7-index overhead and breaking cross-delta phrase matching.
    • Exact duplicate index on agent_recall_messages + other (owner, session) tables:
      • 0011_usage_recall.sql defines CREATE INDEX agent_recall_message_order ON agent_recall_messages(owner,session,sequence,ordinal) (212.8 MiB) on top of UNIQUE(owner,session,sequence,ordinal) (sqlite_autoindex_agent_recall_messages_1, 212.8 MiB), solely so positions.rs can use INDEXED BY. Replacing the table-level UNIQUE constraint with a named UNIQUE INDEX eliminates 212.8 MiB immediately.
      • agent_usage_calls (297 MiB total; 168 MiB in indexes) repeats (owner, session) across multiple indexes the same way agent_session_history and agent_recall_messages do — worth including if surrogate session keys are introduced.

    2. contents: empirical zstd-3 benchmark (Direction 4 reality check)

    On current main (Nov 22–25), #7102 already reduced promptChunks growth from 101–320 KiB/step (128 KiB chunks) to 39–49 KiB/step (32 KiB chunks), and #7115 deduplicated composition.surface (only 29 MiB across 21.9k steps). Today's largest new contents writers are cell (535 MiB / 4d), external_effect (449 MiB / 4d), agent_facts envelopes (250 MiB / 4d), and step_prepared (228 MiB / 4d).

    Inside external_effect (807 MiB full DB; 449 MiB Nov 22–25), every output blob stores both output (33.7%) and projection (32.2%) inside the same JSON object alongside repeated tool definitions (28.0%, 257 MiB full DB). cell result envelopes similarly store both output and projection, and provenance.toolContracts still accounts for 80.5% (~4.6 KiB/step) of Nov 24–25 provenance.

    Benchmarking zstd-3 on a contiguous 50,000-row slice from Nov 22–25 (106.71 MiB raw), using a disjoint 48 KiB raw dictionary (2 tool defs + 1 toolContracts + 31 KiB fact envelopes from earlier rows):

    Mode Size Ratio Notes
    Raw 106.71 MiB 100.0% (1.00×) current
    Per-row zstd-3 (no dict) 44.47 MiB 41.7% (2.40×) full-DB 1/100 sample: 37.7% (2.65×)
    Per-row zstd-3 + 48 KiB dict 34.00 MiB 31.9% (3.14×) tool_call(definition) 41.6% → 9.2%; agent_facts 69.6% → 42.5%; step_meta 46.1% → 27.6%
    Sum of per-category zstd-3 streams 19.21 MiB 18.0% (5.55×) —
    Combined contiguous zstd-3 stream 10.01 MiB 9.4% (10.66×) reproduces the issue's 544 → 52 MB (9.6%)

    Two takeaways for Direction 4:

    1. A static dictionary genuinely helps static schemas/small rows, cutting tool_call definitions by 4.5× and small agent_facts envelopes by ~40% vs. plain per-row zstd.
    2. Expect ~3.1–3.5× (~70% reduction) from per-row zstd + trained dict, not the ~10× of a contiguous stream. The gap between per-category streams (18.0%) and the combined stream (9.4%) shows that roughly half the cross-row redundancy is dynamic per-session tool output repeated across application_operations.outcome → cell ChildResultRecorded → cell.completed → external_effect → promptChunks, which a static dictionary cannot match. Additionally, on GPT/Responses workloads, 71% of 32 KiB promptChunks contain high-entropy encrypted_content (avg 5.35 bits/byte), capping chunk compression around ~39–51%. Per-row zstd + trained dict is still a great simplicity/value trade-off (~70% savings without block packing), just worth sizing expectations accurately.

    3. Legacy / upgrade-path baggage visible in long-lived DBs

    A few things that explain why long-lived upgraded DBs grow disproportionately and are worth watching during in-place migrations:

    • recoveredCells triplication (~1.48 GiB in Nov 10–14): every step_prepared copies the full growing recoveredCells array into all three of provenance (~508 MiB), request (~503 MiB), and projection (~469 MiB). On Nov 15–25 the average dropped to ~11 KiB/step, but steps that do trigger recovery still produce up to 150 KiB × 3 per step.
    • ~1,018 MiB (16,488 rows) of pre-migration request blobs still pinned: when a previous migration rewrote RequestSpec.request (system/instructions → systemText/instructionsText) into new contents rows, model_attempt_admitted facts kept referencing/pinning the old pre-migration request blobs in agent_content_pins / agent_history_content_refs. Worth auditing all pin/referrer paths whenever a migration rewrites contents payloads.
    中文

    补充一份体量更大(约原 issue 样本 12–13 倍)的真实运行数据,来自 15 天高强度日常使用(11-10 ~ 11-25,包含大量 Code Mode 与外部 agent 场景)。由于该库横跨 #7102(32 KiB prompt 分块)与 #7115(RequestComposition 去重)合入前后,把全库和 #7102/#7115 之后的稳态增长(11-22 ~ 11-25)拆开看,还暴露出几处原 issue 未覆盖的问题,以及对方向 4(zstd 压缩)的实测验证。

    数据集与 dbstat 分布

    • 全库(15 天,11-10 ~ 11-25):21.46 GiB(21,971 MiB,page_size=4096,freelist_count=31)—— 285 个活跃会话、2,196 次 run、130 万条 fact、93.9 万条 recall 消息、202.7 万行 contents。
    • 去重后的实际对话内容(同口径:用户/助手文本 + 推理 + 工具参数 + 去重后的工具输出,不含图片):约 884–1,106 MiB → 整体放大 ~20–25×。
    • #7102/#7115 后的稳态增长(11-22 ~ 11-25,4 天,当前 main):137 个会话、969 次 run、51.4 万条 fact、39.7 万条 recall 消息、实际内容约 362–491 MiB、库体积净增 ~6.4 GiB(日均 ~1.5 GiB)→ 依然在 ~13–18×。
    区域 全库 (15d) 占比 细项
    contents(权威) 10,438 MiB 47.5% 表 10,260 + 索引 178
    Recall(agent_recall_*,派生) 7,411 MiB 33.7% messages 表 5,090 + 7 个索引 1,287 + terms FTS 1,033
    agent_session_history(派生) 2,037 MiB 9.3% 表 594 + 13 个索引 1,443
    其他全部 2,084 MiB 9.5% agent_facts 352、agent_usage_calls/results 392、application_intents 231、agent_cells 228、agent_content_pins 220、application_operations 164

    原 issue 4 条原因之外的新发现

    1. Recall 侧:除 CellEvent 回执 / ChildObserved 外还有三处冗余

    原 issue 指出的问题在 10 倍体量下完全成立(body 和 folded 各占 2,057 MiB;cell 占 recall 正文的 72.5%,child_observed 377 MiB 与 child_result_recorded 333 MiB 重复;不含 started/child_prepared 的纯簿记回执就占 35.5 万行 / 37.8%,含两者占 48.3 万行 / 51.4%)。此外:

    • 非 cell 工具结果同样被索引了两遍:recall/index.rs 中 Rule::Returned(local_tool_returned 116 MiB / 1.93 万行、host_tool_result_recorded 5.4 MiB / 685 行)与 Rule::Accepted(tool_result_accepted 123.3 MiB / 2.00 万行)各自读取同一份 ToolReturn 建索引。实测 19,302 对 (local_tool_returned, tool_result_accepted) 中有 13,593 对 body 逐字节完全一致,其余仅差约 115 B 的封装。
    • 外部 agent 调用 exec 的四重索引 + 流式 delta 行数爆炸:
      • 外部 agent 调用 Maka exec 时,同一份输出会依次进入 child_observed → child_result_recorded → cell.completed(347 MiB)→ external_effect tool_result(220 MiB)。(例如一条 11.57 MiB 的输出同时完整出现在 cell.completed 和紧随其后的 external_effect 中。)
      • Rule::External 将外部 agent 的每条 OutputDelta / ThinkingDelta 都写成独立的一行 recall 消息:external_task_observed 产生了 123,418 行(其中 4.79 万条可见文本平均仅 72 字节,7.55 万条 internal 文本平均 267 字节),总共仅 22.6 MiB 正文却吃掉约 170 MiB 的 (owner, session) 7 索引开销,还把跨分片短语搜索切碎了。
    • agent_recall_messages 存在逐字节重复索引,且其他表也有 (owner, session) 膨胀:
      • 0011_usage_recall.sql 在表级 UNIQUE(owner,session,sequence,ordinal)(sqlite_autoindex_agent_recall_messages_1,212.8 MiB)之外又建了列完全一致的 agent_recall_message_order(212.8 MiB),仅仅是为了让 positions.rs 能写 INDEXED BY。改成具名 UNIQUE INDEX 即可直接省下 212.8 MiB。
      • agent_usage_calls(总计 297 MiB,其中索引 168 MiB)同样在多个索引里重复存储长文本 (owner, session),引入会话代理键时建议一并覆盖。

    2. contents 侧:zstd-3 实测对比(方向 4 的压缩率上限校准)

    在当前 main(11-22 ~ 11-25)上,#7102 已把 promptChunks 的增长从 101–320 KiB/step(128 KiB 块)降到 39–49 KiB/step(32 KiB 块),#7115 也已完成 composition.surface 去重(2.19 万步合计仅 29 MiB)。目前最大的实时新写入源是 cell(4 天 535 MiB)、external_effect(4 天 449 MiB)、agent_facts 信封(4 天 250 MiB)和 step_prepared(4 天 228 MiB)。

    其中 external_effect(全库 807 MiB;11-22 ~ 11-25 449 MiB)的每条输出 JSON 内部同时存放 output(33.7%)与 projection(32.2%),调用记录里重复携带完整的工具 definition(28.0%,全库 257 MiB);cell 的返回信封同样并存 output 与 projection;provenance.toolContracts 仍占 11-24 ~ 11-25 provenance 的 80.5%(约 4.6 KiB/步)。

    在 11-22 ~ 11-25 连续 50,000 行 contents(106.71 MiB 原始字节) 上实测 zstd-3(使用从更早数据抽取的 48 KiB 字典,含 2 个工具定义 + 1 份 toolContracts + 31 KiB fact 信封):

    模式 体积 压缩后占比 说明
    原始未压缩 106.71 MiB 100.0% (1.00×) 当前
    逐行 zstd-3(无字典) 44.47 MiB 41.7% (2.40×) 全库 1/100 抽样为 37.7% (2.65×)
    逐行 zstd-3 + 48 KiB 字典 34.00 MiB 31.9% (3.14×) tool_call(definition) 41.6% → 9.2%;agent_facts 69.6% → 42.5%;step_meta 46.1% → 27.6%
    按类别各自流式 zstd-3 求和 19.21 MiB 18.0% (5.55×) —
    整体连续流式 zstd-3 10.01 MiB 9.4% (10.66×) 复现原 issue 的 544 → 52 MB (9.6%)

    对方向 4 的两点参考:

    1. 静态字典对重复 schema 和小行非常有效:相比无字典逐行 zstd,工具 definition 体积再降 4.5×,agent_facts 小信封再降 ~40%。
    2. 逐行 zstd + 静态字典的合理预期是 ~3.1–3.5×(减 ~70%),达不到流式压缩的 ~10×。「按类流式求和 18.0%」与「混合连续流式 9.4%」之间近一倍的差距,说明另一半跨行冗余来自同一会话内的动态工具输出在 application_operations.outcome → cell ChildResultRecorded → cell.completed → external_effect → promptChunks 间的多次复写,这是静态字典无法消除的;另外 GPT/Responses 场景下 71% 的 32 KiB promptChunks 含有高熵 encrypted_content(均熵 5.35 bits/B),块本身压缩率在 ~39–51% 封顶。工程上逐行 zstd + 训练字典已经能用很低的实现复杂度把 contents 砍掉 ~70%,只是规划目标比例时不要按 10× 估算。

    3. 长生命周期升级库的历史包袱(供原地迁移参考)

    • recoveredCells 三重拷贝(11-10 ~ 11-14 约 1.48 GiB):每步 step_prepared 会把不断增长的 recoveredCells 数组完整写进 provenance(~508 MiB)、request(~503 MiB)和 projection(~469 MiB)三处。11-15 之后均值降到 ~11 KiB/步,但实际触发 recovery 时单步仍可达 150 KiB × 3。
    • 旧迁移残留的 ~1,018 MiB(16,488 行)未释放 request blob:此前迁移将 RequestSpec.request 从 system/instructions 改写为 systemText/instructionsText 时写入了新的 contents 行,但 model_attempt_admitted 仍引用并 pin 着迁移前的旧 blob(agent_content_pins / agent_history_content_refs)。后续做 contents 原地迁移时值得注意审计所有引用与 pin 路径。
  3. M4n5ter commented on Nov 25, 2026

    @M4n5ter
    Member
    English

    Followed up with a code-level audit against 4d498edd3e to check what could actually break when implementing Directions 1–4 (and to check if we missed any hidden traps on a 20+ GiB live DB). Summarizing the concrete gotchas and a suggested order of changes:

    1. Recall: body is not just a disposable cache — Memory depends on its byte offsets

    • evidence.rs opens agent_recall_messages.body directly via blob_open, and 0055_external_effect_ended_unknown.sql relies on references_json[$n] and fields_json positions (e.g. field.key = 1 to locate child_result_recorded results) to propagate redaction/suppression spans across sibling tool outputs.
    • What breaks if we just strip fields/rows: old evidence offsets shift, and worse, redacted text can leak back into search through a sibling tool output. Any Recall cleanup needs to update those Memory views/triggers together (and test with a retracted span + sibling output).
    • A few edge cases when trimming Recall:
      • Don't lump Started (JS code) and ChildPrepared (tool inputs) in with pure bookkeeping like vm_bound/child_bound — strip their JSON receipt wrapper, keep the actual code/args searchable.
      • Don't blindly drop cell.completed or external_effect outputs just because child calls exist — cell_final() can transform/summarize child outputs or run with zero children. Only deduplicate when provenance and visibility provably match.
      • When coalescing OutputDelta / ThinkingDelta, don't UPDATE and re-gram on every 72 B chunk (that turns linear rows into O(n²) write amp). Index once at message end using MessageStart/MessageEnd + message_id, and read live/interrupted tails from persisted fragments. Note session_catalog/index.rs also inserts one preview row per visible delta.
      • Dropping folded is still worth doing, just note that recall/query.rs runs LIMIT 128 inside a loop (128 per batch, not per query) — worth benchmarking p95 on common single-char / CJK queries rather than just first-page latency.

    2. Schema & index catches

    • One more exact duplicate index: agent_run_specs_history and agent_recall_scope_runs are both (owner, session, run).
    • Don't drop agent_session_history_session(owner, session): checked EXPLAIN QUERY PLAN — because sequence is the rowid, WHERE owner=? AND session=? AND sequence<? ORDER BY sequence DESC LIMIT 1 uses it as a covering range seek; dropping it falls back to USE TEMP B-TREE FOR ORDER BY. The actual merge candidate on agent_session_history is _run_fk(run) + _run(owner,session,run,step,kind) → (run, step, kind).
    • Defer agent_usage_calls from the first surrogate-key pass: its owner is nullable (standalone cells) and it has cross-session global time queries, so it needs separate care rather than cramming into the history/recall namespace migration.

    3. contents compression & live code-level duplication

    • The hard part of Direction 4 isn't zstd — it's direct byte access: besides 11 views + 1 trigger reading contents.payload, multiple paths assume raw bytes: length(payload) == ContentRef.bytes, streaming zeroblob + blob_open writes (content/stream.rs), and blob_open range reads (artifacts/read.rs, session_history/sql.rs). A SQLite UDF won't cover those, and we shouldn't decompress a multi-MB artifact just to read its tail.
    • Cleaner first step: add an explicit encoding flag (raw | zstd-v1) + logical byte length column, keep large/streamed artifacts raw, and start with plain per-row zstd (no dictionary). That already captures ~58–62% compression without dictionary versioning or risking private user data in a shipped dict; a static versioned dict can be a later codec if still needed (avoid per-DB dynamic dicts).
    • Two live code-level issues still on main:
      • driver_model.rs still copies both recovered_cells and notifications verbatim into all three of FrozenInput, projection, and provenance. It only looked quiet after Nov 15 because recovery wasn't triggered often; long recovered runs will still balloon 3× per step.
      • cells/sql.rs re-serializes and upserts the entire growing CellView (all children) on every cell event — live table size is O(n) (228 MiB), but cumulative WAL/CPU write amp on cells with many children is O(n²).
    • (Correction on the ~1 GiB pre-migration request blobs from my previous comment: cleanup_driver.rs / original_reader may still reference old request digests semantically, so those shouldn't be batch-unpinned by date without tracing the full reference graph.)

    4. Upgrading 20+ GiB live DBs without blowing up disk

    • Single outer SAVEPOINT: migration.rs wraps all pending migrations in one SAVEPOINT maka_schema_migrations. Rebuilding history + recall + recompressing 10 GiB of contents inside one migration will hold the entire WAL open with zero mid-way checkpoints, easily spiking peak disk to 2–3× DB size.
      • Because raw and zstd-v1 can both be valid encodings under the new schema, the schema switch can be atomic while existing contents rows are re-encoded incrementally in bounded batches afterwards.
    • Multi-hop upgrade hazard: migration 0055 (lib.rs) runs a Rust data hook that rebuilds Recall. If later PRs change Recall's INSERT SQL (e.g. dropping folded or switching to namespace_id), upgrading from a DB older than v55 will hit 0055 first and fail unless 0055 stays schema-compatible.
    • Good news on vacuum: Rust-created runtime-rust.sqlite already uses auto_vacuum = INCREMENTAL and material.rs runs PRAGMA incremental_vacuum(128) (confirmed in the live DB header), so it doesn't need a full-DB VACUUM like #6000.

    5. Practical rollout order

    1. Quick zero-risk win: remove the INDEXED BY hint in positions.rs:37 and drop the two exact duplicate indexes (agent_recall_message_order, agent_recall_scope_runs) — immediate ~213 MiB win on this DB.
    2. Drop folded (with CJK / single-char p95 benchmarks).
    3. One combined derived rebuild: Recall semantic dedup (with Memory's offset/redaction contract updated) + namespace_id surrogate keys for history & recall.
    4. contents raw | zstd-v1 + logical byte length + incremental batch re-encoding of old rows.
    5. Structural dedup (FromOutput-style sharing for StoredCellReturn::Inline / ExternalReturn::Output, shared refs for definition / toolContracts / recoveredCells), then re-evaluate whether a static zstd dict is still needed.

    (Rough sizing check: Steps 1–4 should take this 21.5 GiB DB down to ~10–12 GiB and cut 4-day steady growth from 6.4 GiB to ~3–4 GiB. Getting all the way to the 3–5× goal on heavy Code Mode / external-agent workloads likely requires Step 5 as well.)

    中文

    又顺着 4d498edd3e 的源码把四个方向逐个核了一遍,主要看落地时真正会踩哪些坑(尤其在 20+ GiB 的现网大库上)。整理成几条直白的注意事项和推进顺序:

    1. Recall 的 body 不只是搜索缓存——Memory 把它当成了字节坐标

    • evidence.rs 直接对 agent_recall_messages.body 做 blob_open,而 0055_external_effect_ended_unknown.sql 依赖 references_json[$n] 和 fields_json 的字段序号(例如按 field.key = 1 定位 child_result_recorded 的 result)来把撤回/遮罩区间传播给关联的工具输出。
    • 直接删字段/删行会出什么事:旧证据的字节偏移全会错位,更严重的是已经撤回/隐藏的内容可能从另一份关联工具输出里重新被搜出来。所以改 Recall 时必须把 Memory 的这批视图和触发器一起改,并补一个“撤回字段 + 关联输出”的回归测试。
    • 另外几个 Recall 细节:
      • Started(cell 的 JS 代码)和 ChildPrepared(工具入参)里有真实可搜内容,别跟 vm_bound/child_bound 一起一刀切扔掉——去掉外层 JSON 回执壳、保留正文即可。
      • cell.completed 和 external_effect 的输出不一定和子调用完全等价(cell 可能做过汇总/变换,或者根本没调子工具),只有在能确认同源且可见性一致时才去重。
      • 合并外部 agent 的 OutputDelta / ThinkingDelta 时,千万别每来 72 B 就 UPDATE 整条记录并重算 FTS grams(会把线性行数变成 O(n²) 写放大)。可以用已有的 MessageStart/MessageEnd + message_id 在消息结束时一次建索引,未结束/中断的尾部直接读持久化分片。另外 session_catalog/index.rs 也在给每条可见 delta 写一行 preview,要留意。
      • 删 folded 依然值得做,但 recall/query.rs 的 LIMIT 128 是在 loop 里每批 128,不是每次查询最多 128——删之前记得拿高频单字、中文短词和大工具输出测一下 p95,别只看第一页延迟。

    2. Schema 和索引的几个坑

    • 又找到一对 100% 重复的索引:agent_run_specs_history 和 agent_recall_scope_runs 都是 (owner, session, run)。
    • agent_session_history_session(owner, session) 不能随便删:实测 EXPLAIN QUERY PLAN,因为 sequence 是 rowid,WHERE owner=? AND session=? AND sequence<? ORDER BY sequence DESC LIMIT 1 靠它走 covering range seek;删了会退化成 USE TEMP B-TREE FOR ORDER BY。这张表上真正值得合并的是 _run_fk(run) + _run(owner,session,run,step,kind) → (run, step, kind)。
    • 第一批改代理键先别硬塞 agent_usage_calls:它的 owner 允许为 NULL(standalone cell),还有跨会话的全局时间查询,放第二批单独处理更稳。

    3. contents 压缩与仍在 main 上的代码级重复

    • 方向 4 真正麻烦的不是 zstd,而是直接按字节读写的接口:除了 11 个视图 + 1 个触发器读 contents.payload 外,还有好几处代码直接假设 payload 是原始字节:length(payload) == ContentRef.bytes、流式 zeroblob + blob_open 写入(content/stream.rs)、以及 blob_open 分段读取(artifacts/read.rs、session_history/sql.rs)。光注册一个 SQLite 解码 UDF 盖不住这些路径,也不可能为了读几十 MiB artifact 的最后 4 KiB 去整块解压。
    • 更稳妥的起步方案:加显式编码标记(raw | zstd-v1)和逻辑长度列,大文件/流式 artifact 保持 raw,先上无字典逐行 zstd。这一步就能吃掉 ~58–62% 的体积,且完全避开字典版本管理和私有数据编进内置字典的风险;真有需要后面再加静态版本化字典(别搞每库动态字典)。
    • main 上仍有两处代码级重复/写放大:
      • driver_model.rs 现在依然会把 recovered_cells 和 notifications 原样拷贝进 FrozenInput、projection、provenance 三个 blob。11-15 之后看起来安静只是因为没频繁触发 recovery,长会话一旦触发还是每步 3 份。
      • cells/sql.rs 每次 cell event 都会把不断变大的整棵 CellView(含全部 children)重新序列化 upsert——活表看起来是线性的(228 MiB),但子调用多的 cell 累计 WAL 和 CPU 是 O(n²) 写放大。
    • (顺带更正上一条评论里关于 ~1 GiB 旧 request blob 的推测:cleanup_driver.rs / original_reader 语义上仍可能核对原 request,不能按迁移日期批量 unpin,必须按完整引用图核查。)

    4. 20+ GiB 现网库升级时的磁盘炸弹

    • 外层单 SAVEPOINT:migration.rs 把所有待执行迁移包在同一个 SAVEPOINT maka_schema_migrations 里。如果在一个迁移事务里同时重建 history + recall + 重压 10 GiB contents,整个过程无法中途 checkpoint WAL,磁盘峰值会直接冲到原库的 2–3 倍。
      • 好在 raw 和 zstd-v1 在新 schema 下本来就都是合法格式:可以只把 schema 切换做原子迁移,老数据的重压缩放到之后按字节预算分批执行。
    • 跨级升级暗雷:0055 迁移(lib.rs)的 Rust data hook 会调 Recall 重建。如果后续 PR 改了 Recall 的写入列(比如删了 folded 或换成 namespace_id),老库从 < 55 跨级升级会在跑到 0055 时先炸掉,必须留意向前兼容。
    • 好消息:Rust 建出来的 runtime-rust.sqlite 默认就已经开了 auto_vacuum = INCREMENTAL,material.rs 也已经在跑 PRAGMA incremental_vacuum(128)(已核对主库文件头),不需要像 #6000 那样卡一次全库 VACUUM。

    5. 建议的落地顺序

    1. 最小零风险 PR:去掉 positions.rs:37 的 INDEXED BY,删掉两对完全重复的索引(agent_recall_message_order、agent_recall_scope_runs)——这台机器上立省 ~213 MiB。
    2. 删 folded(补高频单字/中文 p95 压测)。
    3. 合并成一次派生表重建:Recall 语义去重(同步更新 Memory 偏移/撤回契约)+ history/recall 换 namespace_id 代理键。
    4. contents 上 raw | zstd-v1 + 逻辑长度列 + 老行分批重压缩。
    5. 结构去重(给 StoredCellReturn::Inline / ExternalReturn::Output 补齐类似 FromOutput 的同源引用,definition / toolContracts / recoveredCells 改共享引用),做完再决定是否还要加静态 zstd 字典。

    (现实预期:做完 1–4 步,21.5 GiB 老库大概能压到 ~10–12 GiB,4 天稳态增量从 6.4 GiB 降到 ~3–4 GiB;要在重度 Code Mode + 外部 agent 负载下压进目标 3–5×,第 5 步大概率绕不过去。)

  4. YongGoose commented on Nov 25, 2026

    @YongGoose
    Member

    I'd like to take step 1 of the rollout above: drop agent_recall_message_order and agent_recall_scope_runs in a new migration and remove the INDEXED BY hint in positions.rs, checking the plan with EXPLAIN QUERY PLAN and covering the upgrade in upgrade_compat.rs. I'll leave the other steps open unless you'd like me to continue with folded next.

  5. M4n5ter commented on Nov 25, 2026

    @M4n5ter
    Member

    Thanks @YongGoose! I'm planning to build out the full sequence as a stacked PR chain (Step 1 → Step 5) so we can benchmark and verify every step end-to-end against this 21.5 GiB real-world DB without migration-number collisions across PRs.\n\nIf you haven't started Step 1 yet, I'll include it as the base PR of the stack — and your review on the stack (especially around SQLite migration/WAL behavior) would be super welcome! If you've already got a branch going for Step 1, let me know and I'll happily rebase the rest of the stack on top of yours.

  6. YongGoose commented on Nov 25, 2026

    @YongGoose
    Member

    I haven't started, so please take Step 1 as the base of your stack. I'm glad to review the chain, especially the migration and WAL side: how long the outer SAVEPOINT keeps the WAL from checkpointing during the rebuilds, and how batched re-encoding of contents interacts with #7212. Please tag me when the first PR is up.

  7. added 9 commits that reference this issue on Nov 26, 2026
    7fe7333
    f15860e
    3e44d0f
    40b15ac
    2f14a35
    c451733
    67c5436
    4b1c84c
    f87a8ad
  8. UncertaintyDeterminesYou4ndMe commented on Nov 27, 2026

    @UncertaintyDeterminesYou4ndMe
    Contributor

    Posted by Claude Opus 5.5 (AI).

    A growth data point from the same desktop trial root as my earlier comment on #7318, about scheduled work rather than the per-session multiplier.

    Every Proactive discovery check creates its own worker session (id from sha256(fire.id), plugins/agent/native/src/owner/discovery.rs:~660; created in enqueue_discovery_worker, :918). On this root, in 4 days:

    Checks Sessions Content pinned only by these runs
    8 completed (7 discovery checks, 1 other scheduled task) 8 17.8 MiB (about 2.2 MiB each)
    10 failed at the first request 10 1.2 MiB (about 120 KiB each)

    I found nothing that removes these sessions or their runs: no retention or pruning for discovery or scheduled-task sessions, and Plan::settle_inner keeps every run in task.runs (insert(0, run), plugins/agent/scheduler/engine/src/plan.rs:346) with no cap. The only removal is the person removing a session. At one completed check a day that is roughly 0.8 GiB a year for one plan, before any change from the #7318 stack.

    (The 10 failures are #7350.)

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions