Repository navigation
Description
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:
- Recall indexes cell lifecycle receipts and indexes cell output twice.
Rule::Cellinrecall/index.rsturns everyCellEventinto a searchabletool_resultmessage. Its serialized JSON is stored as a non-internalReceiptfield.- Bookkeeping events such as
started,vm_bound,child_prepared,child_display_recorded,child_admitted,child_boundandloaded_tools_publishedeach become a message. Their text consists of UUIDs, digests and deployment references: about 15 MB. ChildObservedinlines the whole operation reply, including the tool output, as escaped JSON.ChildResultRecordedfor the same operation then indexes the same output again as plain text: about 34 MB. For example, the stdout of oneShellcall 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
foldedand in the gram index.
- Bookkeeping events such as
- Recall stores every body twice.
agent_recall_messages.bodyandfoldedare 175 MB each.foldedcachesfold(&body), whichrecall/query.rsalready recomputes on another path, and a query page checks at most 128 candidates. - Long text keys repeat in every row and index. Every
agent_session_historyrow storesowner(a 106-byte JSON string) andsession(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. contentsis 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
systemPromptandtools: 31 MB over 1,086 steps, next totoolCatalogDigest; - every tool operation carries the full tool
definition: 33 MB over 3,871 calls; - every external-agent prompt carries the full
systemandinstructions: 51 MB over 1,085 rows.
- every request composition carries the full
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
- 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 inlinedChildObservedreply. If some receipt fields must stay searchable, such as a shell command line, index those fields alone. - Drop
agent_recall_messages.foldedand fold the candidates at query time. - Replace the
(owner, session)text keys in derived history and recall tables and indexes with an integer surrogate. - Compress
contentsat the storage layer, for example with zstd and a trained dictionary. Digests stay computed over the uncompressed bytes, so everyContentRefand cross-record reference stays valid, and only the encoding is migrated in place. SQL views thatjson_extractfrompayloadread 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
VACUUMdoes 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
contentsrecords 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_messagesno longer storesfolded, and existing recall search and ranking tests still pass. - Derived history and recall tables key sessions by an integer surrogate instead of repeated
owner/sessiontext. -
contentspayloads are stored compressed. Digests,ContentRefs and SQL views keep working unchanged. - Existing databases upgrade in place.
upgrade_compat.rscovers 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 | 混合 |
四个原因,按"是缺陷"的明确程度排序:
- 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 索引里再存一次。
- Recall 的每条正文存了两份。
agent_recall_messages的body和folded各 175 MB。folded只是缓存了fold(&body),而recall/query.rs在另一条路径上本来就会现算;每页查询最多也只核对 128 个候选。 - 长文本键在每行、每个索引里重复。
agent_session_history每行都存owner(106 字节的 JSON 字符串)和session(100 字节),7 个索引都以(owner, session)开头,结果 12.5 万行占了 183 MB,平均每行约 1.5 KB。recall 的唯一索引和排序索引也是同样的情况。 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 仍能搜到同样的对话,已有数据库原地升级,不丢任何状态。
方向
- Recall 每次工具调用只收录一次。 不再收录生命周期回执;cell 子调用的输出只从已落定的结果(
ChildResultRecorded/LocalChildReturned)收录,不再从内联的ChildObserved回复收录。如果回执里个别字段(例如 shell 命令行)需要能被搜到,只收录这些字段。 - 删掉
agent_recall_messages.folded,查询时对候选现算。 - 派生的 history 和 recall 表及索引改用整数代理键,替代
(owner, session)长文本键。 - 在存储层压缩
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
M4n5ter commentedon Nov 25, 2026
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(RequestCompositiondedup), splitting full-DB vs. post-#7102/#7115steady-state growth (Nov 22–25) also surfaces a few additional defects and an empirical check on Direction 4.Dataset &
dbstatbreakdown21,971 MiB,page_size=4096,freelist_count=31) — 285 active sessions, 2,196 runs, 1.30M facts, 939k recall rows, 2.03Mcontentsrows.#7102/#7115steady-state (Nov 22–25, 4 days, currentmain): 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×.contents(authoritative)agent_recall_*, derived)messagestable 5,090 + 7 indexes 1,287 +termsFTS 1,033agent_session_history(derived)agent_facts352,agent_usage_calls/results392,application_intents231,agent_cells228,agent_content_pins220,application_operations164Additional findings beyond the 4 causes listed
1. Recall: three more amplification sources alongside
CellEventreceipts /ChildObservedThe issue's observations hold at 10× scale (
body=folded= 2,057 MiB each;cell= 72.5% of recallbody;child_observed377 MiB duplicateschild_result_recorded333 MiB; pure cell bookkeeping receipts withoutstarted/child_preparedare 355k rows / 37.8% of all rows, or 483k / 51.4% including them). In addition:recall/index.rsindexesLocalToolReturned(116 MiB, 19.3k rows) andHostToolResultRecorded(5.4 MiB, 685 rows) viaRule::Returned, and then indexes the exact sameToolReturnagain viaRule::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.execquad-indexing & streaming-delta row explosion:exec, the same output is indexed acrosschild_observed→child_result_recorded→cell.completed(347 MiB) →external_effecttool_result(220 MiB). (E.g. an 11.57 MiB output appears verbatim in bothcell.completedand the immediately followingexternal_effect.)Rule::Externalturns everyOutputDelta/ThinkingDeltainto a standalone recall row:external_task_observedcontributes 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.agent_recall_messages+ other(owner, session)tables:0011_usage_recall.sqldefinesCREATE INDEX agent_recall_message_order ON agent_recall_messages(owner,session,sequence,ordinal)(212.8 MiB) on top ofUNIQUE(owner,session,sequence,ordinal)(sqlite_autoindex_agent_recall_messages_1, 212.8 MiB), solely sopositions.rscan useINDEXED BY. Replacing the table-levelUNIQUEconstraint with a namedUNIQUE INDEXeliminates 212.8 MiB immediately.agent_usage_calls(297 MiB total; 168 MiB in indexes) repeats(owner, session)across multiple indexes the same wayagent_session_historyandagent_recall_messagesdo — worth including if surrogate session keys are introduced.2.
contents: empiricalzstd-3benchmark (Direction 4 reality check)On current
main(Nov 22–25),#7102already reducedpromptChunksgrowth from101–320 KiB/step(128 KiB chunks) to39–49 KiB/step(32 KiB chunks), and#7115deduplicatedcomposition.surface(only 29 MiB across 21.9k steps). Today's largest newcontentswriters arecell(535 MiB / 4d),external_effect(449 MiB / 4d),agent_factsenvelopes (250 MiB / 4d), andstep_prepared(228 MiB / 4d).Inside
external_effect(807 MiB full DB; 449 MiB Nov 22–25), every output blob stores bothoutput(33.7%) andprojection(32.2%) inside the same JSON object alongside repeated tooldefinitions (28.0%, 257 MiB full DB).cellresult envelopes similarly store bothoutputandprojection, andprovenance.toolContractsstill accounts for 80.5% (~4.6 KiB/step) of Nov 24–25provenance.Benchmarking
zstd-3on a contiguous 50,000-row slice from Nov 22–25 (106.71 MiBraw), using a disjoint 48 KiB raw dictionary (2 tool defs + 1toolContracts+ 31 KiB fact envelopes from earlier rows):zstd-3(no dict)zstd-3+ 48 KiB dicttool_call(definition)41.6% → 9.2%;agent_facts69.6% → 42.5%;step_meta46.1% → 27.6%zstd-3streamszstd-3streamTwo takeaways for Direction 4:
tool_calldefinitions by 4.5× and smallagent_factsenvelopes by ~40% vs. plain per-row zstd.application_operations.outcome→cellChildResultRecorded→cell.completed→external_effect→promptChunks, which a static dictionary cannot match. Additionally, on GPT/Responses workloads, 71% of 32 KiBpromptChunkscontain high-entropyencrypted_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:
recoveredCellstriplication (~1.48 GiB in Nov 10–14): everystep_preparedcopies the full growingrecoveredCellsarray into all three ofprovenance(~508 MiB),request(~503 MiB), andprojection(~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.requestblobs still pinned: when a previous migration rewroteRequestSpec.request(system/instructions→systemText/instructionsText) into newcontentsrows,model_attempt_admittedfacts kept referencing/pinning the old pre-migrationrequestblobs inagent_content_pins/agent_history_content_refs. Worth auditing all pin/referrer paths whenever a migration rewritescontentspayloads.中文
补充一份体量更大(约原 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分布21,971 MiB,page_size=4096,freelist_count=31)—— 285 个活跃会话、2,196 次 run、130 万条 fact、93.9 万条 recall 消息、202.7 万行contents。#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×。contents(权威)agent_recall_*,派生)messages表 5,090 + 7 个索引 1,287 +termsFTS 1,033agent_session_history(派生)agent_facts352、agent_usage_calls/results392、application_intents231、agent_cells228、agent_content_pins220、application_operations164原 issue 4 条原因之外的新发现
1. Recall 侧:除
CellEvent回执 /ChildObserved外还有三处冗余原 issue 指出的问题在 10 倍体量下完全成立(
body和folded各占 2,057 MiB;cell占 recall 正文的 72.5%,child_observed377 MiB 与child_result_recorded333 MiB 重复;不含started/child_prepared的纯簿记回执就占 35.5 万行 / 37.8%,含两者占 48.3 万行 / 51.4%)。此外:recall/index.rs中Rule::Returned(local_tool_returned116 MiB / 1.93 万行、host_tool_result_recorded5.4 MiB / 685 行)与Rule::Accepted(tool_result_accepted123.3 MiB / 2.00 万行)各自读取同一份ToolReturn建索引。实测 19,302 对(local_tool_returned, tool_result_accepted)中有 13,593 对body逐字节完全一致,其余仅差约 115 B 的封装。exec的四重索引 + 流式 delta 行数爆炸:exec时,同一份输出会依次进入child_observed→child_result_recorded→cell.completed(347 MiB)→external_effecttool_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-25provenance的 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 信封):zstd-3(无字典)zstd-3+ 48 KiB 字典tool_call(definition)41.6% → 9.2%;agent_facts69.6% → 42.5%;step_meta46.1% → 27.6%zstd-3求和zstd-3对方向 4 的两点参考:
definition体积再降 4.5×,agent_facts小信封再降 ~40%。application_operations.outcome→cellChildResultRecorded→cell.completed→external_effect→promptChunks间的多次复写,这是静态字典无法消除的;另外 GPT/Responses 场景下 71% 的 32 KiBpromptChunks含有高熵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。requestblob:此前迁移将RequestSpec.request从system/instructions改写为systemText/instructionsText时写入了新的contents行,但model_attempt_admitted仍引用并 pin 着迁移前的旧 blob(agent_content_pins/agent_history_content_refs)。后续做contents原地迁移时值得注意审计所有引用与 pin 路径。M4n5ter commentedon Nov 25, 2026
English
Followed up with a code-level audit against
4d498edd3eto 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:
bodyis not just a disposable cache — Memory depends on its byte offsetsevidence.rsopensagent_recall_messages.bodydirectly viablob_open, and0055_external_effect_ended_unknown.sqlrelies onreferences_json[$n]andfields_jsonpositions (e.g.field.key = 1to locatechild_result_recordedresults) to propagate redaction/suppression spans across sibling tool outputs.Started(JS code) andChildPrepared(tool inputs) in with pure bookkeeping likevm_bound/child_bound— strip their JSON receipt wrapper, keep the actual code/args searchable.cell.completedorexternal_effectoutputs 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.OutputDelta/ThinkingDelta, don'tUPDATEand re-gram on every 72 B chunk (that turns linear rows into O(n²) write amp). Index once at message end usingMessageStart/MessageEnd+message_id, and read live/interrupted tails from persisted fragments. Notesession_catalog/index.rsalso inserts one preview row per visible delta.foldedis still worth doing, just note thatrecall/query.rsrunsLIMIT 128inside 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
agent_run_specs_historyandagent_recall_scope_runsare both(owner, session, run).agent_session_history_session(owner, session): checkedEXPLAIN QUERY PLAN— becausesequenceis the rowid,WHERE owner=? AND session=? AND sequence<? ORDER BY sequence DESC LIMIT 1uses it as a covering range seek; dropping it falls back toUSE TEMP B-TREE FOR ORDER BY. The actual merge candidate onagent_session_historyis_run_fk(run)+_run(owner,session,run,step,kind)→(run, step, kind).agent_usage_callsfrom the first surrogate-key pass: itsowneris 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.
contentscompression & live code-level duplicationcontents.payload, multiple paths assume raw bytes:length(payload) == ContentRef.bytes, streamingzeroblob+blob_openwrites (content/stream.rs), andblob_openrange 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.raw | zstd-v1) + logical byte length column, keep large/streamed artifactsraw, 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).main:driver_model.rsstill copies bothrecovered_cellsandnotificationsverbatim into all three ofFrozenInput,projection, andprovenance. It only looked quiet after Nov 15 because recovery wasn't triggered often; long recovered runs will still balloon 3× per step.cells/sql.rsre-serializes and upserts the entire growingCellView(allchildren) 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²).requestblobs from my previous comment:cleanup_driver.rs/original_readermay 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
SAVEPOINT:migration.rswraps all pending migrations in oneSAVEPOINT maka_schema_migrations. Rebuilding history + recall + recompressing 10 GiB ofcontentsinside one migration will hold the entire WAL open with zero mid-way checkpoints, easily spiking peak disk to 2–3× DB size.rawandzstd-v1can both be valid encodings under the new schema, the schema switch can be atomic while existingcontentsrows are re-encoded incrementally in bounded batches afterwards.0055(lib.rs) runs a Rust data hook that rebuilds Recall. If later PRs change Recall'sINSERTSQL (e.g. droppingfoldedor switching tonamespace_id), upgrading from a DB older than v55 will hit0055first and fail unless0055stays schema-compatible.runtime-rust.sqlitealready usesauto_vacuum = INCREMENTALandmaterial.rsrunsPRAGMA incremental_vacuum(128)(confirmed in the live DB header), so it doesn't need a full-DBVACUUMlike#6000.5. Practical rollout order
INDEXED BYhint inpositions.rs:37and drop the two exact duplicate indexes (agent_recall_message_order,agent_recall_scope_runs) — immediate ~213 MiB win on this DB.folded(with CJK / single-char p95 benchmarks).namespace_idsurrogate keys for history & recall.contentsraw | zstd-v1+ logical byte length + incremental batch re-encoding of old rows.FromOutput-style sharing forStoredCellReturn::Inline/ExternalReturn::Output, shared refs fordefinition/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)来把撤回/遮罩区间传播给关联的工具输出。Started(cell 的 JS 代码)和ChildPrepared(工具入参)里有真实可搜内容,别跟vm_bound/child_bound一起一刀切扔掉——去掉外层 JSON 回执壳、保留正文即可。cell.completed和external_effect的输出不一定和子调用完全等价(cell 可能做过汇总/变换,或者根本没调子工具),只有在能确认同源且可见性一致时才去重。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 和索引的几个坑
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上的代码级重复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²) 写放大。requestblob 的推测:cleanup_driver.rs/original_reader语义上仍可能核对原 request,不能按迁移日期批量 unpin,必须按完整引用图核查。)4. 20+ GiB 现网库升级时的磁盘炸弹
SAVEPOINT:migration.rs把所有待执行迁移包在同一个SAVEPOINT maka_schema_migrations里。如果在一个迁移事务里同时重建 history + recall + 重压 10 GiBcontents,整个过程无法中途 checkpoint WAL,磁盘峰值会直接冲到原库的 2–3 倍。raw和zstd-v1在新 schema 下本来就都是合法格式:可以只把 schema 切换做原子迁移,老数据的重压缩放到之后按字节预算分批执行。0055迁移(lib.rs)的 Rust data hook 会调 Recall 重建。如果后续 PR 改了 Recall 的写入列(比如删了folded或换成namespace_id),老库从< 55跨级升级会在跑到0055时先炸掉,必须留意向前兼容。runtime-rust.sqlite默认就已经开了auto_vacuum = INCREMENTAL,material.rs也已经在跑PRAGMA incremental_vacuum(128)(已核对主库文件头),不需要像#6000那样卡一次全库VACUUM。5. 建议的落地顺序
positions.rs:37的INDEXED BY,删掉两对完全重复的索引(agent_recall_message_order、agent_recall_scope_runs)——这台机器上立省 ~213 MiB。folded(补高频单字/中文 p95 压测)。namespace_id代理键。contents上raw | zstd-v1+ 逻辑长度列 + 老行分批重压缩。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 步大概率绕不过去。)
YongGoose commentedon Nov 25, 2026
I'd like to take step 1 of the rollout above: drop
agent_recall_message_orderandagent_recall_scope_runsin a new migration and remove theINDEXED BYhint inpositions.rs, checking the plan withEXPLAIN QUERY PLANand covering the upgrade inupgrade_compat.rs. I'll leave the other steps open unless you'd like me to continue withfoldednext.M4n5ter commentedon Nov 25, 2026
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.
YongGoose commentedon Nov 25, 2026
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
SAVEPOINTkeeps the WAL from checkpointing during the rebuilds, and how batched re-encoding ofcontentsinteracts with #7212. Please tag me when the first PR is up.perf(agent): deduplicate step metadata, tool contracts, external desc…
perf(agent): deduplicate step metadata, tool contracts, external desc…
perf(agent): deduplicate step metadata, tool contracts, external desc…
perf(agent): deduplicate step metadata, tool contracts, external desc…
perf(agent): deduplicate step metadata, tool contracts, external desc…
perf(storage): compress application tables, agent_cells bodies, and i…
perf(storage): compress application tables, agent_cells bodies, and i…
perf(agent): externalize and deduplicate media in frozen prompts (Lay…
perf(agent): externalize and deduplicate media in frozen prompts (Lay…
UncertaintyDeterminesYou4ndMe commentedon Nov 27, 2026
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 inenqueue_discovery_worker, :918). On this root, in 4 days:I found nothing that removes these sessions or their runs: no retention or pruning for discovery or scheduled-task sessions, and
Plan::settle_innerkeeps every run intask.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.)
perf(agent): externalize and deduplicate media in frozen prompts (Lay…
perf(agent): externalize and deduplicate media in frozen prompts (Lay…
perf(agent): externalize and deduplicate media in frozen prompts (Lay…