opencode icon indicating copy to clipboard operation
opencode copied to clipboard

[FEATURE]: opencode db compact — reclaim bloated event table on existing 1.19.x databases (RU/EN/ZH)

Open k1vinvin224 opened this issue 5 days ago • 1 comments

Кратко / Summary / 概要

One report in three languages (Russian, English, Chinese), same data. opencode 1.19.6 on Termux/Android: opencode.db grew to 774 MB, mostly repeated full snapshots in the event table, and there is no built-in way to reclaim an existing database. opencode db only exposes path and a sqlite shell/query — no maintenance command.


Русский

Проблема

opencode 1.19.6 (Termux/Android, aarch64, локальный CLI). После нескольких недель использования opencode.db вырос до 774 МБ. Около 80% занимает таблица event: при каждом обновлении сообщения/части сохраняется полный снимок (message.updated.1, message.part.updated.1), включая большие поля summary.diffs. Исторические версии нигде не используются, но занимают место. Встроенного способа очистить уже существующую базу нет.

Измерения до очистки

Таблица Строк Размер
event 93 175 ~616 МБ
message 6 864 ~35,5 МБ
part 25 122 ~46,5 МБ
opencode.db 774 МБ

Дублирование снимков:

  • message.updated.1: 25 517 событий на 6 868 id сообщений (до 135 копий одного сообщения);
  • message.part.updated.1: 60 834 события на 25 134 id частей;
  • session.updated.1: 6 802 события на 18 сессий;
  • максимальный одиночный снимок — 1,34 МБ.

Ручная очистка (проверенная)

  1. Для каждой сессии оставить один session.created и последний session.updated.
  2. Для каждого живого сообщения — последний message.updated; для каждой живой части — последний message.part.updated.
  3. Удалить устаревшие снимки и message.removed.
  4. Перенумеровать seq подряд (0..N) для каждого агрегата и обновить event_sequence.seq.
  5. Проверить, что каждый оставленный снимок совпадает с message/part; при расхождении — откат.
  6. Выполнить VACUUM.

Результат: 774 МБ → 186 МБ, 32 022 события, все 6 864 сообщения и 25 122 части совпадают, integrity_check = ok. Дальнейшая работа добавляет события корректно (170 новых событий, seq без разрывов).

Предложение

Добавить opencode db compact [--dry-run] [--force]:

  • отказ при запущенном сервере/активных писателях;
  • резервная копия через SQLite backup API;
  • проверка схемы/миграций и отказ при неизвестных типах событий;
  • дедупликация снимков, пересчёт seq, обновление event_sequence;
  • проверка эквивалентности проекциям message/part с откатом при ошибке;
  • VACUUM после успеха (при необходимости auto_vacuum = INCREMENTAL). Дополнительно: --drop-log для локальных баз, где журнал событий действительно не читается, и --session <id> для очистки одной сессии.

English

Problem

opencode 1.19.6 (Termux/Android, aarch64, local CLI). After a few weeks opencode.db reached 774 MB, ~80% in the event table. Every message/part update stores a full snapshot (message.updated.1, message.part.updated.1), including large summary.diffs. Superseded versions are not needed but are never pruned, and there is no supported way to reclaim an existing DB.

Measurements (before compaction)

Table Rows Size
event 93,175 ~616 MB
message 6,864 ~35.5 MB
part 25,122 ~46.5 MB
opencode.db 774 MB

Snapshot duplication:

  • message.updated.1: 25,517 events for 6,868 message ids (up to 135 copies of one message);
  • message.part.updated.1: 60,834 events for 25,134 part ids;
  • session.updated.1: 6,802 events for 18 sessions;
  • largest single snapshot: 1.34 MB.

Verified manual compaction

  1. Keep one session.created and the latest session.updated per session.
  2. Keep the latest message.updated per live message and the latest message.part.updated per live part.
  3. Drop superseded snapshots and message.removed.
  4. Renumber seq contiguously (0..N) per aggregate and update event_sequence.seq.
  5. Verify each kept snapshot equals the message/part projection; rollback on mismatch.
  6. Run VACUUM.

Result: 774 MB → 186 MB, 32,022 events, all 6,864 messages and 25,122 parts verified identical, integrity_check = ok. Continued use appends events correctly (170 new events, contiguous seq).

Proposal

Add opencode db compact [--dry-run] [--force]:

  • refuse while the server is running / writers are active;
  • back up via the SQLite backup API;
  • validate schema/migrations and abort on unknown event types;
  • deduplicate snapshots, renumber seq, update event_sequence;
  • verify equivalence against the message/part projections and roll back on mismatch;
  • VACUUM on success (optionally set auto_vacuum = INCREMENTAL). Also: --drop-log for local-only DBs where the event log is truly never read, and --session <id> for scoped compaction.

中文

问题

opencode 1.19.6(Termux/Android,aarch64,本地 CLI)。使用几周后 opencode.db 涨到 774 MB,约 80% 在 event 表:每次消息/片段更新都存一份完整快照(message.updated.1、message.part.updated.1),包含体积很大的 summary.diffs。被覆盖的历史版本没有用途,却从不清理,也没有内置办法回收已有数据库。

清理前实测

表 行数 大小
event 93,175 ~616 MB
message 6,864 ~35.5 MB
part 25,122 ~46.5 MB
opencode.db 774 MB

快照冗余:

  • message.updated.1:25,517 条事件对应 6,868 个消息 id(单个消息最多存了 135 份);
  • message.part.updated.1:60,834 条事件对应 25,134 个片段 id;
  • session.updated.1:6,802 条事件对应 18 个会话;
  • 最大单条快照 1.34 MB。

已验证的手动清理

  1. 每个会话保留 1 条 session.created 和最新 1 条 session.updated。
  2. 每个存活消息保留最新 1 条 message.updated,每个存活片段保留最新 1 条 message.part.updated。
  3. 删除被覆盖的快照和 message.removed。
  4. 每个聚合重新连续编号 seq(0..N),并同步 event_sequence.seq。
  5. 校验每条保留快照与 message/part 投影一致,不一致则回滚。
  6. 执行 VACUUM。

结果:774 MB → 186 MB,32,022 条事件;6,864 条消息、25,122 个片段全部与投影一致;integrity_check = ok;继续使用可正常追加事件(新增 170 条,seq 连续)。

建议

新增 opencode db compact [--dry-run] [--force]:

  • 服务运行/有写入时拒绝执行;
  • 通过 SQLite backup API 先备份;
  • 校验 schema/迁移版本,遇到未知事件类型则安全中止;
  • 去重快照、重排 seq、更新 event_sequence;
  • 提交前与 message/part 投影比对,不一致回滚;
  • 成功后 VACUUM(可选设置 auto_vacuum = INCREMENTAL)。 另可选:对确实不读取事件日志的本地库提供 --drop-log,以及按会话清理的 --session <id>。

Environment

  • opencode 1.19.6 (sessions created with 1.19.5/1.19.6), Termux/Android aarch64
  • DB: ~/.local/share/opencode/opencode.db (SQLite, WAL)
  • opencode db currently provides only path and a query/sqlite shell

Related

#33356, #41175, #47854, #47591

k1vinvin224 avatar Nov 30 '26 09:11 k1vinvin224

Thanks for the detailed write-up and the measurements. The manual compaction steps you verified should help others in the same situation.

You're on opencode 1.19.6, which is V1. V1 now only gets critical fixes, so a new maintenance command like opencode db compact is unlikely to be added there. We encourage upgrading to V2 (npm package @opencode/cli): https://opencode.ai/docs/migrate-v1/

To be clear, I haven't confirmed that V2 avoids this growth. These open V2 issues cover related storage growth, and you're welcome to add your findings or the db compact idea there:

  • #47854: V2 event history duplicates large snapshot payloads
  • #47591: core databases don't reclaim deleted pages (auto_vacuum)
  • #55282, #58436: other opencode.db size reports on V2

I'm closing this issue now. If you think this is critical, or you see the same problem on V2, reply here and the issue will reopen.

opencodejr[bot] avatar Nov 30 '26 09:11 opencodejr[bot]