[Memory v2] 8 MiB recency prefilter can discard human evidence before provenance-tiered selection
Summary
Memory v2 has a selection-order gap: the shared recent-rollout reader applies an 8 MiB newest-first byte cap before v2's provenance-tiered selection runs.
That means v2's intended policy — human input and assistant final responses should outrank commentary/context/tool output — only applies to evidence that has already survived the recency prefilter. In a tool-heavy coding turn, low-priority tool output can fill the newest 8 MiB and make earlier human corrections or decisions completely invisible to v2 extraction.
Stage 1 can still succeed, so this is a silent completeness issue, not a context-window failure.
Why this looks like a regression in selection semantics
Memory v2 added source-priority selection in #43799 / commit 6924ce636b2186948f2332ac9460b5871b50aa2f:
"Select evidence by source so human input and assistant final responses take priority over commentary, context, and tool output."
Later, #53940 / commit 5670b1c18e861e5f89bafaff768b86ed579edd81 added a shared reader for both memory versions that scans newest-to-oldest and retains at most 8 MiB before v1/v2-specific serialization.
Current order is effectively:
full rollout
-> newest-first 8 MiB prefilter
-> v2 Human > Final > OtherAgent > Commentary > Context > Tool selection
-> Stage 1 model
So the Human-first guarantee is no longer global over the rollout.
Minimal synthetic reproduction
A minimal fixture does not need compaction or multiple rollout files.
Chronological records:
- early user message:
IMPORTANT_EARLY_CORRECTION: never modify the public API. - ten valid
function_call_outputrecords of about 900 KB each - latest user message:
LATEST_USER_MESSAGE
Each tool-output record is below the current 1 MiB per-record limit.
Mirroring the current reverse-scan byte accounting:
- total records: 12
- retained records: 10
- retained serialized bytes: ~8.10 MB
- latest user message: retained
- early human correction: not retained
At that point v2's provenance-tiered selector never sees the early correction, so it cannot prefer it over tool output.
Equivalent pseudo-test:
rollout =
[early_human_correction]
+ [~9 MB of individually-valid tool output]
+ [latest_human_message]
recent = read_recent_rollout_items(rollout)
assert latest_human_message in recent
assert early_human_correction not in recent
v2_input = serialize_tiered_input(recent, token_budget)
# impossible for the v2 selector to recover the missing human evidence
assert early_human_correction not in v2_input
A stronger regression test would assert the desired behavior instead: an earlier human correction should survive low-priority tool evidence when the overall extraction budget is bounded.
Why this matters for coding-agent sessions
Coding sessions are especially vulnerable because a small amount of high-value user intent can be followed by many megabytes of code reads, command output, test logs, and tool results.
For example:
user turn A -> code/tool activity
user turn B -> correction
user turn C -> >8 MiB tool-heavy execution
If Memory Stage 1 runs only after turn C, turns A/B can be absent from extraction even though v2 explicitly ranks human evidence above tool output.
Compaction summaries do not appear to repair this path because compacted records are excluded from memory extraction input.
Expected behavior
Bounded extraction is necessary, but resource bounding and evidence prioritization should not conflict.
Possible directions:
- Apply provenance-aware selection while scanning the whole bounded source stream, so Human/Final evidence has a reserved budget independent of Tool evidence.
- Maintain separate budgets/lanes (for example, always preserve bounded Human + Final evidence, then fill remaining budget with Commentary/Tool evidence).
- Chunk by complete turns/source ranges and checkpoint coverage before Phase 2.
- At minimum, surface incomplete coverage instead of marking Stage 1 successful without indicating that earlier high-priority evidence was never considered.
Simply increasing 8 MiB would postpone rather than solve the issue.
Relation to existing issues
- #38860 is about oversized rollouts causing Stage 1 context-window failures. The 8 MiB reader helps that failure mode.
- #61327 is about long-lived/paginated logical threads where Stage 1 reads only the latest physical rollout segment.
- This issue is different: a single rollout file can be read successfully and Stage 1 can succeed, while earlier high-priority human evidence is silently discarded because recency filtering happens before v2 provenance filtering.
Scope / proof limits
This report is based on the current source path plus a synthetic reproduction of the reader's byte-budget behavior. I did not run a full Codex binary or production memory database against a real private conversation.
The reproduction is structural: once the early human record is outside the shared 8 MiB prefilter, the downstream v2 selector has no code path to recover it.
The ordering claim holds at every line. The number that decides the fix is not the one in the report.
read_recent_rollout_items (memories/write/src/rollout_input.rs:35) walks the file newest to oldest through ReverseJsonlScanner, charges each surviving record serde_json::to_vec(&line.item)?.len() against MAX_ROLLOUT_BYTES (line 28, 8 MiB), and ends the whole scan on the first record that does not fit (remaining.checked_sub(..) else break, lines 74-77). serialize_tiered_input (line 105) tiers whatever survived, Human first. Nothing between the two re-reads the file. So the Human-first guarantee is scoped to what the recency scan already admitted, as reported.
Two parts of the premise are off, and both move the fix.
First, the fixture assumes ~900 KB tool records reach the reader. Two of the three tool routes are capped below that before they are durable: PERSISTED_MCP_RESULT_MAX_BYTES and PERSISTED_COMMAND_OUTPUT_MAX_BYTES are both 64 KB (rollout/src/policy.rs:17-18), applied in persisted_event_msg for Paginated history. A plain function_call_output response item goes through persisted_rollout_item (policy.rs:25) without truncation, so a large one is reachable that way, but it is not what the evidence on disk looks like. Largest rollout in my sessions directory is 6.10 MB on disk and persists 206 records totalling 1,435,332 bytes of serialized items, 17.1 percent of the prefilter budget, with 188 tool records averaging about 7.6 KB. The failure you report is real and it arrives by accumulation rather than by one giant record: at the 64 KB cap, 128 records fill 8 MiB.
Second, and this is the part the four directions circle without landing on: the prefilter charges records in bytes the selector will never spend. A row is cut to MAX_ROW_BYTES - TRUNCATION_RESERVE_BYTES = 9,904 bytes, and a tool row to TOOL_OUTPUT_TOKENS * 4 - 96 = 7,904 bytes (lines 91, 92, 245-264). One 900 KB tool record therefore spends 900 KB of the prefilter to contribute at most 7,904 bytes downstream. On your fixture, with your record counts:
persisted records 12 (10 tool, 2 user)
shipped charge 8,190,014 B (97.6% of 8 MiB) broke=true user rows lost=1
charged at row cap 79,267 B ( 0.9% of 8 MiB) broke=false user rows lost=0
spend ratio 103.32x, capacity rows {"shipped_at_64kb":128,"shipped_at_1mb":8,"at_row_cap":846}
8,190,014 bytes spent, the scan ends on budget, one human row gone. Charged at what a row can actually contribute, the same 12 records cost 79,267 bytes and nothing is lost.
So the charge should be min(serialized_len, MAX_ROW_BYTES - TRUNCATION_RESERVE_BYTES). It is one expression in the loop you already have, it changes nothing about tiering, and it makes the budget mean rows retained instead of bytes touched. Capacity goes from 128 records at the 64 KB cap to 846 at 9,904.
The break is the second defect and it is smaller than it looks, because the per-record cap already behaves the other way. A record over MAX_RECORD_BYTES is discarded by the scanner and the scan continues (discarding_oversized_record in reverse_jsonl_scanner.rs); a record under 1 MiB that does not fit the remaining budget ends the scan and abandons everything older, including 200 byte human rows that would have fit. Skipping the no-fit record and continuing to look for rows that do fit is the consistent behaviour, bounded by a skipped-bytes allowance if scan work is the concern.
That answers directions 1 and 2 as well. The selector does not need a reserved Human lane. Human is walked first against the entire remaining budget (lines 269-276), and a human row can never cost more than 9,904, while the stage-1 budget is DEFAULT_ROLLOUT_TOKEN_LIMIT 150,000 tokens (lib.rs:96) times 4 = 600,000 bytes, which about 61 human rows fill. Human evidence does not lose to tool evidence in the selector at any input. It only loses in the prefilter, which makes the prefilter the only place with a defect. Direction 3 is a rewrite of a pipeline that a charge unit fixes.
Direction 4 is nearly free. The loop already knows it broke and how many records it walked past, so that is one counter. The selector already knows per-tier cut counts through selected (lines 268-293). Both can ride on the stage-1 record as rows seen, rows retained, losses per tier, and whether the scan ended on the prefilter budget instead of the end of the file.
Your note that compaction summaries cannot repair this holds at both layers, which is worth stating precisely. RolloutItem::Compacted(_) => None in the selector (line 118), and should_persist_response_item_for_memories returns false for Compaction, ContextCompaction and Other (rollout/src/policy.rs:122-124), so the summary is not in the rollout that the reader opens at all. Reasoning is excluded the same way (line 119), so reasoning never consumes the prefilter either and the budget goes to tool output and text.
Fix order:
- charge
min(serialized_len, 9_904)in the prefilter - replace the no-fit
breakwith a bounded skip - carry coverage on the stage-1 record
Raising 8 MiB is not on that list. The prefilter already holds 14 times the 600,000 bytes the selector can render, so its size was never the binding constraint. The currency was.
Script to run it on any rollout, read only:
#!/usr/bin/env node
// node prefilter-coverage.mjs <rollout.jsonl>
import fs from 'node:fs';
const MAX = 8 * 1024 * 1024, REC = 1024 * 1024;
const ROW_CAP = 10_000 - 96, TOOL_CAP = 2_000 * 4 - 96;
const PERSISTED = new Set(['message','agent_message','local_shell_call','function_call','tool_search_call','function_call_output','tool_search_output','custom_tool_call','custom_tool_call_output','web_search_call']);
const TOOLISH = new Set(['function_call','tool_search_call','function_call_output','tool_search_output','custom_tool_call','custom_tool_call_output','web_search_call','local_shell_call']);
const recs = [];
for (const raw of fs.readFileSync(process.argv[2], 'utf8').split('\n')) {
if (!raw.trim()) continue;
let line; try { line = JSON.parse(raw); } catch { continue; }
if (line.type !== 'response_item') continue;
const item = line.payload;
if (!item || !PERSISTED.has(item.type)) continue;
if (item.type === 'message' && item.role === 'developer') continue;
const bytes = Buffer.byteLength(JSON.stringify(item), 'utf8');
if (bytes > REC) continue;
recs.push({ bytes, isTool: TOOLISH.has(item.type), isUser: item.type === 'message' && item.role === 'user' });
}
const scan = (charge) => {
let remaining = MAX, broke = false; const kept = new Set();
for (let i = recs.length - 1; i >= 0; i--) {
const r = recs[i];
const cost = charge === 'row' ? Math.min(r.bytes, r.isTool ? TOOL_CAP : ROW_CAP) : r.bytes;
if (cost > remaining) { broke = true; break; }
remaining -= cost; kept.add(i);
}
return { charged: MAX - remaining, broke, kept };
};
const shipped = scan('serialized'), fixed = scan('row');
const users = recs.map((r, i) => r.isUser ? i : -1).filter(i => i >= 0);
const lost = (s) => users.filter(i => !s.kept.has(i)).length;
console.log(`records ${recs.length}, user ${users.length}`);
console.log(`shipped ${shipped.charged} B (${(100*shipped.charged/MAX).toFixed(1)}%) broke=${shipped.broke} lost=${lost(shipped)}`);
console.log(`row cap ${fixed.charged} B (${(100*fixed.charged/MAX).toFixed(1)}%) broke=${fixed.broke} lost=${lost(fixed)}`);
process.exit(lost(shipped) ? 1 : 0);
It reproduces your fixture (97.6 percent charged, scan broke, one human row lost, 103x) and prints clean on four real rollouts here, 0.6 to 17.1 percent charged with nothing lost.
The reason this shape is worth fixing rather than widening is that a bounded extraction which reports success is worse than one that reports partial coverage, since the memory written from it looks complete. MemoryRouter is built on the same premise at the other end: agents keep conversational memory across sessions and survive compaction, so what a bounded read drops has to be visible rather than inferred from a summary that never arrived. If you want the coverage side of this handled without patching Stage 1, that is what it does: https://docs.memoryrouter.ai/codex?utm_source=github&utm_medium=issue&utm_campaign=openai-codex