[GH-ISSUE #1404] [Issue]: Long-Term Memory: finished drafts are never deleted, and every reply rewrites usage counters nothing reads #713

Closed
opened 2026-10-20 17:29:59 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @Promansis on GitHub (Oct 15, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1404

Originally assigned to: @Promansis on GitHub.

Summary

Two Long-Term Memory stores grow with use and are read in full on frequent paths:

  • Finished extraction drafts are never deleted. Every draft listing reads and validates all of them, including the pending-count check the Long-Term Memory screen makes when it opens.
  • usage.json is rewritten whole on every reply that injects memories. Each time it gains per-chat, per-memory counters under the vault lock. Nothing reads those counters except the code that expires and deletes them.

This is the remainder of finding 4 from the 1.4.8 architecture audit. #1328 (1.4.29) fixed the other parts: repair backups and the rejected-suggestion cap.

Affected package

long-term-memory 1.4.38 (upstream/staging eb4af30d0), under packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory/:

  • draft-store.ts: listDrafts (270-292) reads and validates every draft file, then filters by status.
  • retention.ts: runLongTermMemoryRetentionUnsafe. Its five steps (131-226) prune quarantine, usage, receipts, events and incomplete generations, but not drafts.
  • usage.ts: recordLongTermMemoryInjection (107-160).
  • The only readers of usage.chats are retention step 2 (retention.ts:144-178) and the permanent-delete cleanup (storage.ts:1299-1311).

Expected behavior

  • Finished drafts are removed after a while. Pending and invalidated drafts stay, because Review and Activity show those.
  • A reply does not rewrite data that nothing reads.

Actual behavior

  1. Drafts.
    • Statuses. A draft is pending, accepted, auto_applied, superseded or invalidated.
    • What the UI asks for. Only pending and invalidated drafts (/drafts/pending-count, and /drafts/review?includeInvalidated=true from Review and Activity).
    • Deletion. A draft file is deleted only when Review discards all of its changes (draft-store.ts:406, routes.ts:1630). Retention never deletes drafts.
    • Who pays. listDrafts parses every file before filtering. It runs on:
      • /status;
      • /drafts/pending-count, fetched when the screen opens (LongTermMemoryDetail.tsx:56);
      • each new extraction draft (supersedeOlderPendingDrafts, draft-store.ts:243-244);
      • the Review and Activity projections;
      • backups;
      • reference redirects after a rename or merge (storage.ts:556).
  2. usage.json.
    • On each reply that injects memories, recordLongTermMemoryInjection (usage.ts:114-143), under the vault lock that recall also takes:
      • reads and validates the whole file;
      • updates retrievalCount, injectionCount, totalInjectedTokens, lastRetrievedAt and lastInjectedAt for every injected memory in that chat;
      • adds the receipt id to acceptedReceipts;
      • rewrites the whole file.
    • Expiry. Entries expire only after usageRetentionDays and receiptRetentionDays, both 180 by default.
    • Readers. No route or client code reads usage. readLongTermMemoryUsage is called only by retention, the permanent-delete cleanup and the writer itself.

Measured on one real vault (a read-only copy taken 2026-10-08; aggregate counts only):

Store Size
drafts/ 17 files from about 2 weeks of use: 1.2 MB, median 75 KB, largest 126 KB. None pending (9 superseded, 8 accepted), so each pending-count check parsed 1.2 MB to find nothing.
indexes/usage.json 918 KB after about 2.5 weeks and 38 chats. About 92% of its content is 1,975 per-memory counter entries; the 810 accepted receipt ids are about 55 KB.

Both grow with use: drafts without limit, usage counters for 180 days.

Steps to reproduce

  1. Use auto extraction in a chat for a few days, accepting drafts or letting newer ones supersede them.
  2. Open <dataDir>/long-term-memory/drafts/. Every finished draft is still there, including after the daily retention run.
  3. Send replies that inject memories and watch indexes/usage.json grow. Searching the package for usage.chats finds only retention and the delete cleanup.

Environment

  • Marinara Engine version: 2.5.0 line (package range >=2.4.1 <4.0.0)
  • Package version: code read at long-term-memory 1.4.38 (upstream/staging eb4af30d0); sizes come from a vault written by earlier 1.4.x releases
  • Install type: source
  • OS + version: not platform-specific
  • Browser or app shell: any

Logs, screenshots, or video

See the size table above. It holds aggregate counts only, with no vault content.

Additional context

Minimal fix, one commit each:

  1. Prune finished drafts.
    • Add a step 6 to runLongTermMemoryRetentionUnsafe. It deletes draft files whose status is accepted, auto_applied or superseded and whose updatedAt is older than config.auditWindowDays (30 by default). Reusing that existing retention field leaves the config schema unchanged.
    • Keep pending and invalidated drafts. Count removals in the result, as the other steps do.
    • getDraft already returns null for a missing file, and subject-choice-review.ts:51 already returns draft: null when a resolved identity decision has no draft. Confirm the Review client handles null for a decision whose draft was pruned.
    • Regression in tests/long-term-memory-storage.regression.ts, beside the retention cases at 360-410: an accepted and a superseded draft older than the window are removed, while a recent accepted draft, a pending draft and an invalidated draft are kept.
  2. Stop writing per-memory usage counters.
    • In recordLongTermMemoryInjection, stop updating usage.chats and write chats: {}. That drops the existing counters on the next reply.
    • Keep acceptedReceipts and the duplicate check as they are, so the dispatch result returned to the Engine does not change.
    • Retention step 2 and the delete cleanup then have nothing to do. Deleting them can be a follow-up.
    • Update the reserved-key test at tests/long-term-memory-index-keys.regression.ts:693-715 to check acceptedReceipts only.
    • Regression: after two injected replies, usage.json has no per-memory entries, and a repeated accounting id still returns null.

Notes:

  • No downgrade risk: the usage schema still requires chats, and an empty object is valid for older versions too.
  • Not covered: acceptedReceipts still gains one id per injected reply for receiptRetentionDays (about 55 KB in the sample). Shortening that window needs a check of what the Engine does with the dispatch result.
  • If per-memory recall counts are wanted later, for example for a "last recalled" column, they can come back together with a reader.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @Promansis on GitHub (Oct 15, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1404 Originally assigned to: @Promansis on GitHub. ## Summary Two Long-Term Memory stores grow with use and are read in full on frequent paths: - **Finished extraction drafts are never deleted.** Every draft listing reads and validates all of them, including the pending-count check the Long-Term Memory screen makes when it opens. - **`usage.json` is rewritten whole on every reply that injects memories.** Each time it gains per-chat, per-memory counters under the vault lock. Nothing reads those counters except the code that expires and deletes them. This is the remainder of finding 4 from the 1.4.8 architecture audit. #1328 (1.4.29) fixed the other parts: repair backups and the rejected-suggestion cap. ## Affected package `long-term-memory` 1.4.38 (`upstream/staging` eb4af30d0), under `packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory/`: - `draft-store.ts`: `listDrafts` (270-292) reads and validates every draft file, then filters by status. - `retention.ts`: `runLongTermMemoryRetentionUnsafe`. Its five steps (131-226) prune quarantine, usage, receipts, events and incomplete generations, but not drafts. - `usage.ts`: `recordLongTermMemoryInjection` (107-160). - The only readers of `usage.chats` are retention step 2 (`retention.ts:144-178`) and the permanent-delete cleanup (`storage.ts:1299-1311`). ## Expected behavior - Finished drafts are removed after a while. Pending and invalidated drafts stay, because Review and Activity show those. - A reply does not rewrite data that nothing reads. ## Actual behavior 1. **Drafts.** - **Statuses.** A draft is `pending`, `accepted`, `auto_applied`, `superseded` or `invalidated`. - **What the UI asks for.** Only pending and invalidated drafts (`/drafts/pending-count`, and `/drafts/review?includeInvalidated=true` from Review and Activity). - **Deletion.** A draft file is deleted only when Review discards all of its changes (`draft-store.ts:406`, `routes.ts:1630`). Retention never deletes drafts. - **Who pays.** `listDrafts` parses every file before filtering. It runs on: - `/status`; - `/drafts/pending-count`, fetched when the screen opens (`LongTermMemoryDetail.tsx:56`); - each new extraction draft (`supersedeOlderPendingDrafts`, `draft-store.ts:243-244`); - the Review and Activity projections; - backups; - reference redirects after a rename or merge (`storage.ts:556`). 2. **`usage.json`.** - **On each reply that injects memories**, `recordLongTermMemoryInjection` (`usage.ts:114-143`), under the vault lock that recall also takes: - reads and validates the whole file; - updates `retrievalCount`, `injectionCount`, `totalInjectedTokens`, `lastRetrievedAt` and `lastInjectedAt` for every injected memory in that chat; - adds the receipt id to `acceptedReceipts`; - rewrites the whole file. - **Expiry.** Entries expire only after `usageRetentionDays` and `receiptRetentionDays`, both 180 by default. - **Readers.** No route or client code reads usage. `readLongTermMemoryUsage` is called only by retention, the permanent-delete cleanup and the writer itself. **Measured on one real vault** (a read-only copy taken 2026-10-08; aggregate counts only): | Store | Size | |---|---| | `drafts/` | 17 files from about 2 weeks of use: 1.2 MB, median 75 KB, largest 126 KB. None pending (9 superseded, 8 accepted), so each pending-count check parsed 1.2 MB to find nothing. | | `indexes/usage.json` | 918 KB after about 2.5 weeks and 38 chats. About 92% of its content is 1,975 per-memory counter entries; the 810 accepted receipt ids are about 55 KB. | Both grow with use: drafts without limit, usage counters for 180 days. ## Steps to reproduce 1. Use auto extraction in a chat for a few days, accepting drafts or letting newer ones supersede them. 2. Open `<dataDir>/long-term-memory/drafts/`. Every finished draft is still there, including after the daily retention run. 3. Send replies that inject memories and watch `indexes/usage.json` grow. Searching the package for `usage.chats` finds only retention and the delete cleanup. ## Environment - Marinara Engine version: 2.5.0 line (package range `>=2.4.1 <4.0.0`) - Package version: code read at long-term-memory 1.4.38 (`upstream/staging` eb4af30d0); sizes come from a vault written by earlier 1.4.x releases - Install type: source - OS + version: not platform-specific - Browser or app shell: any ## Logs, screenshots, or video See the size table above. It holds aggregate counts only, with no vault content. ## Additional context **Minimal fix, one commit each:** 1. **Prune finished drafts.** - Add a step 6 to `runLongTermMemoryRetentionUnsafe`. It deletes draft files whose status is `accepted`, `auto_applied` or `superseded` and whose `updatedAt` is older than `config.auditWindowDays` (30 by default). Reusing that existing retention field leaves the config schema unchanged. - Keep `pending` and `invalidated` drafts. Count removals in the result, as the other steps do. - `getDraft` already returns `null` for a missing file, and `subject-choice-review.ts:51` already returns `draft: null` when a resolved identity decision has no draft. Confirm the Review client handles `null` for a decision whose draft was pruned. - **Regression** in `tests/long-term-memory-storage.regression.ts`, beside the retention cases at 360-410: an accepted and a superseded draft older than the window are removed, while a recent accepted draft, a pending draft and an invalidated draft are kept. 2. **Stop writing per-memory usage counters.** - In `recordLongTermMemoryInjection`, stop updating `usage.chats` and write `chats: {}`. That drops the existing counters on the next reply. - Keep `acceptedReceipts` and the duplicate check as they are, so the dispatch result returned to the Engine does not change. - Retention step 2 and the delete cleanup then have nothing to do. Deleting them can be a follow-up. - Update the reserved-key test at `tests/long-term-memory-index-keys.regression.ts:693-715` to check `acceptedReceipts` only. - **Regression:** after two injected replies, `usage.json` has no per-memory entries, and a repeated accounting id still returns `null`. **Notes:** - No downgrade risk: the usage schema still requires `chats`, and an empty object is valid for older versions too. - Not covered: `acceptedReceipts` still gains one id per injected reply for `receiptRetentionDays` (about 55 KB in the sample). Shortening that window needs a check of what the Engine does with the dispatch result. - If per-memory recall counts are wanted later, for example for a "last recalled" column, they can come back together with a reader. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-20 17:29:59 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Agents#713
No description provided.