Skip to content

Commit 5cf8c62

Browse files
CL-9006: fix automatic compaction governor so post-compact above-threshold sessions latch (#1175)
* test(compaction): red latch tests for post-compact above-threshold re-arm * fix(compaction): latch post-compact re-arm on a wide resume gap * docs(context-window): correct hasWideResumeGap comment (proactive path only)
1 parent 3e5c4e5 commit 5cf8c62

5 files changed

Lines changed: 295 additions & 57 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,12 @@ The agent maintains an optional **`manage_tasks`** list (create/update via the h
189189

190190
When a cycle's input tokens cross a threshold, the director compacts the inference-facing history (the full run is always retained in the context store). The threshold is **model-aware** — roughly 60% of the active model's real context window — so small-window models compact early enough to avoid provider context-overflow while large-window models do not compact prematurely. The compacted prefix is **append-only across passes**: the existing compacted user turn stays byte-identical; new folds become later summary turns with a harness-inserted assistant spacer (identified by reserved `model: "harness"`, plus a visible sentinel; persisted `[compaction]` tokens without a producer still freeze) between them so the prompt head can remain in the provider KV cache. Model-emitted copies of the spacer are not frozen. Spacer-only model replies are incomplete: ChatDirector nudges, then falls through loop-protection, workflow-idle, and open-task rails rather than empty-settling with work still open. The governor covers five cases:
191191

192-
- **Threshold at a tool pause** — Once over threshold, the follow-up `infer` after a tool batch is swapped for a `compact` cycle, and inference resumes via a host continuation message. After a compact that remains over the high watermark, the governor uses **growth hysteresis** (wait for usage to grow by ~10% of the window) instead of re-arming on every cycle; dropping under 60% is not required.
192+
- **Threshold at a tool pause** — Once over threshold, the follow-up `infer` after a tool batch is swapped for a `compact` cycle, and inference resumes via a host continuation message. After a compact that remains over the high watermark, the governor latches: it does not re-arm on growth alone until usage climbs a wide resume gap (~20% of the window, a full warning band) past the post-compact measurement, or until a summarizing fold gets usage back at or under the threshold. A consecutive-compact cap holds across tool-call occupancy as a second rail.
193193
- **Idle (end-of-turn)** — An interactive turn can end with a reply and then sit idle with no tool batch to intercept; the governor requests a continuation at that pause and compacts when it arrives. An operator message that races the continuation still compacts first, then re-enters inference to answer it.
194194
- **Idle recompress past the provider TTL** — Cache expiry does not compact. Stored turns stay. When settings set `anthropicCachePrompt`, and the saved Anthropic-protocol cache write is at least 5 minutes old, the pre-inference context transform stubs old tool-result bodies on the outgoing prompt only. `turns.jsonl` is not rewritten. The setting defaults off.
195195

196196
- **Operator `/compact`** — A first-class slash command folds now without waiting for the occupancy governor. Optional trailing instructions go to the summarizer (empty uses the default structured fold) and are stored on the compact record so later auto-folds still see them. Director rebuild (`/model`, interrupt, resume) restores those instructions from the latest compact record's parameters. An in-flight turn uses the same pair-safe compact-then-continue hop as threshold compact; an idle compact shows the fold and does not start a new turn.
197-
- **Overflow recovery** — A `context_overflow` inference error would otherwise become a terminal error reply; the governor compacts and retries instead, bounded so a history the compactor cannot shrink does not loop forever. Overflow ignores hysteresis for the compact itself.
197+
- **Overflow recovery** — A `context_overflow` inference error would otherwise become a terminal error reply; the governor compacts and retries instead, bounded so a history the compactor cannot shrink does not loop forever. The overflow compact itself always fires, but the recovery counts against the same latch: only an under-threshold fold restores the budget, and the proactive path stays subject to the latched re-arm rule.
198198

199199
The compaction control flow is shaped by a reactor invariant: a `compact` action runs in its own cycle (it cannot be paired with `infer`), and **the reactor delivers no event after a compact cycle**. A director that simply emitted `compact` in place of the follow-up `infer` would leave the loop idle forever — the cause of an earlier stall. Instead the governor pairs `compact` with an emit action (`custom.compaction.continue`), and the host answers that emission by delivering a content-less inbound message (`buildCompactionContinuationMessage()`) through the serial operation queue, generation-guarded like every other deliver. A hop superseded because interrupt already bumped generation and enqueued a rebuild is re-queued onto the replacement agent rather than consumed on the outgoing liveAgent. That message adds no turn (`createInboundTurn` returns `null` for empty content) but re-enters the loop, where the director issues the follow-up `infer` against the freshly truncated history. Each emission is answered at most once (a replayed duplicate of an already-answered emission is ignored), and an unsolicited continuation with neither resume flag set answers `wait` rather than burning a billable inference. The legacy `requestContinuation` closure survives only on the sub-agent path, which delivers directly with no host emit hop; idle arming keeps the two channels exclusive (closure fires and the arming flag stays false, or no closure and the flag reports the arming) so a caller honoring both cannot double-deliver.
200200

‎src/agent/compaction.test.ts‎

Lines changed: 187 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
stickyExtraInstructionsFromRecords,
1515
} from "./compaction.js";
1616
import {
17-
compactionResumeDeltaFor,
17+
compactionWideResumeDeltaFor,
1818
compactionThresholdFor,
1919
} from "../provider/context-window.js";
2020
import {
@@ -147,7 +147,7 @@ function overflowError(): ReactorInboundEvent {
147147
}
148148

149149
const overThreshold = compactionThresholdFor("m") + 1;
150-
const resumeDelta = compactionResumeDeltaFor("m");
150+
const wideDelta = compactionWideResumeDeltaFor("m");
151151
const inferAction: ReactorAction[] = [{ type: "infer" }];
152152
const tenTurns = turnsOfLength(10, 1);
153153
const threeTurns = turnsOfLength(3, 1);
@@ -634,15 +634,15 @@ describe("compaction governor", () => {
634634
governor.interceptActions(toolDone(), inferAction, capabilities),
635635
).not.toBeNull();
636636

637-
// Post-compact snapshot is still over high; growth hysteresis must hold
638-
// the next arm until usage grows by resumeDelta.
637+
// Post-compact snapshot is still over high; the latch must hold the next
638+
// arm until usage climbs a wide resume gap past the snapshot.
639639
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
640640
expect(
641641
governor.interceptActions(toolDone(), inferAction, capabilities),
642642
).toBeNull();
643643
});
644644

645-
test("re-arms after usage grows by the resume delta past the last compact", () => {
645+
test("re-arms after usage grows by the wide resume gap past the last compact", () => {
646646
const governor = createCompactionGovernor(() => undefined);
647647
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
648648
expect(
@@ -655,7 +655,7 @@ describe("compaction governor", () => {
655655
).toBeNull();
656656

657657
governor.noteInferenceDone(
658-
inferenceDone(overThreshold + resumeDelta),
658+
inferenceDone(overThreshold + wideDelta),
659659
tenTurns,
660660
);
661661
const actions = governor.interceptActions(
@@ -667,7 +667,7 @@ describe("compaction governor", () => {
667667
expect(actions?.some((a) => a.type === "compact")).toBe(true);
668668
});
669669

670-
test("clears hysteresis once usage drops under the high watermark", () => {
670+
test("clears the latch once usage drops under the high watermark", () => {
671671
const governor = createCompactionGovernor(() => undefined);
672672
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
673673
expect(
@@ -695,7 +695,7 @@ describe("compaction governor", () => {
695695
expect(actions?.some((a) => a.type === "compact")).toBe(true);
696696
});
697697

698-
test("overflow still compact while hysteresis blocks the proactive path", () => {
698+
test("overflow still compacts while the latch blocks the proactive path", () => {
699699
const governor = createCompactionGovernor(() => undefined);
700700
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
701701
expect(
@@ -712,7 +712,7 @@ describe("compaction governor", () => {
712712
expect(actions?.some((a) => a.type === "compact")).toBe(true);
713713
});
714714

715-
test("consecutive threshold and idle compacts are bounded until occupancy", () => {
715+
test("consecutive threshold and idle compacts stay bounded across tool-call occupancy", () => {
716716
const governor = createCompactionGovernor(() => undefined);
717717
const echo = LEGACY_COMPACT_SPACER_TEXT;
718718
governor.noteInferenceDone(inferenceDone(overThreshold, echo), tenTurns);
@@ -722,42 +722,47 @@ describe("compaction governor", () => {
722722

723723
governor.noteInferenceDone(inferenceDone(overThreshold, echo), tenTurns);
724724
governor.noteInferenceDone(
725-
inferenceDone(overThreshold + resumeDelta, echo),
725+
inferenceDone(overThreshold + wideDelta, echo),
726726
tenTurns,
727727
);
728728
expect(
729729
governor.interceptActions(toolDone(), inferAction, capabilities),
730730
).not.toBeNull();
731731

732+
// Still over after two folds: the cap holds on both rails even as usage
733+
// keeps climbing past wide gaps ...
732734
governor.noteInferenceDone(
733-
inferenceDone(overThreshold + resumeDelta, echo),
735+
inferenceDone(overThreshold + wideDelta, echo),
734736
tenTurns,
735737
);
736738
governor.noteInferenceDone(
737-
inferenceDone(overThreshold + 2 * resumeDelta, echo),
739+
inferenceDone(overThreshold + 2 * wideDelta, echo),
738740
tenTurns,
739741
);
740742
expect(
741743
governor.interceptActions(toolDone(), inferAction, capabilities),
742744
).toBeNull();
743-
governor.noteIdleTurn(
744-
inferenceDone(overThreshold + 2 * resumeDelta, echo),
745-
[{ type: "reply", content: "done" }],
746-
);
745+
governor.noteIdleTurn(inferenceDone(overThreshold + 2 * wideDelta, echo), [
746+
{ type: "reply", content: "done" },
747+
]);
747748
expect(
748749
governor.interceptIdleContinuation(emptyMessage(), capabilities),
749750
).toBeNull();
750751

752+
// ... and tool-call occupancy does not reopen either rail.
751753
governor.noteInferenceDone(
752-
inferenceDone(overThreshold + 3 * resumeDelta, "real work"),
754+
inferenceDoneWithTools(overThreshold + 3 * wideDelta),
753755
tenTurns,
754756
);
755757
expect(
756758
governor.interceptActions(toolDone(), inferAction, capabilities),
757759
).toBeNull();
758760

761+
// Fold evidence restores the rails: under the watermark, then a fresh
762+
// crossing arms immediately with no gap required.
763+
governor.noteInferenceDone(inferenceDone(1000, "real work"), tenTurns);
759764
governor.noteInferenceDone(
760-
inferenceDoneWithTools(overThreshold + 4 * resumeDelta),
765+
inferenceDone(overThreshold, "real work"),
761766
tenTurns,
762767
);
763768
expect(
@@ -936,6 +941,167 @@ describe("compaction governor", () => {
936941
});
937942
});
938943

944+
describe("post-compact above-threshold latch (CL-9006)", () => {
945+
// Half the wide gap: growth that used to re-arm under the old resume delta
946+
// must no longer re-arm on its own.
947+
const smallGrowth = Math.floor(wideDelta / 2);
948+
949+
test("resume-delta-scale growth while still over threshold does not re-arm", () => {
950+
const governor = createCompactionGovernor(() => undefined);
951+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
952+
expect(
953+
governor.interceptActions(toolDone(), inferAction, capabilities),
954+
).not.toBeNull();
955+
956+
// Post-compact measurement stays over the high watermark: the latch sets.
957+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
958+
// Growth by half the wide gap must NOT re-arm on its own.
959+
governor.noteInferenceDone(
960+
inferenceDone(overThreshold + smallGrowth),
961+
tenTurns,
962+
);
963+
expect(
964+
governor.interceptActions(toolDone(), inferAction, capabilities),
965+
).toBeNull();
966+
// The idle path shares the same latch.
967+
governor.noteIdleTurn(inferenceDone(overThreshold + smallGrowth), [
968+
{ type: "reply", content: "done" },
969+
]);
970+
expect(
971+
governor.interceptIdleContinuation(emptyMessage(), capabilities),
972+
).toBeNull();
973+
});
974+
975+
test("a wide resume gap while still over threshold re-arms", () => {
976+
const governor = createCompactionGovernor(() => undefined);
977+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
978+
expect(
979+
governor.interceptActions(toolDone(), inferAction, capabilities),
980+
).not.toBeNull();
981+
982+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
983+
governor.noteInferenceDone(
984+
inferenceDone(overThreshold + wideDelta),
985+
tenTurns,
986+
);
987+
const actions = governor.interceptActions(
988+
toolDone(),
989+
inferAction,
990+
capabilities,
991+
);
992+
expect(actions).not.toBeNull();
993+
expect(actions?.some((a) => a.type === "compact")).toBe(true);
994+
});
995+
996+
test("the consecutive-compact cap holds across tool-call occupancy", () => {
997+
const governor = createCompactionGovernor(() => undefined);
998+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
999+
expect(
1000+
governor.interceptActions(toolDone(), inferAction, capabilities),
1001+
).not.toBeNull();
1002+
1003+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
1004+
governor.noteInferenceDone(
1005+
inferenceDone(overThreshold + wideDelta),
1006+
tenTurns,
1007+
);
1008+
expect(
1009+
governor.interceptActions(toolDone(), inferAction, capabilities),
1010+
).not.toBeNull();
1011+
1012+
// Post-compact measurement still over: tool-call occupancy must not reset
1013+
// the cap, even past a wide gap.
1014+
governor.noteInferenceDone(
1015+
inferenceDone(overThreshold + wideDelta),
1016+
tenTurns,
1017+
);
1018+
governor.noteInferenceDone(
1019+
inferenceDoneWithTools(overThreshold + 2 * wideDelta),
1020+
tenTurns,
1021+
);
1022+
expect(
1023+
governor.interceptActions(toolDone(), inferAction, capabilities),
1024+
).toBeNull();
1025+
// The idle path shares the same cap.
1026+
governor.noteIdleTurn(
1027+
inferenceDoneWithTools(overThreshold + 2 * wideDelta),
1028+
[{ type: "reply", content: "done" }],
1029+
);
1030+
expect(
1031+
governor.interceptIdleContinuation(emptyMessage(), capabilities),
1032+
).toBeNull();
1033+
});
1034+
1035+
test("overflow recoveries are bounded across still-over measurements", () => {
1036+
const governor = createCompactionGovernor(() => undefined);
1037+
expect(
1038+
governor.interceptOverflow(overflowError(), capabilities),
1039+
).not.toBeNull();
1040+
expect(governor.resumeAfterCompact(emptyMessage())).toBe("infer");
1041+
1042+
// Still-over post-compact measurement: no relief, budget stays spent.
1043+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
1044+
expect(
1045+
governor.interceptOverflow(overflowError(), capabilities),
1046+
).not.toBeNull();
1047+
expect(governor.resumeAfterCompact(emptyMessage())).toBe("infer");
1048+
1049+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
1050+
expect(
1051+
governor.interceptOverflow(overflowError(), capabilities),
1052+
).toBeNull();
1053+
});
1054+
1055+
test("an under-threshold fold restores the overflow budget", () => {
1056+
const governor = createCompactionGovernor(() => undefined);
1057+
expect(
1058+
governor.interceptOverflow(overflowError(), capabilities),
1059+
).not.toBeNull();
1060+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
1061+
expect(
1062+
governor.interceptOverflow(overflowError(), capabilities),
1063+
).not.toBeNull();
1064+
// Fold evidence: usage back under the watermark restores the budget.
1065+
governor.noteInferenceDone(inferenceDone(1000), tenTurns);
1066+
expect(
1067+
governor.interceptOverflow(overflowError(), capabilities),
1068+
).not.toBeNull();
1069+
});
1070+
1071+
test("auto re-arm after an operator compact uses the identical latch", () => {
1072+
const governor = createCompactionGovernor(() => undefined);
1073+
governor.noteInferenceDone(inferenceDone(1000), tenTurns);
1074+
expect(governor.requestManual("", { inFlight: true })).toBe("armed");
1075+
expect(
1076+
governor.interceptActions(toolDone(), inferAction, capabilities),
1077+
).not.toBeNull();
1078+
1079+
// Post-operator-compact measurement stays over: small growth must not
1080+
// re-arm the automatic path.
1081+
governor.noteInferenceDone(inferenceDone(overThreshold), tenTurns);
1082+
governor.noteInferenceDone(
1083+
inferenceDone(overThreshold + smallGrowth),
1084+
tenTurns,
1085+
);
1086+
expect(
1087+
governor.interceptActions(toolDone(), inferAction, capabilities),
1088+
).toBeNull();
1089+
1090+
// Wide gap re-arms identically to the automatic path.
1091+
governor.noteInferenceDone(
1092+
inferenceDone(overThreshold + wideDelta),
1093+
tenTurns,
1094+
);
1095+
const actions = governor.interceptActions(
1096+
toolDone(),
1097+
inferAction,
1098+
capabilities,
1099+
);
1100+
expect(actions).not.toBeNull();
1101+
expect(actions?.some((a) => a.type === "compact")).toBe(true);
1102+
});
1103+
});
1104+
9391105
describe("cache expiry never folds (CL-8914)", () => {
9401106
const MINUTE_MS = 60_000;
9411107

@@ -1045,10 +1211,10 @@ describe("cache expiry never folds (CL-8914)", () => {
10451211
).toBeNull();
10461212
});
10471213

1048-
test("the hysteresis gap does not fold on cache expiry", () => {
1214+
test("the latched gap does not fold on cache expiry", () => {
10491215
// After a threshold compact, a post-compact infer at the same usage
1050-
// clears `pending` via growth hysteresis — the exact re-entry where the
1051-
// removed TTL path used to fire.
1216+
// clears `pending` via the above-threshold latch — the exact re-entry
1217+
// where the removed TTL path used to fire.
10521218
let nowMs = 70_000_000;
10531219
const governor = createCompactionGovernor(
10541220
() => undefined,

0 commit comments

Comments
 (0)