[GH-ISSUE #946] [Issue]: LTM bounded candidate recovery and output slimming (I09, I12) #497

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

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

Originally assigned to: @Promansis on GitHub.

Summary

Long-Term Memory discards an entire extraction when the provider reports an output-token limit, even if complete evidence units precede the truncated tail. A response exceeding the candidate cap likewise loses every candidate. Meanwhile, the generation contract requires per-unit IDs and source hashes that the server immediately replaces.

Implement bounded candidate recovery and output slimming together (phase 6, I09/I12): preserve complete, validated candidates as an explicitly incomplete draft and stop requiring redundant model-generated metadata.

Affected package

long-term-memory — package-owned server extraction and the directly affected shared accounting/schema contracts.

Expected behavior

  • On length, max_tokens, or token_limit, recover only syntactically complete objects from the top-level units array. Discard an unfinished candidate; never complete a string, field, nested value, or claim by guessing. Continue through existing identity, evidence, scope, deduplication, and graph validation.
  • A recoverable batch produces a partial draft and an explicit incomplete-output diagnostic. It must never mark the source current or trigger automatic application gated on a complete extraction, including when the JSON is already valid, every retained unit passes, or retained units all deduplicate.
  • Process at most LTM_EXTRACTION_MAX_CANDIDATES (currently 999) provider candidates in their original order. Report overflow without failing the whole extraction; keep rejection details bounded by LTM_EXTRACTION_MAX_REJECTION_DETAILS (currently 80).
  • Remove id and sourceHash from the model generation fields and response schema. Preserve the server's deterministic ID and authoritative source hash. If evidence is omitted, populate it from the trusted source-note context before schema validation; explicitly supplied invalid evidence must still fail the existing checks.
  • Make the generated schema compatible with the intended structured-output subset, while retaining server-side semantic validation and the existing bounded provider compatibility fallbacks.

Actual behavior

Confirmed by source inspection at aa2b391e1cfc3b86bcc68d6f82412a8364ac9b43:

  • runLongTermMemoryEvidenceUnitExtraction() throws ltm_model_output_truncated before parsing any content for all three token-limit finish reasons.
  • parseEvidenceUnitPayload() throws when input.units.length > 999; the extraction wrapper converts this to ltm_model_output_unusable.
  • evidenceUnitResponseFormat() requires id, sourceHash, and evidence. normalizedEvidenceUnitRecord() already replaces the first two, but does not supply omitted evidence. evidenceUnitMessages().unitFields also asks for these fields.
  • The generated schema uses strict: false, conditional allOf / if / then / not blocks, and optional properties. Removing conditionals alone does not establish strict-provider compatibility.
  • Current regressions intentionally assert whole-response rejection for overflow. The truncated-output fixture has no complete unit, so it does not cover recoverable output.

Steps to reproduce

The following are synthetic regression cases to execute during implementation; they were derived from source and existing fixtures, not run for this issue:

  1. Use the fixture model in tests/long-term-memory-extraction-reliability.regression.ts. Return an envelope with one complete, otherwise-valid unit followed by an unfinished second object, with finishReason: "length". Current code throws before considering the complete unit. A fully valid envelope with the same finish reason also throws.
  2. Return a valid units array of 1,000 candidates with finishReason: "stop". Current code rejects the whole response with the maximum-candidate error. This rejection is already asserted in both extraction reliability and extraction graph suites.
  3. Inspect evidenceUnitResponseFormat() and the generated unitFields: both request metadata overwritten server-side. Omit evidence from an otherwise-valid candidate and the current per-unit schema rejects it before a trusted-source default can be supplied.

Environment

  • Marinara Engine version: no running Engine used; package manifest declares >=2.4.1 <4.0.0 and builtAgainst.engineVersion: 2.4.1.
  • Package version: 1.3.4 in the inspected manifest.
  • Install type: source inspection of Marinara-Agents staging.
  • OS + version: Linux; distribution/version not collected.
  • Browser or app shell: not applicable.

Logs, screenshots, or video

No live-provider logs, private chat data, or screenshots were used. Evidence is code and existing test assertions, not an executed reproduction.

Let ltm/ mean packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory/ and shared/ mean packages/long-term-memory/src/engine/packages/shared/src/features/agents/long-term-memory/.

Evidence Inspected location
Model response schema, overwritten IDs/hashes, overflow rejection ltm/evidence-unit-extraction.ts:274–402,483–510,712–762
Generated field contract and token-limit rejection before parsing ltm/evidence-unit-extraction.ts:935–964,1124–1147
Parser accounting through identity resolution and compilation ltm/source-extraction.ts:520–595
Freshness and automatic-application gates ltm/source-processing.ts:75–84,242–262
Mandatory evidence/source hash and bounded, balanced accounting shared/schema.ts:806–829,2092–2173
Existing overflow and unusable-output assertions tests/long-term-memory-extraction-graph.regression.ts:822–848; tests/long-term-memory-extraction-reliability.regression.ts:98–149

GitHub comparison against upstream staging at 40fe81f61c7150e73e15e80a4938986f9d2390cc showed one additional commit and no changes to the LTM package, referenced tests, issue templates, or contribution guidance. Focused issue/PR searches found no matching outstanding recovery/output-slimming work.

Additional context

Validated scope and implementation constraints

  1. Recovery is local and conservative. Reuse ordinary JSON parsing first. A recovery scan must respect quoted strings, escapes, nested objects/arrays, and top-level array boundaries; it must not scrape arbitrary embedded objects or repair malformed non-truncated responses. Bound recovery work and retained output. No additional model repair/completion call. If no complete usable units are recoverable, retain the existing explicit failure and retryable-source behavior.
  2. Incompleteness survives the entire pipeline. A partial state alone is insufficient: canMarkCurrent() currently permits partial_success with zero drops for clean deduplication. Carry the token-limit/overflow signal through normalization, compilation, draft finalization, and single/batch processing, using the smallest existing mechanism that preserves this distinction. Do not manufacture a candidate rejection solely to encode an unknown truncated tail.
  3. Overflow accounting must be schema-valid. Shared outcome counts, accounting counts, and candidate indices currently cap at 999, and accounting enforces providerCandidates + normalizedAdditions == parserRejections + validationRejections + deduplications + keptUnits. Simply slicing the array and passing the original count downstream will still fail. Define explicit bounded overflow reporting, preserve truthful counts and balance, and keep draft/API persistence valid. Test structured backfill combined with near-cap provider input. Do not silently clamp away discarded work or raise the processing cap as the fix.
  4. Trusted metadata remains server-owned. Reuse deterministic ID generation and source evidence helpers. Populate omitted evidence only when the caller supplies trusted source context; do not derive provenance from model fields. Equivalent minimal and legacy responses should normalize consistently, including repeated extraction/deduplication. Leave the internal evidence-unit validation contract intact.
  5. Strictness is a proved contract, not a flag change. Flatten unsupported conditionals while preserving bucket/participant constraints in server validation. Cover both subject-name resolution modes and nested optional fields, including relationship dimensions and link aspects. Prove schema acceptance for the supported provider subset before enabling strict mode; do not claim strict support based on JSON validity or strict: true alone. Preserve the merged independent response-format/reasoning fallbacks.
  6. Keep prompt work separated. Align the generated machine-readable unitFields with the schema. Free-form extraction/summary prompt edits and the final DEFAULT_LTM_EXTRACTION_PROMPT constants pass remain outside this issue. Current packaged prompts still instruct the model to emit evidence/source hashes; record that limitation and coordinate the maintainer's Engine prompt updates before claiming end-to-end token savings.

Acceptance and regression proof

  • All three token-limit finish reasons preserve complete preceding units, discard the unfinished tail, and leave the source non-current. Cover an already-valid envelope, cutoff between units, nested links/dimensions, quoted braces, escaped quotes/backslashes, and no recoverable unit.
  • Malformed non-truncated output still fails; recovery invents no content or provenance and makes no extra model call. Existing cancellation and provider compatibility fallback cases remain valid.
  • Exactly-at-cap and over-cap responses complete with bounded processing and honest diagnostics. More than 80 rejected/overflow candidates do not expand detailed diagnostics beyond their cap. Accounting, indices, draft serialization, and route response schemas remain valid, including normalized additions.
  • A retained unit whose required event was truncated or excluded still fails graph validation; identity ambiguity, scope isolation, evidence, hash, and source-event requirements remain enforced.
  • Partial results cannot acquire a current fingerprint or auto-apply in single and batch paths, including zero retained mutations and all-deduplicated recovery. Complete clean deduplication continues to mark sources current.
  • Minimal units without model IDs/hashes/omitted evidence receive deterministic trusted metadata before validation. Explicitly malformed or wrong-source evidence is rejected; legacy metadata cannot override server values.
  • Generated schema and machine-readable field descriptions omit redundant metadata. Provider-schema compatibility is checked explicitly for all supported shapes; any live-provider verification gap is stated.
  • Update the existing overflow-rejection expectations only for this authorized behavior change; retain no-extra-repair-call and unrecoverable-output assertions.

Primary regression owners: tests/long-term-memory-extraction-reliability.regression.ts and tests/long-term-memory-extraction-graph.regression.ts. Extend the existing source/finalization cases and the focused imports/drafts cases in tests/long-term-memory-routes.regression.ts where needed for persistence and API proof.

Before implementation, complete Marinara Start/resume and establish the contract-sensitive baseline in the issue-linked workspace. Run the focused regressions first, then the required LTM and repository gates, rebuild the affected package/catalog through their builders, and verify the resulting artifact. No tests, builds, provider calls, install checks, or implementation edits were performed for this issue validation.

Baseline dependencies are already merged: #898 (source update fixes), #920 (context/freshness handling), and #938 / #935 (independent provider fallbacks and output viability). Preserve those behaviors; do not reimplement them. Exclude retryability cleanup, batch caching, identity repair, prompt redesign, and new recovery services from this phase.

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 (Sep 19, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/946 Originally assigned to: @Promansis on GitHub. ## Summary Long-Term Memory discards an entire extraction when the provider reports an output-token limit, even if complete evidence units precede the truncated tail. A response exceeding the candidate cap likewise loses every candidate. Meanwhile, the generation contract requires per-unit IDs and source hashes that the server immediately replaces. Implement bounded candidate recovery and output slimming together (phase 6, I09/I12): preserve complete, validated candidates as an explicitly incomplete draft and stop requiring redundant model-generated metadata. ## Affected package `long-term-memory` — package-owned server extraction and the directly affected shared accounting/schema contracts. ## Expected behavior - On `length`, `max_tokens`, or `token_limit`, recover only syntactically complete objects from the top-level `units` array. Discard an unfinished candidate; never complete a string, field, nested value, or claim by guessing. Continue through existing identity, evidence, scope, deduplication, and graph validation. - A recoverable batch produces a partial draft and an explicit incomplete-output diagnostic. It must never mark the source current or trigger automatic application gated on a complete extraction, including when the JSON is already valid, every retained unit passes, or retained units all deduplicate. - Process at most `LTM_EXTRACTION_MAX_CANDIDATES` (currently 999) provider candidates in their original order. Report overflow without failing the whole extraction; keep rejection details bounded by `LTM_EXTRACTION_MAX_REJECTION_DETAILS` (currently 80). - Remove `id` and `sourceHash` from the model generation fields and response schema. Preserve the server's deterministic ID and authoritative source hash. If evidence is omitted, populate it from the trusted source-note context before schema validation; explicitly supplied invalid evidence must still fail the existing checks. - Make the generated schema compatible with the intended structured-output subset, while retaining server-side semantic validation and the existing bounded provider compatibility fallbacks. ## Actual behavior Confirmed by source inspection at `aa2b391e1cfc3b86bcc68d6f82412a8364ac9b43`: - `runLongTermMemoryEvidenceUnitExtraction()` throws `ltm_model_output_truncated` before parsing any content for all three token-limit finish reasons. - `parseEvidenceUnitPayload()` throws when `input.units.length > 999`; the extraction wrapper converts this to `ltm_model_output_unusable`. - `evidenceUnitResponseFormat()` requires `id`, `sourceHash`, and `evidence`. `normalizedEvidenceUnitRecord()` already replaces the first two, but does not supply omitted evidence. `evidenceUnitMessages().unitFields` also asks for these fields. - The generated schema uses `strict: false`, conditional `allOf` / `if` / `then` / `not` blocks, and optional properties. Removing conditionals alone does not establish strict-provider compatibility. - Current regressions intentionally assert whole-response rejection for overflow. The truncated-output fixture has no complete unit, so it does not cover recoverable output. ## Steps to reproduce The following are synthetic regression cases to execute during implementation; they were derived from source and existing fixtures, not run for this issue: 1. Use the fixture model in `tests/long-term-memory-extraction-reliability.regression.ts`. Return an envelope with one complete, otherwise-valid unit followed by an unfinished second object, with `finishReason: "length"`. Current code throws before considering the complete unit. A fully valid envelope with the same finish reason also throws. 2. Return a valid `units` array of 1,000 candidates with `finishReason: "stop"`. Current code rejects the whole response with the maximum-candidate error. This rejection is already asserted in both extraction reliability and extraction graph suites. 3. Inspect `evidenceUnitResponseFormat()` and the generated `unitFields`: both request metadata overwritten server-side. Omit `evidence` from an otherwise-valid candidate and the current per-unit schema rejects it before a trusted-source default can be supplied. ## Environment - Marinara Engine version: no running Engine used; package manifest declares `>=2.4.1 <4.0.0` and `builtAgainst.engineVersion: 2.4.1`. - Package version: `1.3.4` in the inspected manifest. - Install type: source inspection of Marinara-Agents `staging`. - OS + version: Linux; distribution/version not collected. - Browser or app shell: not applicable. ## Logs, screenshots, or video No live-provider logs, private chat data, or screenshots were used. Evidence is code and existing test assertions, not an executed reproduction. Let `ltm/` mean `packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory/` and `shared/` mean `packages/long-term-memory/src/engine/packages/shared/src/features/agents/long-term-memory/`. | Evidence | Inspected location | | --- | --- | | Model response schema, overwritten IDs/hashes, overflow rejection | `ltm/evidence-unit-extraction.ts:274–402,483–510,712–762` | | Generated field contract and token-limit rejection before parsing | `ltm/evidence-unit-extraction.ts:935–964,1124–1147` | | Parser accounting through identity resolution and compilation | `ltm/source-extraction.ts:520–595` | | Freshness and automatic-application gates | `ltm/source-processing.ts:75–84,242–262` | | Mandatory evidence/source hash and bounded, balanced accounting | `shared/schema.ts:806–829,2092–2173` | | Existing overflow and unusable-output assertions | `tests/long-term-memory-extraction-graph.regression.ts:822–848`; `tests/long-term-memory-extraction-reliability.regression.ts:98–149` | GitHub comparison against upstream `staging` at `40fe81f61c7150e73e15e80a4938986f9d2390cc` showed one additional commit and no changes to the LTM package, referenced tests, issue templates, or contribution guidance. Focused issue/PR searches found no matching outstanding recovery/output-slimming work. ## Additional context ### Validated scope and implementation constraints 1. **Recovery is local and conservative.** Reuse ordinary JSON parsing first. A recovery scan must respect quoted strings, escapes, nested objects/arrays, and top-level array boundaries; it must not scrape arbitrary embedded objects or repair malformed non-truncated responses. Bound recovery work and retained output. No additional model repair/completion call. If no complete usable units are recoverable, retain the existing explicit failure and retryable-source behavior. 2. **Incompleteness survives the entire pipeline.** A partial state alone is insufficient: `canMarkCurrent()` currently permits `partial_success` with zero drops for clean deduplication. Carry the token-limit/overflow signal through normalization, compilation, draft finalization, and single/batch processing, using the smallest existing mechanism that preserves this distinction. Do not manufacture a candidate rejection solely to encode an unknown truncated tail. 3. **Overflow accounting must be schema-valid.** Shared outcome counts, accounting counts, and candidate indices currently cap at 999, and accounting enforces `providerCandidates + normalizedAdditions == parserRejections + validationRejections + deduplications + keptUnits`. Simply slicing the array and passing the original count downstream will still fail. Define explicit bounded overflow reporting, preserve truthful counts and balance, and keep draft/API persistence valid. Test structured backfill combined with near-cap provider input. Do not silently clamp away discarded work or raise the processing cap as the fix. 4. **Trusted metadata remains server-owned.** Reuse deterministic ID generation and source evidence helpers. Populate omitted evidence only when the caller supplies trusted source context; do not derive provenance from model fields. Equivalent minimal and legacy responses should normalize consistently, including repeated extraction/deduplication. Leave the internal evidence-unit validation contract intact. 5. **Strictness is a proved contract, not a flag change.** Flatten unsupported conditionals while preserving bucket/participant constraints in server validation. Cover both subject-name resolution modes and nested optional fields, including relationship dimensions and link aspects. Prove schema acceptance for the supported provider subset before enabling strict mode; do not claim strict support based on JSON validity or `strict: true` alone. Preserve the merged independent response-format/reasoning fallbacks. 6. **Keep prompt work separated.** Align the generated machine-readable `unitFields` with the schema. Free-form extraction/summary prompt edits and the final `DEFAULT_LTM_EXTRACTION_PROMPT` constants pass remain outside this issue. Current packaged prompts still instruct the model to emit evidence/source hashes; record that limitation and coordinate the maintainer's Engine prompt updates before claiming end-to-end token savings. ### Acceptance and regression proof - [ ] All three token-limit finish reasons preserve complete preceding units, discard the unfinished tail, and leave the source non-current. Cover an already-valid envelope, cutoff between units, nested links/dimensions, quoted braces, escaped quotes/backslashes, and no recoverable unit. - [ ] Malformed non-truncated output still fails; recovery invents no content or provenance and makes no extra model call. Existing cancellation and provider compatibility fallback cases remain valid. - [ ] Exactly-at-cap and over-cap responses complete with bounded processing and honest diagnostics. More than 80 rejected/overflow candidates do not expand detailed diagnostics beyond their cap. Accounting, indices, draft serialization, and route response schemas remain valid, including normalized additions. - [ ] A retained unit whose required event was truncated or excluded still fails graph validation; identity ambiguity, scope isolation, evidence, hash, and source-event requirements remain enforced. - [ ] Partial results cannot acquire a current fingerprint or auto-apply in single and batch paths, including zero retained mutations and all-deduplicated recovery. Complete clean deduplication continues to mark sources current. - [ ] Minimal units without model IDs/hashes/omitted evidence receive deterministic trusted metadata before validation. Explicitly malformed or wrong-source evidence is rejected; legacy metadata cannot override server values. - [ ] Generated schema and machine-readable field descriptions omit redundant metadata. Provider-schema compatibility is checked explicitly for all supported shapes; any live-provider verification gap is stated. - [ ] Update the existing overflow-rejection expectations only for this authorized behavior change; retain no-extra-repair-call and unrecoverable-output assertions. Primary regression owners: `tests/long-term-memory-extraction-reliability.regression.ts` and `tests/long-term-memory-extraction-graph.regression.ts`. Extend the existing source/finalization cases and the focused imports/drafts cases in `tests/long-term-memory-routes.regression.ts` where needed for persistence and API proof. Before implementation, complete Marinara Start/resume and establish the contract-sensitive baseline in the issue-linked workspace. Run the focused regressions first, then the required LTM and repository gates, rebuild the affected package/catalog through their builders, and verify the resulting artifact. No tests, builds, provider calls, install checks, or implementation edits were performed for this issue validation. Baseline dependencies are already merged: #898 (source update fixes), #920 (context/freshness handling), and #938 / #935 (independent provider fallbacks and output viability). Preserve those behaviors; do not reimplement them. Exclude retryability cleanup, batch caching, identity repair, prompt redesign, and new recovery services from this phase. ## 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:28:04 +07:00
  • closed this issue
  • added the
    bug
    label
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#497
No description provided.