Repository navigation
perf(agent): deduplicate step metadata, tool contracts, external descriptors, and return payloads - #7290
perf(agent): deduplicate step metadata, tool contracts, external descriptors, and return payloads#7290M4n5ter wants to merge 1 commit into
Conversation
c98f4db to
7fe7333
Compare
7fe7333 to
f15860e
Compare
f15860e to
3e44d0f
Compare
3e44d0f to
40b15ac
Compare
Astro-Han
left a comment
There was a problem hiding this comment.
English
Great work on StoredToolDefinition, out-of-line RequestSpec.toolContracts, removing notifications/recoveredCells duplication from projection/provenance, and keeping CellReplyState::Interrupted observations inline for cross-run wait and snapshot portability.
Issues to address
NativeExternalEffects::settleandread_returnreturnCellReply { observation: Value::Null }to callers (plugins/agent/native/src/owner/driver_external_effects.rs:1381-1460,836-877,1716-1740):- In
settle,reply.observationis mutated toserde_json::Value::Nullin place before serializingExternalReturn::Output, and then that same mutatedoutputis returned directly inOk(ReturnedToolResult { output, ... })toHostEffects::invokecallers. - Similarly,
read_returndeserializes the persistedExternalReturnand passesoutputstraight throughrender_returnwithout hydratingreply.observationfromCellReplyState::Completed { result }. - Fix: strip
observationonly on the persisted payload (keep/restore the originalobservationfor the return value insettle), and hydratereply.observationfromself.state.content(run, result.clone()).awaitinread_returnwhenreply.observation.is_null()on aCompletedcell.
- In
- Asymmetry on explicit
"observation": nullinToolResultFields::value()(plugins/agent/state/src/session_history/tool_result_source.rs:349-355):external_effects/sql.rs:289andsession_history/sql.rs:967checkreply.observation.is_null(), whereastool_result_source.rs:353checksif observation.is_some(). If a blob ever carries an explicit"observation": nullinstead of omitting the key, lazy reconstruction will be skipped. Changing the check toobservation.as_ref().is_some_and(|v| v.kind != JsonKind::Null)makes both sides consistent. - Minor cleanups:
driver_model.rs:960-964, 1027: in non-Code-Mode runs,tool_contractsis empty{}yet still writes atool_contracts_bloband pins it per run; settingtool_contracts: Nonewhen empty avoids unnecessary pins.ExternalEffectEvent::Prepared'sdefinition_refis currently pinned in bothsql.rs:1076-1085andexternal_effects/sql.rs:215-225, whereasReturned'sCellReplyState::Completed { result }is pinned only inexternal_effects/sql.rs:283-295; consolidating pin ownership in one layer will avoid ordering fragility later.
Further improvements to push steady-state down into 3–5×
Because intra-blob duplication is already ~90% compressed by #7289's zstd, #7290's 1.61 GiB raw reduction nets ~343 MiB post-zstd. Looking at my local 1.71 GiB DB (and post-Nov-22 steady-state writes), the biggest remaining wins that zstd alone cannot solve are:
- Extend
from_outputbeyond JSON toTextandCellprojections (plugins/agent/facts/src/tool_output/acceptance.rs:73-82): On my local DB, 97.8% (54.0 of 55.2 MiB) oftool_return(output + projection)blobs are('cell', 'text'), whereprojection.textalone accounts for 26.1 MiB of duplicated text alongside the cell output—andToolOutput::Text↔DurableToolProjection::Textisn't covered either. ExtendingStoredProjection::FromOutputto exact-matchTextoutputs and deterministically renderedCompletedcell projections eliminates the largest remaining text duplication incontents. - Address large uncompressed JSON tables outside
contents(223 MiB / 27% of post-stack steady-state on my DB; ~2.1 GiB / 22% on yours):agent_cells.body(22.8 MiB locally, uncompressed TEXT, plus O(n²) fullCellViewre-serialization on every cell event incells/sql.rs): normalizing children into a child table or storing snapshots compressed cuts both disk size and WAL write amplification.application_operation_contracts(10.7 MiB locally for only 31 rows of uncompressed JSON),application_intents.recovery_json(13.0 MiB), andapplication_operations.request_json(12.1 MiB): storing these viacontents(or compressing them) immediately captures both deduplication and #7289's zstd savings.
- Out-of-line static
system/instructionson external-agent prompts: Similar toRequestSpec.toolContracts, external-agent prompt records still embed full staticsystem+instructionsper step (49 MiB in my historical corpus); referencing them viaContentRefavoids repeating them across rows.
中文
StoredToolDefinition 互斥枚举、RequestSpec.toolContracts 外置、从 projection/provenance 去掉重复的 notifications/recoveredCells,以及在 CellReplyState::Interrupted 上保留内联 observation 以兼容跨 run wait 和快照迁移,这几处设计都很细致。
需要处理的问题
NativeExternalEffects::settle与read_return向调用方返回了CellReply { observation: Value::Null }(plugins/agent/native/src/owner/driver_external_effects.rs:1381-1460、836-877、1716-1740):settle在序列化ExternalReturn::Output之前原地把reply.observation置成了serde_json::Value::Null,随后直接把这同一个被改过的output放进Ok(ReturnedToolResult { output, ... })返回给了HostEffects::invoke调用方。- 同样,
read_return反序列化落盘的ExternalReturn后直接透传给render_return,没有按CellReplyState::Completed { result }还原reply.observation。 - 修复方式:
settle仅对持久化副本剥离observation(返回时保留/恢复原始observation),read_return在检测到Completedcell 且reply.observation.is_null()时从self.state.content(run, result.clone()).await还原。
ToolResultFields::value()对显式"observation": null判定不对称(plugins/agent/state/src/session_history/tool_result_source.rs:349-355):external_effects/sql.rs:289与session_history/sql.rs:967判的是reply.observation.is_null(),而tool_result_source.rs:353判的是if observation.is_some()。若记录里出现显式"observation": null而非省略键,会跳过懒重建。改成observation.as_ref().is_some_and(|v| v.kind != JsonKind::Null)即可对齐。- 两处小清理:
driver_model.rs:960-964, 1027:非 Code Mode 下tool_contracts是空{},目前仍写入tool_contracts_blob并按 run pin 一次,空时直接置tool_contracts: None更干净。ExternalEffectEvent::Prepared的definition_ref在sql.rs:1076-1085和external_effects/sql.rs:215-225各 pin 了一次,而Returned的CellReplyState::Completed { result }只在external_effects/sql.rs:283-295pin;统一收口到同一层能避免后续调整调用顺序踩坑。
进一步改进方向(把稳态压进 3–5×)
因为同 blob 内的重复已经被 #7289 的 zstd 提前压掉了约 90%,#7290 的 1.61 GiB 原始减量叠加 zstd 后净省约 343 MiB。结合我本地 1.71 GiB 库(以及 11-22 后的稳态写入),仅靠 zstd 解决不了的最大剩余收益在三处:
- 把
from_output从 JSON 扩展到Text和Cell投影(plugins/agent/facts/src/tool_output/acceptance.rs:73-82):我本地库里 55.2 MiB 的tool_return(output + projection)中 97.8%(54.0 MiB)是('cell', 'text'),光重复的projection.text就占 26.1 MiB,而ToolOutput::Text↔DurableToolProjection::Text目前也没覆盖。把StoredProjection::FromOutput扩展到完全相等的Text输出和确定性渲染的Completedcell 投影,能砍掉contents里剩余最大的文本双份拷贝。 - 收口
contents之外未压缩的大 JSON 表(我本地 223 MiB,占完栈后稳态的 27%;你那边约 2.1 GiB,占 22%):agent_cells.body(本地 22.8 MiB 明文 TEXT,且cells/sql.rs每次 cell event 都会把整棵CellViewO(n²) 重写):把 children 拆成子表或压缩存储,能同时压低磁盘体积和 WAL 写放大。application_operation_contracts(本地仅 31 行明文 JSON 就占 10.7 MiB)、application_intents.recovery_json(13.0 MiB)和application_operations.request_json(12.1 MiB):外置进contents或压缩存储,能立刻同时吃到去重和 #7289 zstd 红利。
- 外置外部 agent prompt 里的静态
system/instructions:和RequestSpec.toolContracts类似,外部 agent prompt 每步仍重复内联完整的system和instructions(我历史语料占 49 MiB),改成ContentRef外置即可跨行共享。
40b15ac to
2f14a35
Compare
2f14a35 to
76ad352
Compare
|
@Astro-Han Addressed all 3 correctness/cleanup items and landed all 3 further improvements directly in the stack (rebased onto #7289):
Across the full 7-PR stack (#7285–#7290 + #7318) on a 24.34 GiB offline CoW clone, existing historical storage drops from |
Astro-Han
left a comment
There was a problem hiding this comment.
English
Confirmed all 3 previous findings are fixed on 76ad3524cc (settle / read_return preserve CellReply.observation, ToolResultFields::value() handles explicit JsonKind::Null, empty tool_contracts blobs are omitted), and the ('text', 'text') / ('cell', 'text') FromOutput extensions plus instructions_ref pin/snapshot/import wiring are cleanly closed end-to-end.
Three smaller items to clean up before merging:
- Unbounded RAM read of
CellObservation.resultincompleted_cell_projection_json(plugins/agent/state/src/session_history/tool_result_source.rs:464-470, 999-1015):read_source_bytesaccumulates the entireresultJSON into aVec<u8>(thebudgetonly caps per-read 32 KiB chunks) and parses it into a fullserde_json::ValueDOM, bypassingSourceBudgeton large JSON cell results. Streaming JSON escaping or enforcingSourceBudgeton the accumulated size closes this. - Assertion misses dictionary tier
encoding = 3(products/maka/cli/tests/upgrade_compat.rs:2086): The post-upgrade continuation check assertsc.encoding IN (1, 2), which will miss rows encoded with #7289'sdict_v1tier (3); changing toIN (1, 2, 3)aligns with #7289. - Silent skip on malformed
instructionsRef(plugins/agent/state/src/sql.rs:1081-1091,plugins/agent/state/src/session_history/sql.rs:958-967):if let Ok(reference) = ...silently skips a corruptedinstructionsRefobject instead of failing closed like the neighboringExternalEffectEvent::Preparedcheck.
中文
已核实 76ad3524cc 修完了上次全部 3 条发现(settle / read_return 保持完整 CellReply.observation、ToolResultFields::value() 对齐显式 JsonKind::Null、空 tool_contracts 不再写多余 blob),新增的 ('text', 'text') / ('cell', 'text') FromOutput 扩展与 instructions_ref 的 pin / snapshot / 导入链路也已全链路闭环。
合并前还有三处小问题可以顺手清理:
completed_cell_projection_json无界缓存CellObservation.result绕过SourceBudget(plugins/agent/state/src/session_history/tool_result_source.rs:464-470, 999-1015):read_source_bytes会把整份resultJSON 无界读进Vec<u8>(budget只限制单次 32 KiB 读块)再解析成完整serde_json::ValueDOM。对大 JSON cell 结果建议改为流式转义输出或把累计字节纳入SourceBudget上限。products/maka/cli/tests/upgrade_compat.rs:2086漏掉了字典编码档3:升级后续跑校验写的是c.encoding IN (1, 2),会漏掉 #7289 走dict_v1压缩的行,改成IN (1, 2, 3)即可。instructionsRef格式损坏时静默跳过(plugins/agent/state/src/sql.rs:1081-1091、plugins/agent/state/src/session_history/sql.rs:958-967):if let Ok(reference) = ...遇到损坏的instructionsRef字段会静默跳过,建议和旁边的ExternalEffectEvent::Prepared一样改成 fail-closed。
76ad352 to
ef0d958
Compare
English@Astro-Han Thanks for the review! Rebased onto the updated stack and fixed all three items in
中文@Astro-Han 感谢 review!已同步 rebase 并在
|
ef0d958 to
4f4f92f
Compare
Astro-Han
left a comment
There was a problem hiding this comment.
English
Confirmed all three previous items are cleanly fixed on 4f4f92f9a4:
completed_cell_projection_jsonnow streams viaJsonStringEscapedByteswith bounded memory, correct JSON escaping and UTF-8 chunk-boundary handling, and byte-identical slicing.external_task_instructions_refis shared and fail-closed on malformed or missing referenced content.upgrade_compat.rschecksc.encoding IN (1, 2, 3).
Two optional minor follow-ups (non-blocking):
plugins/agent/state/src/sql.rs:1124-1135:ExternalEffectEvent::Returnedstill ignores read/parse errors fail-open when pinning, unlikesession_history/sql.rs:966-979which fails closed.plugins/agent/state/src/session_history/tool_result_source.rs:1235:JsonStringEscapedCursor::read_chunkallocates a fixed 32 KiB scratch buffer while holding the caller's buffer; clamping tocap.clamp(64, 32 * 1024)or reusing a cursor buffer is slightly tighter under small budgets.
Ready to merge once the earlier PRs in the stack land.
中文
已确认 4f4f92f9a4 上三项问题均已干净修复:
completed_cell_projection_json已改为JsonStringEscapedBytes有界流式实现,JSON 转义、UTF-8 跨块边界与任意切片均正确。external_task_instructions_ref已抽成共用实现并在非法/缺失引用时 fail-closed。upgrade_compat.rs已更新为c.encoding IN (1, 2, 3)。
两处不阻塞合并的小点:sql.rs:1124-1135 的 ExternalEffectEvent::Returned pin 仍是 fail-open(与 session_history/sql.rs:966-979 不一致);tool_result_source.rs:1235 可按 cap.clamp(64, 32 * 1024) 申请或复用缓冲。前置 PR 就绪后即可合并。
4f4f92f to
aa191fc
Compare
|
@Astro-Han Quick heads-up on the rebase push |
…riptors, and return payloads
Eliminate structural duplication in newly written durable fact payloads while
preserving full read compatibility with historical payloads:
- Reference-share repeated tool contracts, external effect definitions
(StoredToolDefinition::{Inline, Ref}), and external instructions
(instructions_ref) via content-addressed ContentRef blobs.
- Deduplicate redundant projection text on ('text', 'text') and ('cell', 'text')
tool returns via StoredToolResult::FromOutput and strip redundant inline
CellReply.observation on Completed outputs (keeping observation on Interrupted
for cross-run external wait reads).
- Switch accept_cell_with_tool to StoredToolResult so compact CellCompleted
returns round-trip cleanly across live runs and upgrade_compat capsules.
Refs #7272
Generated-by: Antigravity
aa191fc to
e714c93
Compare
English
PR 6/8 in the #7272 storage optimization stack (stacked on #7289; rebased onto
mainafter0057_pinned_memory.sql).Stack (#7272)
m0058)agent_recall_messages.folded(m0059)m0060)(owner, session)strings withnamespace_id(m0061)contents(m0062–m0063)application_*&agent_cells, internagent_usage_callsJSON blobs (m0064–m0065)Layout v3, zero SQL migration)Summary
Eliminates structural duplication in newly written durable fact payloads while keeping full read compatibility with historical payloads:
StoredToolDefinition::{Inline, Ref}), and external instructions (instructions_ref) via content-addressedContentRefblobs.('text', 'text')and('cell', 'text')tool returns viaStoredToolResult::FromOutput, and strips redundant inlineCellReply.observationonCellReplyState::Completedoutputs (preserving inlineobservationonCellReplyState::Interruptedso cross-run external wait reads and snapshots stay intact).accept_cell_with_tool(plugins/agent/engine/src/driver/cells.rs) toToolReturn<StoredToolResult>so compactCellCompletedreturns round-trip cleanly across live runs andupgrade_compatcapsules, and preserves emptytool_contractsprovenance inaccess/model.rsandcompacted.rs.Offline Real-DB Stack Outcome (24.34 GiB CoW Clone)
This PR targets newly written durable facts (on top of the historical migrations in #7285–#7289 and #7318). Across the full 7-PR stack on a
24.34 GiBoffline CoW clone, existing historical data alone drops to10.34 GiBpre-VACUUM(-57.5%/2.35×) and9.30 GiBpost-VACUUM(-61.8%/2.62×), with #7290 further shrinking steady-state new writes.Tests
cargo fmt --check— PASScargo clippy --no-deps -p maka-event-log -p maka-agent-facts -p maka-agent-state --all-targets -- -D warnings— PASScargo nextest run -p maka-event-log -p maka-agent-facts -p maka-agent-state -p maka-agent-engine— PASScargo nextest run -p maka-agent-native -E 'test(tool_history) | test(step_projection) | test(external_return) | test(tool_contracts) | test(external_effect)'— 26/26 PASScargo nextest run -p maka-cli --test upgrade_compat -E 'test(upgrade_compat_capsule_roundtrip)'— PASSRefs #7272
中文
#7272 存储优化系列第 6/8 个 PR(基于 #7289,已同步 rebase 到
main0056之后)。系列栈(#7272)
m0058)agent_recall_messages.folded冗余列(m0059)m0060)namespace_id替换重复(owner, session)字符串(m0061)contents分档/静态字典 zstd 压缩与后台存量重压(m0062–m0063)application_*与agent_cells并对agent_usage_callsJSON 字典驻留(m0064–m0065)Layout v3,零 SQL 迁移)改动内容
消除新写 durable facts 中的结构性重复,同时完整兼容历史载荷读取:
ContentRef引用共享重复的 tool contracts、外部工具定义(StoredToolDefinition::{Inline, Ref})及外部指令文本(instructions_ref)。StoredToolResult::FromOutput消除('text', 'text')与('cell', 'text')工具返回中的重复 projection 文本,并仅在CellReplyState::Completed输出上剥离冗余内联CellReply.observation(保留Interrupted场景的内联观测,保证跨 run 等待与快照完整)。accept_cell_with_tool切换为ToolReturn<StoredToolResult>,并修复access/model.rs与compacted.rs中空tool_contracts的 provenance 还原。整栈离线实测结果(24.34 GiB CoW 克隆)
本 PR 优化后续新写 durable facts;整条 7-PR 栈(#7285–#7318)仅在存量历史数据上即已从
24.34 GiB -> 10.34 GiB(VACUUM前活跃页,-57.5%/2.35×)压至9.30 GiB(VACUUM后,-61.8%/2.62×),叠加本 PR 后新写稳态占用进一步下降。Refs #7272