Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sweep): keep a later stopped window's cap when an earlier turn is rewritten (#6785)
garrytanc7f1cc803cf5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 657cef5ecf..8500716131 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,7 +31,7 @@ After upgrading, transcripts an earlier verify marked this way are extracted aga### Itemized changes- `src/core/context/corpus-segments.ts`: `corpusFileCompletion` is the one completion classifier for sweep selection, the under-claim re-check, retention GC, the HTTP drain and the doctor backlog, so a rewritten file counts as pending everywhere. A sidecar whose `skipped` is `chat_unavailable` is pending, and only finished files get the plain retention; unavailable, partial and rewritten files keep the un-ingested ceiling. The failure record format (`<file>.failures.json`, `CORPUS_WINDOW_FAILURE_CAP` 5) lives here too, and the session-end hook reaps it with its `.txt`.-- `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after an admitted chat call counts against the window's start and the source incarnation, and so does a paid window whose progress could not be committed; an extraction refused by the spend guard before any chat call was admitted, or replayed without a model call, does not count. Neither tail growth nor the error label resets the count, and a commit of that window clears it. Selection serves backing-off and stopped files after every other candidate, so they never take a whole batch. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.+- `src/core/context/corpus-windows.ts`: `runCorpusWindows` returns `unavailable` without recording the window, and rewinds a progress an earlier build finished as `chat_unavailable` to its retired turns under the same compare-and-set that takes the lease. A failure thrown after an admitted chat call counts against the window's start and the source incarnation, and so does a paid window whose progress could not be committed; an extraction refused by the spend guard before any chat call was admitted, or replayed without a model call, does not count. Neither tail growth, an edit to an earlier turn nor the error label resets the count; a commit of that window, or a rewrite that removes it, clears it. Selection serves backing-off and stopped files after every other candidate, so they never take a whole batch. One change of the extraction-config fingerprint (model, provider, key presence; no values) re-arms a stopped window once.- `src/core/sweep.ts`: the corpus pass runs the facts-absorb owner-readiness preflight (#5362) per source before any model call, applies the failure cap to writeback turn files as well, stops the pass on `chat_unavailable`, charges every attempted window (a thrown one included) against the per-sweep total, and logs thrown errors with their code. `corpus: false` skips the pass. `armCorpusDrain` logs the sweep's diagnostics (each distinct line once) and its skip reasons whenever they change.- `src/core/context/checkpoint-harvest.ts`: the compact and writeback lanes run the same preflight and the same failure cap; neither writes a receipt or sidecar for an `unavailable`, backing-off or stopped window.- `src/core/context-engine.ts`: the OpenClaw `compact()` inline harvest on Postgres (rung 3) runs the same preflight, records a failed paid attempt where the sweep's cap reads it and then leaves that segment to the sweep, keeps a `chat_unavailable` segment pending, and records any other skip reason in its sidecar.diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.tsindex f01c95e1c4..c0cedc1fb1 100644--- a/src/core/context/corpus-windows.ts+++ b/src/core/context/corpus-windows.ts@@ -444,6 +444,14 @@ export function corpusFileParked(full: string, fingerprint: string | null, nowMsreturn !!record && corpusFailureGate(record, record.key, record.source_incarnation, fingerprint, nowMs) !== 'run';}+/** Whether a failure record's window (`<turn sha256>@<offset>`) still lies at or after `cursor` in `turns`. */+function failureAhead(key: string, turns: CorpusTurn[], cursor: { turn: number; offset: number }): boolean {+ const at = key.lastIndexOf('@');+ const sha = key.slice(0, at);+ const offset = Number(key.slice(at + 1));+ return turns.some((t, i) => t.sha256 === sha && (i > cursor.turn || (i === cursor.turn && offset >= cursor.offset)));+}+/*** The key of the window the next run of `full` starts at (the frontier a* failure record names), or null when the file or its progress is@@ -693,14 +701,14 @@ export async function runCorpusWindows(opts: {break;}state = next;- // Any record left is this window's or stale (the frontier moved past it).- if (failure) {- await clearCorpusFailure(full).catch(() => {});- failure = null;- }if (r) done++;if (isLast) holding = false;cursor = win.endOffset === null ? { turn: win.endTurn + 1, offset: 0 } : { turn: win.endTurn, offset: win.endOffset };+ // This window's record, or one whose window is gone (another incarnation, or its turn no longer ahead), is done.+ if (failure && (failure.key === key || failure.source_incarnation !== incarnation || !failureAhead(failure.key, turns, cursor))) {+ await clearCorpusFailure(full).catch(() => {});+ failure = null;+ }}if (windows.length === 0) {const finished = await updateProgress(full, (cur) =>diff --git a/test/sweep-corpus-failure-cap-6785.test.ts b/test/sweep-corpus-failure-cap-6785.test.tsindex ebfe6b3f9c..05c597a1b9 100644--- a/test/sweep-corpus-failure-cap-6785.test.ts+++ b/test/sweep-corpus-failure-cap-6785.test.ts@@ -513,4 +513,26 @@ describe('#6785: a window that keeps failing after its model call is capped', ()expect(run.status).toBe('contended');expect(existsSync(file + '.failures.json')).toBe(false);});+ test('rewriting an earlier, consumed turn keeps the cap of an unchanged stopped window after it', async () => {+ const { corpusFileStat, recordCorpusFailure, runCorpusWindows } = await import('../src/core/context/corpus-windows.ts');+ const { statSync } = await import('node:fs');+ const file = join(dir, 'earlier-rewrite.txt');+ const turn = (marker: string) => `${marker} ${marker.toLowerCase().repeat(5000)}`;+ const b = `[assistant]\n${turn('B')}`;+ writeFileSync(file, `[user]\n${turn('A')}\n\n${b}`);+ const empty = () => ({ inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] });+ const opts = () => ({ full: file, raw: readFileSync(file, 'utf8'), fileStat: corpusFileStat(statSync(file)), signal: new AbortController().signal,+ overBudget: () => false, source: { id: 'default', incarnation: 'inc-a' }, failures: { fingerprint: 'f1' } });+ await runCorpusWindows({ ...opts(), maxWindows: 1, extract: async () => empty() });+ const key = `${parseCorpusTurns(b)[0].sha256}@0`;+ let record = null;+ for (let i = 0; i < 5; i++) record = await recordCorpusFailure(file, record, key, 'inc-a', 'f1', 0, new Error('B fails'));++ writeFileSync(file, `[user]\n${turn('C')}\n\n${b}`);+ const seen: string[] = [];+ const run = await runCorpusWindows({ ...opts(), maxWindows: 3, extract: async (text) => { seen.push(text.includes('\nB ') || text.startsWith('B ') ? 'B' : 'C'); return empty(); } });+ expect(seen).toEqual(['C']);+ expect(run.status).toBe('dead_lettered');+ expect(JSON.parse(readFileSync(file + '.failures.json', 'utf8')).count).toBe(5);+ });});