Repository navigation
feat(external-memory): tighten editSummaryText and rewrite carriers - #506
nissa-seru wants to merge 16 commits into
Conversation
These tests fail at the base. They pin the editSummaryText of the next commit. - An entry can carry another summary up a level (carriedFrom). An edit of that entry is refused. A compile reads the carried summary's text in the entry's place, so the edit would never show. The error names the carried summary by its id. - An edit of the carried summary reports the entries that carry it, two levels up too, and one whose summary doesn't point to it. It reports them apart from the summaries merged over the old text. It writes each carrier again as a copy of the edited summary: its text, tokens and external, with no response blocks and no provenance. - A summary can render verbatim response blocks. An edit of it is refused unless the edit drops them (dropResponseContent, or --drop-response-content in the CLI). A dry run is refused too, and nothing is written. So is an edit where only a carrier holds such blocks, and the drop deletes them from the carrier. - The caller can give the sha256 of the text that it read (expectedPriorSha256). The edit is refused where the summary's text has another sha256. - The summary and its carriers go in one write of the summaries. Where that write fails before it lands, neither changes, in memory or in the store, and the edit can be asked for again. A write can also land and then throw. The strategy then holds the new text, and an edit asked for again finds that text. Where reading the store back fails, the strategy refuses work until it is initialized again. - The edit is refused, and writes nothing, where the stored summaries aren't as the strategy holds them: the summary or a carrier is gone, or another handle wrote a newer text. It is refused too where reading them to compare fails. - A summary edited again to a text of the same length is priced by its new text, and so is one that the strategy takes up from the store after another handle wrote it. The two existing tests that edit a summary with response blocks now pass --drop-response-content.
The rules of a summary edit move into one pure function, planSummaryEdit in src/summary-edit.ts, which the strategy's editSummaryText uses. - An edit of a carrier (carriesItsSource) is refused. A compile renders the carried summary's text in the carrier's place (summaryAnswerProse). So the carrier's own copy never shows. The error names that summary by its id. If that summary is gone, the carrier's own text renders (carriedMemory), and the edit goes ahead. - A summary's responseContent renders in place of its content (summaryAnswerProse). So an edit that kept it would still show the old text. The edit used to delete it silently. Now such an edit needs dropResponseContent (in the CLI, --drop-response-content). Without it, the edit is refused, and so is a dry run. The count takes the response blocks of each entry that carries the summary too, since those go with the text. - expectedPriorSha256 refuses the edit if the summary's text isn't the text that the caller read. - The new text's token stamp is its length divided by three. This is the rule for a text that no provider measured, and an imported summary gets it too. The old stamp is usually the provider's outputTokens. That count includes reasoning blocks, which dropResponseContent removes. A stamp scaled from it would misprice the new text. - Each carrier is written again as a copy of the edited summary, in the same write of the summaries as the summary itself, so the two never part. A carrier is found up the parent pointers, and also where it carries the summary and the summary doesn't point to it, as a carry that failed halfway can leave. The copy has the summary's text, tokens and external, and no responseContent, provenance or stitched. carry() would make the same copy now. A carrier's own fields still count in two places. The legacy level budgets charge a carrier's own tokens. And under carrierPolicy 'full', recallAnswerCost prices a carrier with response blocks at its old stamp or more. - A write that throws says whether it landed, as the strategy reads the store back. Where it landed, the strategy holds the new text. Where it didn't, the strategy and the store hold the old text, and the edit can be asked for again. Where the read back fails, the strategy can't say which, so it refuses work until it is initialized again. - Before it writes, the edit checks that the stored summaries and chunk records are the ones that the strategy holds (storeWrittenElsewhere). It is refused where another handle wrote them since, and where reading them fails. For this check alone, a failed read now counts as a difference. Each refusal says that the edit is refused and that nothing was written. - An applied edit clears the memo of recall-answer prices, and so does taking up summaries from the store. The memo's key is the summary's id and tokens. An edit to a text of the same length changes neither. - SummaryTextEdit splits the parent chain in two. carriedBy lists the carriers next to the summary. parents lists the summaries merged over the old text, and every summary above them. Before, parents listed the carriers too. The pending external-memory changelog fragment changes in place. The feature isn't released yet, so its text describes the behaviour as it ships.
|
Automatic context view of What a context view runs and what its checks judge: CHECKS.md. The records of the 79 runs it could compare don't differ between the base and this head. In the files profiled hosts loaded, 111 changed source lines that map to code ran in no profiled drive: Parts left out where an arm's stack doesn't bring what they need: 2 runs couldn't be compared; the reasons are below. Usage: the figures of the agents' requests, subagents' included, in the 79 runs are the same in the base and this head: 209,982 tokens sent a request, 72.2% of them read from the cache, 138,491,709 written to it, 3,969,133 output, 24 thinking blocks dropped, USD 0.5588 at list price a priced request and 123 requests with no list price. The figures are the stand-in's model of each provider's published caching and token rules, not a measurement. Two drives of one tree have given the same figures, so a difference between the arms comes from what differs in the code each arm ran. A list price is what each arm's host prices those figures at with its own table (connectome-host's Runs that couldn't be compared (2)This head couldn't be compared at This head couldn't be compared at Upgraded runs beside their fresh twins
A run that writes its own history first, as a fresh twin does, is shown without that history's requests, so its figures are its workload's alone, as the upgraded runs' are. Changed source lines and deletions not seen to run, by file
Held the same in base and head: connectome-host |
|
Automatic review of About these findingsThe findings below came from reading this PR and relevant code; not a holistic understanding of the project's functional intent and its architecture choices. Finding precision is higher for flagging issues than identifying ideal changes/fixes. This review prioritizes recall - minor findings (in particular) may be nits. Before actioning a finding, consider the relevant code from first principles given the functional+architectural intent. In particular, when considering adding machinery/logic, scrutinize whether the incremental value of such pays rent for the complexity it adds to the codebase - kudzu has a direct negative impact on our future ability to work with the codebase. Consider explicitly mentioning which findings you accept/decline (by code-formatted numerical id) and why; this enables future rounds of automated review to take your notes into account. Findings, most severe first:
|
These tests answer the automatic review of 8a14c2d, and each pins what that head already does. A carrier two levels up is rewritten too. The carrier fixture copies the summary's provenance, as a carry does, so the test that the edit drops it can fail. A write that lands and then throws, with a read back that fails, leaves the strategy refusing work, and once initialized again it holds the new text. An edit refused for a carrier's own response blocks writes nothing.
The CLI's dry run says which response blocks the edit would drop and which carriers would read the new text, rather than as if it had happened. An edit of a summary that isn't there, and an edit to an empty text, each say that the edit is refused and that nothing was written. The second says to give a text that isn't blank. planSummaryEdit no longer scans for a carrier that its summary doesn't point to. The load gives each summary its parent pointer back where exactly one entry a level up lists it (settle-summaries), so such a carrier exists only in the session in which a carry failed halfway, and there a compile still renders the summary's text in the carrier's place. The scan found only a carrier one level up, and a walk above it would add more for that one case.
|
This answers the automatic review of Details for agentsHead
Runs, each on a clean checkout: at — Paloma-2644 |
A dry run of an edit is refused where the stored summaries aren't as the strategy holds them, as the apply is. The CLI's dry run names the old text's sha256 in the line that says how to apply, and an apply with --expected-prior-sha256 for another text is refused and writes nothing.
editSummaryText makes its check of the stored summaries and chunk records before it returns a dry run's answer, so that a dry run gives the answer that the apply would give. The CLI's edit takes --expected-prior-sha256, which it passes as expectedPriorSha256, and its dry run says to apply with the sha256 of the text it showed. Two invocations of the CLI are then bound to one text of the summary.
The dry run shows the old text's sha256 and length, not the text, so its last line now says that the apply command applies the edit only where the summary still holds the old text that the dry run read. The header of scripts/external-memory.ts names --expected-prior-sha256.
Main released 0.29.0, which folded the pending fragment that this pull request edited (changelog.d/external-memory-import.added.md). So the change's entries are now fragments of its own, against 0.29.0: a breaking one for the edits that are now refused, a fixed one for the carriers and the write, and an added one for the new options.
Main released 0.29.0, which folded the fragment changelog.d/external-memory-import.added.md. This pull request had described there the editSummaryText fixes that it carries. Those fixes are anima-research#506's, whose own fragments come in when it merges and main merges in here again. So the merge drops this branch's edit of the folded fragment. Main also admits chronicle 0.8, which undoes a branch change whose checkpoint fails, and its selectBranch comment says so. selectBranch keeps this branch's form, and its comment names the chronicles that keep such a selection (0.6, 0.7) and the one that undoes it (0.8). The tests of a real failed checkpoint ask the chronicle that they run on which it does: each runs where it holds, and a new one runs where the switch is undone (the apply deletes the branch that it built, and the store stays on the source).
In 0.29.0, SummaryTextEdit.parents listed every summary up the parent pointers, the entries that carry the edited summary included. The change lists those entries in carriedBy instead, so a caller who read parents for every entry that an edit reaches now reads both. The breaking fragment says so, and how to migrate.
SummaryTextEdit.carriedBy is a required field, so a strategy that implements ExternalMemoryStrategy's editSummaryText returns it too, an empty list where nothing carries the edited summary. The breaking fragment says so.
Anarchid
left a comment
There was a problem hiding this comment.
Nightly dual review · round R1 at 8f84f25 · reviewers: Codex gpt-5.6-sol (xhigh) and Claude claude-opus-5-5, merged and every claim re-verified by the Claude leg · posted by the maintainer's campaign runner. Verdict: CHANGES_REQUESTED (the formal review event is left to the maintainer). Finding ids R1-n are stable; cite them in fix commits.
Reviewed at 8f84f25 against main 87cbd1b
Verdict: changes requested. There is one blocker (R1-1) and four minors.
The edit rules are sound: they match how a compile renders carriers and verbatim response blocks, and the write and read-back are careful. The blocker is something the change doesn't claim to touch. editSummaryText now replaces the held summary objects instead of changing them in place, and executeMerge still marks the source objects it took before its provider call. So an applied edit of a merge's source is silently reverted when that merge lands. On 0.29.0 the same race keeps the edit. Separately, the description says #505 builds on this PR, but #505 holds an older copy of this change (R1-2).
There is no earlier review of ours on this PR.
Blocker
R1-1. An applied edit of a merge's source is reverted when the merge lands (a regression from 0.29.0).
executeMergetakes its sources as the held objects when it starts (src/strategies/autobiographical.ts:14926) and then awaits the provider (:15573,:15610). After the call it checks again only whether a source was parented, dropped or moved (mergeOvertakenDuringCall,:15635; the dropped check goes by id,:9978). It then callssetMergedInto(source, newEntry.id)on the objects it took (:15765).setMergedIntosetsmergedIntoon the object it is given (:7583), andwriteStoredSummarywrites that whole object over every stored copy with its id (:7610).- On main,
editSummaryTextchanged the held entry in place (entry.content = body…, thenwriteStoredSummary), so the object a merge had taken was the edited one. At this head it builds new objects (:16070) and replacesthis.summaries(:16098). The object the merge took still has the old text, response blocks and provenance. - What happens: the merge writes the old copy over the edited one in the store. The held entry, which is the new object, gets no
mergedInto, so its group is queued again. At its entry check, the next attempt finds the sources parented in the store (:14944) and takes up the store's state (:10035), old text included. The edit returnedapplied: true, and nothing logs that it was undone. - The same write goes through a carrier. Take summary A, carried by B, where B is a source of an L3 merge whose call is out. Editing A rewrites A and B. When the merge lands, B's old copy (old tokens and response blocks) goes back while A keeps the new text. That breaks the description's "so they never part". This case follows from the same code; I didn't run it.
- Who can hit it: any caller of
ContextManager.editSummaryTexton a manager whose strategy is ticking. That includes #505'sapplyPlannedOps, which callseditSummaryText({ apply: true, … })on the manager's own strategy. The CLI can't hit it: it opens the store itself, and the store's lock keeps a running resident out. - Repro (below): ten L1s and a merge call held open. Every unparented L1 is edited with
{ apply: true, dropResponseContent: true }while the call is out, then the call is released. At this head, L1-0..2 (the merge's sources) readnative memory 0..2in memory, in the store and after a reopen, while L1-3..9 keep the edit. At 87cbd1b (0.29.0) all ten keep the edit. With the one-line change below applied to the compiled head, all ten keep it again. - Fix: mark the held entry, not the one the merge took:
this.setMergedInto(this.summaryById(source.id) ?? source, newEntry.id)at:15765. Better still,mergeOvertakenDuringCallcould treat a source whose text changed while the call was out as overtaken: compare a sha256 taken at entry. The merge's text was written over the old text, and the edit'sparentscouldn't name a merge that hadn't landed yet. Another option is to keep object identity ineditSummaryTextby assigning into the held entries once the write lands. Whichever you choose, add a test that edits a source while a merge's call is held open.
Repro (run from the repository root after npx tsc -p .)
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ContextManager, AutobiographicalStrategy } from './dist/src/index.js';
import { residentStrategyOptions } from './dist/scripts/resident-settings.js';
const NS = 'agents/Ada';
const SETTINGS = { mergeThreshold: 3, headWindowTokens: 0, recentWindowTokens: 0, compressionRefusalCurveFallbacks: 0, l1HoldbackChunks: 0 };
const RESIDENT = { ...residentStrategyOptions(SETTINGS, 'same-model', 'Ada'), targetChunkTokens: 100, quarantineAlarmIntervalMs: 0, mergeAttemptLimit: 1 };
let minted = 0;
const answer = () => ({ stopReason: 'end_turn', content: [{ type: 'text', text: `native memory ${minted++}` }], usage: { inputTokens: 100, outputTokens: 30 } });
const dir = mkdtempSync(join(tmpdir(), 'edit-during-merge-'));
const path = join(dir, 'store');
try {
// Ten L1s, no merge yet.
const seed = await ContextManager.open({ path, namespace: NS, strategy: new AutobiographicalStrategy({ ...RESIDENT, mergeThreshold: 99 }), membrane: { complete: async () => answer() } });
for (let i = 0; i < 40; i++) seed.addMessage(i % 2 ? 'Ada' : 'User', [{ type: 'text', text: `raw-${i} ${'substantive '.repeat(12)}` }]);
await seed.compile();
for (let i = 0; i < 12; i++) await seed.tick();
seed.close();
// Merges on; the provider call waits until released.
let release, entered;
const gate = new Promise((r) => { release = r; });
const out = new Promise((r) => { entered = r; });
const strategy = new AutobiographicalStrategy({ ...RESIDENT, autoTickOnNewMessage: false });
const manager = await ContextManager.open({ path, namespace: NS, strategy, membrane: { complete: async () => { entered(); await gate; return answer(); } } });
const ticking = (async () => { for (let i = 0; i < 4; i++) await manager.tick(); })();
await out;
const edited = strategy.summaries.filter((s) => s.level === 1 && !s.mergedInto && !s.parentId).map((s) => s.id);
for (const id of edited) manager.editSummaryText(id, `EDITED ${id}`, { by: 'repro' }, { apply: true, dropResponseContent: true });
release();
await ticking;
const stored = new Map(strategy.store.getStateJson(`${NS}/autobio:summaries`).map((s) => [s.id, s.content]));
manager.close();
const reopened = new AutobiographicalStrategy(RESIDENT);
(await ContextManager.open({ path, namespace: NS, strategy: reopened, membrane: { complete: async () => answer() } })).close();
for (const id of edited) {
console.log(`${id}: memory ${JSON.stringify(strategy.summaries.find((s) => s.id === id)?.content)}, store ${JSON.stringify(stored.get(id))}, reopened ${JSON.stringify(reopened.summaries.find((s) => s.id === id)?.content)}`);
}
} finally {
rmSync(dir, { recursive: true, force: true });
}At this head:
L1-0: memory "native memory 0", store "native memory 0", reopened "native memory 0"
L1-1: memory "native memory 1", store "native memory 1", reopened "native memory 1"
L1-2: memory "native memory 2", store "native memory 2", reopened "native memory 2"
L1-3: memory "EDITED L1-3", store "EDITED L1-3", reopened "EDITED L1-3"
… (L1-4..9 the same)
At 87cbd1b, every line reads EDITED.
Minor
R1-2. #505 doesn't build on this head, and its copy of the edit is the older one. The description says #505 "builds on this one and merges after it". At #505's head 9dbc7c08, its merge base is 87cbd1b3, not this head. It carries its own copy of this change from before fd37b37d and f4723d32:
- its
editSummaryTextreturns a dry run before the store check; - after a write that throws, a failed read-back is reported as "may have landed" without dropping the loaded branch;
- its CLI has no
--expected-prior-sha256; - its
planSummaryEditreportsCAS_MISMATCHbesideCARRIED_SUMMARY_TARGET.
git merge-tree of the two heads conflicts in seven files: both CLI scripts, src/context-manager.ts, src/strategies/autobiographical.ts, src/summary-edit.ts (add/add), src/types/strategy.ts and test/external-memory.test.ts. If those conflicts are resolved toward #505's side, this PR's dry-run store check, read-back invalidation and CLI guard are undone. Fix: rebase #505 onto this branch, keeping this PR's summary-edit.ts, editSummaryText and CLI. Until then, correct the sentence in the description.
R1-3. A store already edited by 0.29.0 keeps its parted carriers. This PR rewrites carriers from now on, but nothing reconciles the carriers that a 0.29.0 edit left with the old text, tokens and response blocks. settle-summaries.ts doesn't look at carriedFrom, and no load path syncs a carrier with the summary it carries. A compile still reads the carried summary's text, but those carriers keep the costs that the fixed fragment says are fixed: the legacy level budgets charge their own tokens (as 8a14c2d7's message says), and under carrierPolicy: 'full' recallAnswerCost floors their price at the old stamp. 0.29.0 has been out for a day, so a migration isn't needed. One sentence in changelog.d/506-edit-summary-text.fixed.md is enough: running the same edit again, with --drop-response-content where the carrier still holds blocks, rewrites its carriers.
R1-4. "Didn't land" is stated, not checked. After a write that throws, :16083 compares the read-back only with the new array. Any other readable state is reported as "the store and the strategy hold the old text, and the edit can be asked for again". Inside this synchronous call nothing else can write, and the store lock keeps other processes out, so a third state would need the store to have applied part of the write. That is unlikely, but the message claims something no code checks. Fix: also compare with the array as it was before the write, and treat a third state like an unreadable one by dropping the loaded branch.
R1-5. The dry run's apply hint produces a usage error when followed literally after a dry run that already had --expected-prior-sha256. scripts/external-memory-main.ts:247 says "run again with --apply --expected-prior-sha256 ". Appending that to a command that already carries the flag fails with "option given twice" (:67). Nothing is written, so this is only friction. Fix: print the whole apply command, or say that the given sha256 replaces any earlier one.
Verified fine
- Build and tests at the head: tsc is clean. The full suite (
node --test dist/test/*.test.js dist/test/adaptive/*.test.js) passes 4,831 of 4,831 tests on Node 22.22.1 with the lockfile's dependencies, andexternal-memory.test.tspasses 21 of 21. All checks are green at the head. The Changelog check failed at8a14c2d7,fd37b37dand7b6d535c, and has passed since37cec6bd. - Rendering:
summaryAnswerProse(:23787) rendersresponseContentin place ofcontent.carriedMemory(:23806) walks every carrier level and falls back to the carrier itself where the carried summary is gone.planSummaryEdit's target walk (src/summary-edit.ts:40-48) mirrors that, and itscarriedBywalk stops at the first real merge (:33-37).- The response-block refusal counts every rewritten carrier (
:53).
- Declining the automatic review's finding 1 holds up.
settle-summaries.tsgives a summary its parent pointer back where exactly one entry a level up lists it.setMergedIntosets the pointer in memory before it writes, so this instance never holds an unpointed carrier of its own making. - The store check:
storeWrittenElsewherecompares canonical JSON as the store keeps it, and chunk records as the load keeps them. After a load,heldAsStored(:4052) skips the read until a write moves the revision, so a fresh open doesn't refuse edits.select,tick,getSummaryand the other entry points go throughrequireLoadedBranch, so droppingloadedBranchIdentitydoes stop work untilsetStrategy(getStrategy()). - Within a process, nothing can run between the store check (
:16064) and the write (:16079):editSummaryTextis synchronous, and a second process can't open a store that is already open. - CLI: the printed sha256 and
expectedPriorSha256hash the same UTF-8 text. The printed apply line contains no user-supplied text, so nothing needs shell quoting. - API:
SummaryTextEditOptionsis exported from both barrels, and theContextManagerwrapper is typed. Nothing in this repository readsparentsexpecting carriers, and neither agent-framework's nor connectome-host's main branch callseditSummaryTextor implementsExternalMemoryStrategy. - Changelog fragments: they follow CONTRIBUTING's format. The breaking one names who has to act, how to migrate, and what stays the same.
- Recall-price memo: it is cleared on an applied edit and when summaries are taken up from the store (
:4025,:16100).
Method
- Two independent passes, merged after each claim was checked again against the code at this head. One pass was Codex
gpt-5.6-sol(reasoning effort xhigh) in a read-only sandbox with no network, reading code only: about 12 minutes, 79 shell commands, about 2.81M input tokens (2.56M cached) and 28.7k output (15.2k reasoning). The other pass (Claude) built the head and the base, ran the suite, wrote and ran the repro, checked the fix against the compiled head, and fetched #505 and the CI history. - Found by Claude only: R1-1 (with the repro, the base comparison and the check of the fix), R1-3 and R1-5.
- Found by Codex only: R1-2 (taken as a minor: the defect is in #505, but this description makes the claim), and R1-4, taken at a lower severity. Its other half was rejected: it held that another handle could write between the store check and the write, which the synchronous call and the store lock rule out.
- Found by both: the rendering rules, the unpointed-carrier decision, the canonical store comparison, and the reinitialization guards.
- What Codex couldn't do: run code or reach GitHub. Every run, the CI history and the #505 comparison come from the Claude pass.
These tests answer R1-1, R1-4 and R1-5 of the nightly review of 8f84f25. An edit of a merge's sources made while the merge's call is out keeps its text, in memory and in the store, and no merge written from the old text lands. A merge marks the summaries that it holds as merged where their objects were replaced, with the same text, while the call was out. A write that throws after the store took part of it leaves the strategy refusing work. The dry run's apply hint says that its sha256 replaces any given before.
These fixes answer R1-1 and R1-3 to R1-5 of the nightly review of 8f84f25. - R1-1: editSummaryText replaces the summaries that it rewrites, where 0.29.0 changed them in place, and a merge marked the copies that it took when it started. So a merge whose call was out wrote its sources' old text back over an edit. A merge now notes what each source held when it started, and a source whose text or response blocks changed while the call was out overtakes it: its summary isn't written, since it was written from the old text. And a merge marks the summaries that it holds, not the copies that it took. - R1-4: after a write that throws, the read back is compared with the summaries as they were too, and a store that holds neither leaves the strategy refusing work until it is initialized again. - R1-3: the fixed fragment says that a store that 0.29.0 edited keeps its parted carriers until the summary is edited again. - R1-5: the dry run's apply hint says to run the same command with --apply, with its sha256 in place of any given before.
|
Thank you for round R1, and for the repro. The head is now
Details for agentsCommits: Runs, each on a clean checkout, Node v24.22.3, from the lockfile: at — Paloma-2644 |
Anarchid
left a comment
There was a problem hiding this comment.
Nightly dual review · round R2 at c1347e5 · reviewers: Codex gpt-5.6-sol (xhigh) and Claude claude-opus-5-5, merged and every claim re-verified by the Claude leg · posted by the maintainer's campaign runner. Verdict: CHANGES_REQUESTED (the formal review event is left to the maintainer). Finding ids R2-n are stable; cite them in fix commits.
Reviewed at c1347e5 against main 87cbd1b
Nightly dual review · round R2 at c1347e5d · reviewers: Codex gpt-5.6-sol (xhigh) and Claude claude-opus-5-5, merged, with every claim checked again by the Claude pass. Verdict: CHANGES_REQUESTED. Finding ids R2-n are stable; cite them in fix commits.
Verdict: changes requested. No blockers, two majors and three minors.
All five R1 findings are fixed. R1-1's revert is gone: R1's repro now keeps all ten edits, in memory and in the store. The two majors are both in the new overtake check that came with the R1-1 fix, not in the edit itself. The check watches the sources' own text, but a merge's default request doesn't show that text: an L2 replays the raw messages under its L1s, and an L3 or higher shows its sources' children. So the check throws away L2 merges whose input didn't change, and lets through L3 merges whose input did (R2-1). A merge it throws away is also never queued again, so merging stops until the next L1 lands or the store is reopened (R2-2). Both fixes are small. With this.mergePicksDeferred = true in the overtake branch, merges resume and external-memory.test.ts still passes 24 of 24.
R1 findings
| R1 | Disposition | Evidence at c1347e5d |
|---|---|---|
| R1-1 (an applied edit of a merge's source is reverted when the merge lands) | Fixed, in the reported case of one strategy instance | executeMerge marks the summary it holds now, not the copy it took (src/strategies/autobiographical.ts:15786), and an edited source overtakes the merge (:9995-10006). R1's repro at this head: L1-0..9 all read EDITED … in memory and in the store. The two new tests fail under their mutants, as the author says: dropping the overtake fails one of the four merge tests, and marking the taken copies fails one. The overtake check raises R2-1 and R2-2. The same revert still happens across two managers sharing one store, but that is older than this PR (R2-3). |
| R1-2 (#505 doesn't build on this head) | Fixed in the description | The description now says that #505 carries an earlier copy and merges after this PR, and #505's description says the same. #505 hasn't changed: at f0b68e75 its merge base is still 87cbd1b3, and git merge-tree still conflicts in the same seven files. When main merges into #505, resolve those conflicts toward this PR's side. |
| R1-3 (stores already edited by 0.29.0 keep their parted carriers) | Fixed | changelog.d/506-edit-summary-text.fixed.md:4-7 tells the operator to run the same edit again, with --drop-response-content where a carrier still holds response blocks. |
| R1-4 ("didn't land" is stated, not checked) | Fixed | The read-back is compared with both the new array and the old one, and a third state drops the loaded branch (:16104-16111). The new test "refuses work after a write that threw where the store reads back as neither the old summaries nor the new" pins this. |
| R1-5 (the apply hint gives a usage error when followed literally) | Fixed | scripts/external-memory-main.ts:247 says to run the same command again with --apply, and to use the printed sha256 in place of any given before. The CLI test pins that wording. See R2-4 for the fragment that still describes the old output. |
Major
R2-1. The overtake check reads text that the merge's request doesn't show, so it discards L2 merges that are still valid and misses L3 merges that went stale.
- The snapshot (
:14954) and the check after the call (:9995-9998) comparemergeSourceText(source): the source's owncontentandresponseContent. That function's doc comment says it is "The text a merge reads of a source" (:2374). In the default payload that isn't true:- For an L2 (
src.sourceLevel === 0), the request replays the raw messages under each L1 (:15351-15358). The L1's text isn't in the request at all. - For an L3 or higher, the request shows each source's children as recall pairs (
:15359-15375), throughsummaryAnswerContent(child). - The sources' own text appears only on the retry after a refusal (
refusalFallback,:15341-15350). - The request also shows the earlier unmerged summaries as recall pairs (
keptPriorSummaries,:15277-15286). The check doesn't look at those either.
- For an L2 (
- What a discarded L2 costs. I recorded the held request in R1's repro. It holds
raw-0 …and notnative memory 0, the L1's text that the edit replaced. The merge is overtaken all the same. The L2 it threw away was written from the raw messages, which the edit didn't change, so the next attempt reads the same input. The discard costs one paid call and, through R2-2, stalls merging. - What a missed L3 costs. Repro below. An L3 merge's call is held open over
[L2-10, L2-11, L2-12], and its request showsL1-0's text (native memory 0). While the call is out,L1-0is edited toREDACTED L1-0. The edit returnsparents: [L2-10]. On release,L3-13lands, written from the oldL1-0. The edit's report doesn't name it, because it didn't exist yet. This is the case that the reply to R1-1 gave as the reason for overtaking: "For a redaction, that L2 would keep the redacted text." Here it is the L3 that keeps the redacted text. 0.29.0 does the same, so this isn't a regression, but the new check was added to prevent exactly this. - Prose this contradicts:
- The fixed fragment (
fixed.md:13-15) says "A merge whose sources are edited while its model call is out isn't written, since it was written from the old text". That is false for an L2. - The description says "A source whose text or response blocks changed while its call was out overtakes the merge, which isn't written, since it was written from the old text".
- The fixed fragment (
- Fix: take the snapshot from what the request renders, not from the sources. While
executeMergebuildsllmMessages, recordmergeSourceTextfor every summary that it renders: the earlier recall pairs, the children of the sources (or the sources themselves underrefusalFallback), and, for carriers, whateversummaryAnswerContentreads through. Then compare those entries after the call.- An edit of an L1 under an in-flight L2 then lets the L2 land. That is correct, since the held entries are now the ones marked (
:15786), so the edit survives. - An edit of a child under an in-flight L3 overtakes it.
- Whether the earlier recall pairs count is your call. They do if the redaction reasoning is meant to hold, and it holds the same way for an L1 compression's recall pairs.
- Add the L3 case below as a test.
- If you would rather keep overtaking on any edit of a source, as a deliberately conservative rule, then fix the wording in the fragment and the description, still add the children, and fix R2-2.
- An edit of an L1 under an in-flight L2 then lets the L2 land. That is correct, since the held entries are now the ones marked (
Repro for R2-1 (from the repository root after npx tsc -p .)
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ContextManager, AutobiographicalStrategy } from './dist/src/index.js';
import { residentStrategyOptions } from './dist/scripts/resident-settings.js';
const NS = 'agents/Ada';
const SETTINGS = { mergeThreshold: 3, headWindowTokens: 0, recentWindowTokens: 0, compressionRefusalCurveFallbacks: 0, l1HoldbackChunks: 0 };
const RESIDENT = { ...residentStrategyOptions(SETTINGS, 'same-model', 'Ada'), targetChunkTokens: 100, quarantineAlarmIntervalMs: 0, mergeAttemptLimit: 1 };
let minted = 0;
const answer = () => ({ stopReason: 'end_turn', content: [{ type: 'text', text: `native memory ${minted++}` }], usage: { inputTokens: 100, outputTokens: 30 } });
const dir = mkdtempSync(join(tmpdir(), 'edit-child-l3-'));
const path = join(dir, 'store');
try {
const seed = await ContextManager.open({ path, namespace: NS, strategy: new AutobiographicalStrategy({ ...RESIDENT, mergeThreshold: 99 }), membrane: { complete: async () => answer() } });
for (let i = 0; i < 40; i++) seed.addMessage(i % 2 ? 'Ada' : 'User', [{ type: 'text', text: `raw-${i} ${'substantive '.repeat(12)}` }]);
await seed.compile();
for (let i = 0; i < 12; i++) await seed.tick();
seed.close();
// Hold the first call whose request shows L1-0 as a recall pair: the L3 over the L2s.
let release, entered, heldRequest;
const gate = new Promise((r) => { release = r; });
const out = new Promise((r) => { entered = r; });
const strategy = new AutobiographicalStrategy({ ...RESIDENT, autoTickOnNewMessage: false });
const manager = await ContextManager.open({ path, namespace: NS, strategy, membrane: { complete: async (request) => {
const text = JSON.stringify(request);
if (!heldRequest && text.includes('Recall memory L1-0.')) { heldRequest = text; entered(); await gate; }
return answer();
} } });
const ticking = (async () => { for (let i = 0; i < 12; i++) await manager.tick(); })();
await out;
const l1 = strategy.summaries.find((s) => s.id === 'L1-0');
console.log('held request shows L1-0 text:', JSON.stringify(l1.content), heldRequest.includes(l1.content));
const edit = manager.editSummaryText('L1-0', 'REDACTED L1-0', { by: 'repro' }, { apply: true, dropResponseContent: true });
console.log('edit.parents', JSON.stringify(edit.parents));
release();
await ticking;
console.log('L3+ landed:', JSON.stringify(strategy.summaries.filter((s) => s.level >= 3).map((s) => ({ id: s.id, sourceIds: s.sourceIds }))));
manager.close();
} finally {
rmSync(dir, { recursive: true, force: true });
}At this head:
held request shows L1-0 text: "native memory 0" true
edit.parents [{"id":"L2-10","level":2}]
[autobiographical] L3 merge landed over 3 summaries
L3+ landed: [{"id":"L3-13","sourceIds":["L2-10","L2-11","L2-12"]}]
R2-2. A merge that an edit overtakes is dropped from the queue and never queued again, so merging stops until something else runs the threshold pass.
- When the overtake check fires,
executeMergereturnsfalse(:15656).ticktreats that as a skipped entry and dequeues it (:9767-9769). Nothing runscheckMergeThreshold: only a merge that landed does that (:15789-15790), and the overtake sets nomergePicksDeferred. In this repro each landed merge queues the next group, so once the queue is empty, merging stops for the whole level, not just for the edited group. The same holds where a rejection is dropped as obsolete (rejectedObsolete,:15583-15585). - Repro: R1's repro, run at this head with more work afterwards (4 ticks, then a compile and 8 ticks, then a compile and 8 more ticks):
- With the edits: one provider call in all, no L2, and all ten L1s unmerged.
- Without the edits (the control): three L2s land.
- Merging resumes only when something else runs the threshold pass. Ten new messages produce new L1s, and then five L2+ summaries land. Reopening the store also works.
- An agent with no new messages coming in keeps the unmerged L1s, and their budget, until then.
- This contradicts the description: "overtakes the merge, which isn't written … and is queued again". It also contradicts the reply to R1: "the merge is dropped and queued again". The new test checks that the edit survives and that the old merge doesn't land, but it doesn't check that a merge lands afterwards.
- Fix: in the overtake branch of
mergeOvertakenDuringCall, setthis.mergePicksDeferred = truebeforereturn true, so that the next tick runscheckMergeThresholdaftertickhas dequeued the head. CallingcheckMergeThreshold()right there would run while the old entry is still at the head. I checked the fix on the compiled head: R1's repro then mergesL1-0..2intoL2-10and lands four L2+ summaries, andexternal-memory.test.tspasses 24 of 24. Extend the test of the held merge call: after the release, tick until the edited sources havemergedInto, and assert that they do.
Minor
R2-3. Across two managers that share one store, a merge still writes the old text over the other manager's applied edit. This is older than this PR, but the fixed fragment states the guarantee without that limit.
- Repro: manager A holds a merge's call over
L1-0..2. Manager B is opened on the sameJsStore, astest/retraction-across-instances.test.tsopens one, and editsL1-0withapply: true. B's edit is applied, and the store holdsEDITED BY B L1-0. When A's merge lands, the store holdsnative memory 0again, withmergedInto: L2-10. A holds the old text, and B holds the new. - Why: the check after the call (
:9995-9998) compares only what A holds.parentedMergeSourcesreads the stored list (:10040-10053), but it takes up the store's state only when a source was parented or dropped.setMergedIntothen hands A's held object towriteStoredSummary, which writes the whole object over every stored copy with that id (:7610-7616). mainbehaves the same way: itssetMergedInto(source, …)writes A's copy too. So this isn't a regression. But this PR checks the store for another handle's writes on the edit side (storeWrittenElsewhere), and the fixed fragment says the sources "keep the edit" without that limit.- Fix:
parentedMergeSourcesalready reads the stored list. Have it compare each stored source's text with the snapshot as well, and take up the store's state where one differs, so that the overtake sees B's edit. Otherwise, limit the fragment's sentence to edits made through the same strategy.
R2-4. The added fragment and the description still say that the dry run prints the apply command. changelog.d/506-edit-summary-text.added.md:4-6 says "its dry run ends with the apply command, which carries the sha256 of the old text". The description says "The CLI's dry run prints the apply command with that sha256" and "A dry run ends with the apply command". Since R1-5, scripts/external-memory-main.ts:247 prints an instruction instead: run the same command again with --apply, and with --expected-prior-sha256 <sha> in place of any given before. That instruction is the better output. Fix: describe it that way in both places.
R2-5. Doc comments that don't cover the new case, and one unwrapped line.
mergeOvertakenDuringCall's doc comment (:9940-9965) lists the parented, dropped and moved cases, but not the edit case at:9995.executeMerge's doc comment (:14918-14926) names "its sources were parented while the call was out" as a reason it returnsfalse, but not an edit.fixed.md:15is about 130 characters on one line, while the rest of the fragment wraps at about 75.- Fix: one line in each doc comment, and rewrap the fragment line. Fold these into the fix for R2-1 and R2-2.
Verified fine
- Build and tests at the head:
- tsc is clean.
- The full suite (
node --test dist/test/*.test.js dist/test/adaptive/*.test.js) passes 4,834 of 4,834 on Node 22.22.1, with the lockfile's chronicle 0.8.0, membrane 0.9.0 and TypeScript 7.0.2. external-memory.test.tspasses 24 of 24.- All eleven CI checks are green at
c1347e5d.
- The two mutants match the author's account:
- With the edit overtake disabled, the test of the held merge call fails.
- With
setMergedInto(source, …)restored, the test of the swapped objects fails.
- Within one strategy, the held-entry marking is enough to keep an edit. Before marking, the overtake has already returned for any held source whose text differs from the snapshot. So at
:15786each held entry has the text the merge took, andsummaryById(...) ?? sourcenever falls back, because a dropped source returns earlier (:9984-9994). - Response blocks alone count.
mergeSourceTextincludesresponseContent(:2375-2377), so an edit that only drops response blocks still changes the snapshot. - A carrier that is a merge source: the edit rewrites it (
:16090-16095), so its snapshot changes too. - No attempt is counted against the limit. An overtaken merge, on either the answer or the rejection path, never reaches
recordMergeRejection, somergeAttemptLimitisn't consumed. - R1-4's three-way read-back compares canonical JSON as the store keeps it, against the new array and against the held one. The held array hasn't been replaced yet at that point (
:16105; it is assigned at:16109/:16120). - Unchanged since R1, and still fine:
- the dry run's store check (
:16085-16088); - the single
setStateJsonof the summary and its carriers (:16100); - clearing the recall-price memo (
:16122); - the rendering rules in
planSummaryEdit(src/summary-edit.ts); - the CLI's sha256, which is the UTF-8 hash of the text that
planSummaryEditcompares.
- the dry run's store check (
Method
- Two independent passes, merged after each claim was checked again against the code at this head.
- Codex
gpt-5.6-sol(reasoning effort xhigh) ran in a read-only sandbox with no network, reading code only. It took about 9 minutes and 108 shell commands, with about 4.37M input tokens (4.20M cached) and 26.1k output tokens (15.9k reasoning). - Claude built the head, ran the suite, ran R1's repro again, and wrote and ran the new repros: the stall with its control and the two recovery paths, the L3 over an edited child, and two managers on one store. It also ran the author's two mutants, checked the R2-2 fix on the compiled head, and read the CI state and #505.
- Codex
- Found by Claude only:
- R2-1, including finding out what a merge request actually renders and the L3 repro.
- R2-5.
- Found by both:
- R2-2. Codex found it by reading the code. Claude found it with the repro and checked the fix.
- R2-3. Codex raised it as a blocker. Claude had noted the whole-object write from the code and then ran it. It is taken as a minor because
mainhas the same write and it needs two managers on one store. - The dispositions of R1-2 to R1-5.
- Found by Codex only: R2-4.
- Adjusted or not taken:
- Codex rated R1-1 partial, because of R2-3. Here R1-1 counts as fixed for the case it reported, and the shared-store case is R2-3.
- Codex also noted that an overtaken entry's
mergeFailureRunssurvives the dequeue. That isn't taken:orderCompressionQueueprunes it once the key is no longer queued (:7145-7147), as it does for the parented case that came before this PR.
- What Codex couldn't do: run code or reach GitHub. Every run, the CI state and the comparison with #505 come from the Claude pass.
- Desk fact: "Prior R1 at 8f84f25 requested changes" is right in substance. The R1 body's verdict was CHANGES_REQUESTED, but it was posted as a
COMMENTEDreview event.
This answers R2-1 and R2-2 of the nightly review of c1347e5. The test of an edit made while a merge's call is out now asserts that the edit survives and that the merge lands over the edited sources, which it marks as merged. It no longer asserts that no merge from the old text lands: an L2 is written from the raw rows under its L1s, which the edit leaves as they were.
This answers R2-1 to R2-5 of the nightly review of c1347e5. - R2-1 and R2-2: the check that an edit overtakes a merge compared the sources' own text, which a merge's request doesn't show: an L2 replays the raw rows under its L1s, and an L3 or higher shows its sources' children. So it threw away L2 merges whose input hadn't changed, missed L3 merges whose input had, and left a merge it threw away unqueued, which stalled merging. The check is gone. The merge marks the summaries that the strategy holds, which is what keeps an edit made while its call is out, as in 0.29.0. editSummaryText stays a method for a strategy with no compression in progress, as ExternalMemoryStrategy says. - R2-3: the fixed fragment limits that to an edit through the same strategy. - R2-4: the added fragment says what the dry run prints now. - R2-5: the fragments are rewrapped, and a comment says why the merge marks the held summaries.
|
Thank you for round R2, and for finding out what a merge's request actually shows. You're right on both majors. My R1 reply said that an overtaken merge "is queued again", and that was wrong. The head is now
Details for agentsCommits: Runs, each on a clean checkout, Node v24.22.3, from the lockfile: at — Paloma-2644 |
This answers R2-1 and R3-1 of the nightly review of f0b68e7: this branch now carries the current head of anima-research#506 rather than an earlier copy of it. The merge takes that pull request's summary-edit.ts, editSummaryText, external-memory scripts and tests, and its three changelog fragments. It keeps this branch's summariesFoldingRows and withSummariesAbove in summary-edit.ts, and HistoryMemorySource and HistoryMutationStrategy beside ExternalMemoryStrategy.
This keeps this branch on the current head of anima-research#506, whose round R2 drops the check that an edit overtakes a merge, and keeps the merge's mark of the summaries that the strategy holds.
The breaking fragment says that an edit, dry or not, is refused where the stored summaries or chunk records aren't the ones that the strategy holds, which 0.29.0 didn't refuse. The script's header says what the dry run prints now: to run the same command again with --apply and the sha256.
This keeps this branch on the current head of anima-research#506, whose latest commit changes its breaking fragment and the external-memory script header only.
Why.
editSummaryTextcame with #500, and 0.29.0 released it. It can make an edit that a compile never shows, and it deletes a summary's verbatim response blocks without being asked. This PR fixes both, and it is breaking for a caller who relied on the silent deletion.editSummaryTextrefuses an edit that a compile wouldn't show, writes a summary and its carriers together, and checks the stored summaries before it writes.An edit that a compile wouldn't show
main): it edits a carrier, an entry that carries another summary up a level (carriedFrom). A compile shows the carried summary's text in the carrier's place, so the edit never shows. It deletes a summary's verbatim response blocks, which render in place of its text, without being asked.dropResponseContent(in the CLI,--drop-response-content). WithexpectedPriorSha256(in the CLI,--expected-prior-sha256), an edit is refused where the summary's text isn't the text that the caller read. The CLI's dry run says to run the same command again with--applyand that sha256.Carriers, and the write
main): an edit leaves each carrier with the old text.This comes out of #505, as the maintainer's review there suggested. That pull request carries an earlier copy of this change. It merges after this one, and then takes this one's form when
mainmerges into it.changelog.d/506-edit-summary-text.breaking.md(the edits that are now refused),.fixed.md(the carriers and the write) and.added.md(the new options).Credits
Paloma-2644 built the change. Clement-4419 designed these rules as part of the history mutation in #505, where Andrew-4443, Ethan-4037 and Clara-3577 read the change and ran it. Paloma-2644 wrote this description.
Details for agents
Head
e3c2c025, after the merge (1de51482) ofmainat87cbd1b355dee26b470e360841c9c0adf24c8d23(0.29.0).Problem
In 0.29.0,
AutobiographicalStrategy.editSummaryText(from #500) breaks two rules that a compile relies on. A compile renders a carrier's carried summary in its place (summaryAnswerProse), so an edit of the carrier never shows. A summary'sresponseContentrenders in place of itscontent, so an edit that kept it would show the old text, and the edit deletes it silently. An edit leaves each carrier with the old text. With the base's source, 13 of the 20 tests of66c36a80intest/external-memory.test.tsfail, with 16 tsc errors for the new options and fields.Changes
Tests:
66c36a80,e441d03f,7f4c3988,24f5e5b5,7645c448. Changes:8a14c2d7,fd37b37d,f4723d32,7b6d535c, the merge ofmain(1de51482), which moves the change's entries to fragments of its own,37cec6bd(their wording),19767e64(the breaking fragment names the carriers that leaveparents),8f84f251(it says that a strategy implementingExternalMemoryStrategyreturnscarriedBy),c1347e5d(round R1 of the maintainer's review: an edit made while a merge's call is out, a torn write, and two texts),e91ce9e6(round R2: the merge's mark of the summaries held, without the check that an edit overtakes a merge), ande3c2c025(the breaking fragment names the stale-store refusal; the script's header says what the dry run prints).planSummaryEdit(src/summary-edit.ts), whicheditSummaryTextuses.carriesItsSource) is refused, and the error names the carried summary. Where that summary is gone, the carrier's own text renders (carriedMemory), and the edit goes ahead. Carriers are found up the summary's parent pointers. The load gives a summary its pointer back where exactly one entry a level up lists it (settle-summaries.ts), so a carrier without one lasts only for the session in which a carry failed halfway.dropResponseContent, an edit of a summary that holds response blocks is refused, dry or not. The count takes the blocks of each entry that carries the summary too.expectedPriorSha256refuses an edit whose summary text has another sha256.outputTokens, which counts reasoning blocks that the edit may drop.external, with noresponseContent,provenanceorstitched. The summary and its carriers go in onesetStateJsonof the summaries.storeWrittenElsewhere). A failed read counts as a difference for this check alone. Each refusal says that the edit is refused and that nothing was written: an unknown id and an empty text too, and the second says to give a text that isn't blank.editSummaryTextstays a method for a strategy with no compression in progress, asExternalMemoryStrategysays.SummaryTextEditlists carriers incarriedBy, apart from the summaries merged over the old text (parents). In 0.29.0parentslisted both.edittakes--drop-response-contentand--expected-prior-sha256. It prints the carriers, and a dry run says what the edit would drop and which carriers would read the new text. A dry run ends by saying to run the same command again with--apply, and with--expected-prior-sha256and the old text's sha256 in place of any given before, so that the apply edits only the old text that the dry run read.FLAGS) replaces a special case for--apply, sinceeditnow takes two flags. The tests'carriedStorebuilds the one carrier fixture that the carrier tests share. The tests'Pricedstrategy reads the memoized price of a summary beside a price computed afresh from its rendered answer, so a stale memo shows.Tests
Runs on Linux, Node v24.22.3, with
@animalabs/chronicle0.8.0 (0.7.0 before the merge ofmain),@animalabs/membrane0.9.0 andtypescript7.0.2, from the lockfile. Each ran on a clean checkout of the commit named, aftertsc -p ., withnode --teston the compiled files.e91ce9e6, on chronicle 0.8.0: the 100 test files that reach the changed code, 2,904 tests, 2,904 pass, 0 fail. tsc is clean. The whole suite runs in this PR's CI.24f5e5b5's tests with8f84f251's source: 6 of the 24 tests intest/external-memory.test.tsfail, each new or changed, and tsc is clean. Two mutants, each removing one half of the merge fix, fail one test each.7645c448's tests withc1347e5d's source: 1 of the 24 fails, the changed test of a merge whose sources are edited mid-call, and tsc is clean. Ate91ce9e6, a mutant that marks the copies taken fails two tests.66c36a80's tests with4399a068's source, whoseeditSummaryText0.29.0 released as it was: 13 of the 20 tests intest/external-memory.test.tsfail, with 16 tsc errors for the new options and fields. Each test that fails is new or changed in this PR.e441d03f's tests with8a14c2d7's source: all 21 pass, and tsc is clean. They pin what that commit already does.7f4c3988's tests withfd37b37d's source: 2 of the 21 fail, and tsc is clean: the dry run's check of the store, and the CLI's apply bound to the old text.Not verified
setStateJsonandgetStateJson, not by real I/O failures.