Skip to content

perf(agent): externalize and deduplicate media in frozen prompts (Layout v3) - #7341

Open
M4n5ter wants to merge 1 commit into
perf/7272-compress-non-content-tablesfrom
perf/7272-dedup-prompt-media
Open

M4n5ter wants to merge 1 commit into
perf/7272-compress-non-content-tablesfrom
perf/7272-dedup-prompt-media

Conversation

@M4n5ter

@M4n5ter M4n5ter commented Nov 27, 2026 •

Copy link
Copy Markdown
Member
English

PR 8/8 in the #7272 storage optimization stack (stacked on #7318; zero SQL migration required).

Stack (#7272)

  1. perf(agent-state): drop redundant duplicate and prefix indexes on recall, runs, and interactions #7285 — Drop 6 redundant duplicate/prefix B-tree indexes (m0058)
  2. perf(agent-state): drop stored folded column from agent_recall_messages #7286 — Drop agent_recall_messages.folded (m0059)
  3. perf(agent-state): deduplicate Recall indexing at source and coalesce external deltas #7287 — Deduplicate Recall bodies & FTS5 postings at source + 2-tier immutable external delta sealing (m0060)
  4. perf(agent-state): replace repeated (owner, session) strings with integer namespace_id #7288 — Replace repeated (owner, session) strings with namespace_id (m0061)
  5. perf(event-log): add tiered/dictionary zstd compression and background recompression for contents #7289 — Tiered/dictionary zstd compression & background recompression for contents (m0062–m0063)
  6. perf(agent): deduplicate step metadata, tool contracts, external descriptors, and return payloads #7290 — Structural dedup for step metadata, tool contracts, external descriptors & returns
  7. perf(storage): compress application tables, agent_cells bodies, and intern usage JSON blobs #7318 — Compress application_* & agent_cells, intern agent_usage_calls JSON blobs (m0064–m0065)
  8. perf(agent): externalize and deduplicate media in frozen prompts (Layout v3) #7341 — Externalize & CAS-deduplicate media in frozen prompts (Layout v3, zero SQL migration)

Problem

As highlighted by the screenshot-heavy desktop workload report on #7318, snapshot_prompt previously inflated and duplicated media payloads inside frozen prompt chunks:

  1. 2.33× per-image bloat inside a single prompt arena: serialize_source::exact_message_async base64-encoded each image/audio/file part (1.33×) into CaptureArena, and canonical_prompt::project::decode_media immediately decoded a raw binary copy (+1.0×) back into the same arena. Both copies are incompressible entropy and sit on top of the original attachment/artifact blob already stored in contents.
  2. Chunk-shift re-storage: Because snapshot_prompt slices the monolithic arena into fixed 32 KiB chunks, any earlier 1-byte change (e.g. skill revision hash, system prompt update, new run) shifts byte alignment and re-hashes/re-stores another 2.33× copy of every historical image in the prompt (amplifying screenshot-heavy and CUA sessions dramatically).

Summary

  • Layout v3 externalized media (canonical_prompt.rs, project.rs, serialize_source.rs, preparation/snapshot.rs):
    • When snapshot_prompt serializes a ContentRecipe::Media part (both User messages and ToolOutputRecipe::Content), it captures the raw bytes into a lazy MediaCapture arena deduplicated by (sha256, bytes) and writes only a compact content-addressed placeholder ({"type":"ref","digest":"sha256:...","bytes":...}) into the main prompt arena — eliminating base64 encoding/decoding roundtrips and keeping prompt chunks small and zstd-compressible.
    • All new frozen prompt snapshots emit Layout { version: 3 } uniformly (prompt_media omitted when empty); Layout { version: 2 } is kept strictly as a read-only legacy path for existing immutable prompts.
    • Each externalized media record binds the media slot index, byte length, and full 32-byte SHA-256 digest (r[6..10]) inside the cryptographically hashed prompt arena. On restore_prompt_from, media blobs are streamed from ContentSource::{Live, Snapshot} into the temporary restore arena after layout.byte_len, with strict fail-closed verification of version, length, and digest (preventing equal-length blob swaps or missing refs).
  • Automatic CAS dedup & GC/fork-snapshot pinning (driver_model.rs, compacted.rs, summary_repair.rs, materialize.rs, auxiliary.rs):
    • Adds optional #[serde(default, skip_serializing_if = "Vec::is_empty")] prompt_media: Vec<ContentRef> to FrozenInput and includes it in FrozenInput::content_refs() -> RequestSpec.request_contents, so live agent_content_pins and fork agent_history_snapshot_pins retain every media blob automatically.
    • Unmodified attachments/artifacts hit existing contents rows via CAS (0 extra bytes stored on disk across steps, prefix shifts, and forks); resized images from MediaView store once per unique digest instead of 2.33× per shifted step.

Tests

  • Added frozen_prompt_externalizes_and_deduplicates_media_with_tamper_guards (tool_history.rs) covering repeated User + ToolOutput::Content media deduplication, < 8 KiB chunk size proof, prefix-shift stability, bit-for-bit PreparedPrompt logical identity parity with v2, live SQLite restore, and fail-closed checks (equal-length swap, empty media on v3, non-empty media on v2).
  • Added prompt_media_round_trips_and_pins_in_content_refs (driver_model.rs).
  • Verified: maka-agent-engine (41/41 PASS), maka-agent-native image/media/attachment/fork/snapshot tests (19/19 PASS), maka-cli::upgrade_compat upgrade_compat_capsule_roundtrip (PASS), cargo fmt --check, asf-license-headers, migrations (74 locked, 0 pending), zero clippy warnings on touched files.

Refs #7272

中文

#7272 存储优化系列第 8/8 个 PR(基于 #7318,无需新增 SQL 迁移)。

系列栈(#7272)

  1. perf(agent-state): drop redundant duplicate and prefix indexes on recall, runs, and interactions #7285 — 删除 6 个重复/前缀冗余 B-tree 索引(m0058)
  2. perf(agent-state): drop stored folded column from agent_recall_messages #7286 — 删除 agent_recall_messages.folded 冗余列(m0059)
  3. perf(agent-state): deduplicate Recall indexing at source and coalesce external deltas #7287 — 从源头对 Recall 正文与 FTS5 postings 联合去重 + 两段不可变外部 delta 封口(m0060)
  4. perf(agent-state): replace repeated (owner, session) strings with integer namespace_id #7288 — 用整数 namespace_id 替换重复 (owner, session) 字符串(m0061)
  5. perf(event-log): add tiered/dictionary zstd compression and background recompression for contents #7289 — contents 分档/静态字典 zstd 压缩与后台存量重压(m0062–m0063)
  6. perf(agent): deduplicate step metadata, tool contracts, external descriptors, and return payloads #7290 — 新写 durable facts 结构去重(tool contracts、external descriptors/instructions、returns)
  7. perf(storage): compress application tables, agent_cells bodies, and intern usage JSON blobs #7318 — 压缩 application_* 与 agent_cells 并对 agent_usage_calls JSON 字典驻留(m0064–m0065)
  8. perf(agent): externalize and deduplicate media in frozen prompts (Layout v3) #7341 — Frozen prompt 媒体外置与 CAS 去重(Layout v3,零 SQL 迁移)

问题背景

结合 #7318 评论中多截图桌面库的实测反馈,排查确认此前 snapshot_prompt 存在两层媒体放大:

  1. 单次 frozen prompt 内每张图膨胀 2.33×:serialize_source::exact_message_async 先将媒体 base64 编码(1.33×)写入 CaptureArena,紧接着 canonical_prompt::project::decode_media 又把原始二进制解码(+1.0×)追加进同一个 arena;两份都是 zstd 压不动的随机熵,且叠加在 contents 原附件之上。
  2. 前缀偏移 1 字节触发全量重写:snapshot_prompt 按固定 32 KiB 切片,只要前面 system prompt / Skill revision / 上下文变化哪怕 1 字节,历史中所有图片的 2.33× 都会重新分块落库(多截图对话与 CUA 场景尤为严重)。

改动内容

  • Layout v3 媒体外置(canonical_prompt.rs / project.rs / serialize_source.rs / preparation/snapshot.rs):
    • snapshot_prompt 遇到 ContentRecipe::Media(覆盖 User 消息与 ToolOutputRecipe::Content)时,将原始字节按 (sha256, bytes) 去重写入延迟创建的 MediaCapture 临时 arena,主 prompt arena 内只写一条 ~100 B 的内容寻址占位({"type":"ref","digest":"sha256:...","bytes":...}),免去每步 base64 编解码并保持 prompt chunk 高度可压。
    • 所有新写入的 frozen prompt 统一使用 Layout v3(无媒体时省略 prompt_media),Layout v2 仅作为已封存历史 prompt 的只读兼容路径。
    • Arena 二进制记录直接绑定媒体槽位、字节数与完整 32 字节 SHA-256 摘要(r[6..10]),restore_prompt_from 从 ContentSource::{Live, Snapshot} 装回时严格 fail-closed 校验版本、长度与摘要(防止等长媒体替换或缺失)。
  • 自动 CAS 去重与 GC / fork snapshot pin(driver_model.rs / compacted.rs / summary_repair.rs / materialize.rs / auxiliary.rs):
    • FrozenInput 新增可选字段 prompt_media: Vec<ContentRef>(为空时省略),合入 FrozenInput::content_refs() -> RequestSpec.request_contents,自动受活库 agent_content_pins 与 fork agent_history_snapshot_pins 保护;未缩放原图直接 CAS 命中 contents 现有行(磁盘零新增),缩放后图片也仅按唯一摘要存一份。

验证

  • 新增 frozen_prompt_externalizes_and_deduplicates_media_with_tamper_guards(tool_history.rs)与 prompt_media_round_trips_and_pins_in_content_refs(driver_model.rs)。
  • 实跑:maka-agent-engine 41/41 PASS、maka-agent-native 图片/媒体/附件/fork/snapshot 定向测试 19/19 PASS、upgrade_compat_capsule_roundtrip PASS、cargo fmt --check / asf-license-headers / migrations(74 locked, 0 pending)全绿,改动文件零 clippy 警告。

Refs #7272

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

Really clean design on f87a8adfcd—moving media out of the 32 KiB prompt chunks removes both the 2.33× per-image arena bloat and chunk-shift re-storage with zero SQL migration. I verified:

  • Full 32-byte SHA-256 + byte-length fail-closed binding across capture, index record (r[6..10]), and restore_prompt_from (both Live and Snapshot sources), with streaming file-backed restoration and clean arena cleanup on error/cancellation.
  • description.commitment and prefix_digest remain byte-identical between Layout v2 and v3, preserving prompt caching and covered_prefix across upgrades.
  • All snapshot_prompt sites (driver_model.rs, compacted.rs, summary_repair.rs) wire prompt_media into FrozenInput::content_refs() -> RequestSpec.request_contents for live and fork-snapshot pinning.

One item worth adding before merging:

  • products/maka/cli/tests/upgrade_compat.rs:2311-2320: per the persisted payload compatibility rule, when checking continuation_run_id's RequestSpecs after upgrading legacy capsules, please also decode request (FrozenInput) and assert that post-upgrade writes emit layout.version == 3 (confirming v2 -> v3 live continuation end-to-end).

Two minor nits:

  • plugins/agent/engine/src/history/canonical_prompt.rs:95-99: CaptureArena::new(self.io.clone(), None) already starts file-backed, so the immediately following created.promote_to_file().await is redundant and briefly reserves a second local I/O lease.
  • plugins/agent/engine/src/preparation/snapshot.rs:91-115: optionally include media.len() * size_of::<RestoredMediaEntry>() in staging metadata accounting for consistency.
中文

f87a8adfcd 的设计很干净,零 SQL 迁移就把单图 2.33× 膨胀和 32 KiB 切片位移重存一起解决了。已核验:

  • 捕获、索引记录(r[6..10])和 restore_prompt_from(Live/Snapshot 双路径)全程做了完整 32 字节 SHA-256 + 长度 fail-closed 绑定,流式文件恢复且异常/取消路径无 arena 泄漏。
  • description.commitment 与 prefix_digest 在 Layout v2 与 v3 之间逐比特一致,升级不断 prompt cache 与 covered_prefix。
  • driver_model.rs、compacted.rs、summary_repair.rs 全链路将 prompt_media 写入 FrozenInput::content_refs() -> RequestSpec.request_contents,live 与 fork 快照 pin 闭合。

合并前建议补一项:

  • products/maka/cli/tests/upgrade_compat.rs:2311-2320:按持久化 JSON payload 变更规范,建议在 continuation_run_id 校验 RequestSpec 时顺带解码 FrozenInput,断言升级后新写入的是 layout.version == 3,端到端验证 v2 胶囊续跑切到 v3。

两处小细节:canonical_prompt.rs:95-99 的 CaptureArena::new(..., None) 本身已是文件型,紧接着的 promote_to_file() 是多余的;snapshot.rs:91-115 的 staging 可选顺带计入 RestoredMediaEntry 向量元数据字节。

@M4n5ter
M4n5ter force-pushed the perf/7272-dedup-prompt-media branch 2 times, most recently from 3de9958 to fae2955 Compare November 27, 2026 07:19
@M4n5ter

M4n5ter commented Nov 27, 2026

Copy link
Copy Markdown
Member Author

@Astro-Han Thanks for the review — all items plus a few capture/restore hardening fixes are in fae2955ba6:

  1. upgrade_compat.rs Layout v3 continuation check: in the continuation_run_id check, every RequestSpec.request (FrozenInput) is now decoded from contents and asserted to emit layout.version == 3.
  2. Removed redundant promote_to_file(): dropped the extra created.promote_to_file().await in MediaCapture::ensure_arena since CaptureArena::new(self.io.clone(), None) already starts file-backed.
  3. Directory budget accounting & capture/restore hardening:
    • preparation/snapshot.rs: restore_prompt_from accounts for media.len() * size_of::<RestoredMediaEntry>() via staging.preparation.plan_directory and runs validate_external_media_directory up front (checking every slot, SHA-256, length, v2 tag-3 rejection, and exact 1-to-1 slot coverage) before copying any media blobs or returning PreparedPrompt.
    • canonical_prompt.rs + request_backing.rs: switched MediaCapture::capture_bytes to single-pass stream+hash with truncate_unsealed rollback on dedup hit / error, and charged each unique MediaIndex entry through plan_directory.

Verified locally with maka-agent-engine --lib (43 passed), maka-agent-native media/tamper tests, rustfmt --check, and cargo test -p maka-cli --test upgrade_compat.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

English

Confirmed all items and the extra capture/restore hardening are cleanly in place on fae2955ba6:

  • upgrade_compat.rs:2322-2364 decodes post-upgrade continuation FrozenInput payloads and asserts layout.version == 3.
  • Removed the redundant promote_to_file() call in MediaCapture::ensure_arena.
  • Single-pass streaming with truncate_unsealed, directory budget accounting in both capture and restore, and upfront validate_external_media_directory verification all check out.

Ready to merge once the base stack lands.

中文

已确认 fae2955ba6 全部项及新增的捕获/恢复加固都干净落地:

  • upgrade_compat.rs:2322-2364 已解码升级续跑写入的 FrozenInput 并断言 layout.version == 3。
  • MediaCapture::ensure_arena 已移除多余的 promote_to_file()。
  • 单遍流式写入配合 truncate_unsealed、捕获与恢复双侧 directory 预算记账以及前置 validate_external_media_directory 校验均核查通过。

前置栈合入后即可合并。

…out v3)

Prevent frozen prompt snapshots from duplicating media payloads inside 32 KiB
prompt chunks:
- Previously, exact_message_async base64-encoded media (1.33x) into the
  CaptureArena and canonical_prompt::project::decode_media immediately decoded
  a raw binary copy (+1.0x) into the same arena (2.33x per image per prompt),
  and any earlier byte shift re-hashed and re-stored every image chunk.
- Add Layout v3 in canonical_prompt + preparation/snapshot: all new frozen
  prompt snapshots emit Layout v3 uniformly (with prompt_media omitted when
  empty); media parts write only a compact content-addressed ref placeholder
  into the prompt arena, capture raw bytes once into a lazy MediaCapture arena
  deduplicated by (digest, bytes), and pin the media ContentRefs in
  FrozenInput.prompt_media / RequestSpec.request_contents (hitting CAS against
  existing attachment/artifact rows in contents with zero extra disk storage).
- Bind every externalized media record's 32-byte SHA-256 digest and byte
  length inside the prompt arena record and verify them fail-closed on
  restore_prompt_from. Layout v2 is kept strictly as a read-only legacy path
  for existing hash-chained prompts (zero SQL migration required).

Refs #7272

Generated-by: Antigravity
@M4n5ter
M4n5ter force-pushed the perf/7272-dedup-prompt-media branch from fae2955 to c9361ea Compare November 27, 2026 09:30

This branch has not been deployed

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

Labels

effort/XL Under 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants