|
| 1 | +import { describe, expect, it } from "@effect/vitest"; |
| 2 | +import { |
| 3 | + EventId, |
| 4 | + MessageId, |
| 5 | + NodeId, |
| 6 | + type OrchestrationV2Command, |
| 7 | + type OrchestrationV2DomainEvent, |
| 8 | + type OrchestrationV2ThreadProjection, |
| 9 | + ProjectId, |
| 10 | + ProviderDriverKind, |
| 11 | + ProviderInstanceId, |
| 12 | + ProviderThreadId, |
| 13 | + RunId, |
| 14 | + ThreadId, |
| 15 | + TurnItemId, |
| 16 | +} from "@t3tools/contracts"; |
| 17 | +import * as DateTime from "effect/DateTime"; |
| 18 | +import * as Deferred from "effect/Deferred"; |
| 19 | +import * as Effect from "effect/Effect"; |
| 20 | +import * as Layer from "effect/Layer"; |
| 21 | +import * as Stream from "effect/Stream"; |
| 22 | + |
| 23 | +import * as CompactionLoopGuard from "./CompactionLoopGuard.ts"; |
| 24 | +import * as Orchestrator from "./Orchestrator.ts"; |
| 25 | +import * as ProjectionStore from "./ProjectionStore.ts"; |
| 26 | + |
| 27 | +const { CODEX_COMPACTION_LOOP_LIMIT, recordCompaction } = CompactionLoopGuard; |
| 28 | + |
| 29 | +type OrchestrationV2Run = OrchestrationV2ThreadProjection["runs"][number]; |
| 30 | +type OrchestrationV2Message = OrchestrationV2ThreadProjection["messages"][number]; |
| 31 | + |
| 32 | +const replay = (offsetsMs: ReadonlyArray<number>) => { |
| 33 | + let history: ReadonlyArray<number> = []; |
| 34 | + return offsetsMs.map((offset) => { |
| 35 | + const result = recordCompaction(history, offset); |
| 36 | + history = result.history; |
| 37 | + return result.tripped; |
| 38 | + }); |
| 39 | +}; |
| 40 | + |
| 41 | +describe("recordCompaction", () => { |
| 42 | + it("defaults to three compactions within five minutes", () => { |
| 43 | + expect(CODEX_COMPACTION_LOOP_LIMIT.compactions).toBe(3); |
| 44 | + expect(CODEX_COMPACTION_LOOP_LIMIT.windowMs).toBe(300_000); |
| 45 | + }); |
| 46 | + |
| 47 | + it("trips on the third compaction of a thrash sequence", () => { |
| 48 | + expect(replay([0, 40_000, 80_000])).toEqual([false, false, true]); |
| 49 | + }); |
| 50 | + |
| 51 | + it("trips once per loop and again if the loop continues", () => { |
| 52 | + expect(replay([0, 30_000, 60_000, 60_005, 90_000, 120_000])).toEqual([ |
| 53 | + false, |
| 54 | + false, |
| 55 | + true, |
| 56 | + false, |
| 57 | + false, |
| 58 | + true, |
| 59 | + ]); |
| 60 | + }); |
| 61 | + |
| 62 | + it("does not trip on normally spaced compactions", () => { |
| 63 | + expect(replay([0, 6 * 60_000, 12 * 60_000, 18 * 60_000])).toEqual([false, false, false, false]); |
| 64 | + }); |
| 65 | + |
| 66 | + it("drops compactions that fell out of the window", () => { |
| 67 | + expect(replay([0, 200_000, 310_000, 400_000])).toEqual([false, false, false, true]); |
| 68 | + }); |
| 69 | + |
| 70 | + it("counts the paired signals of one compaction once", () => { |
| 71 | + expect(replay([0, 5, 60_000, 60_010])).toEqual([false, false, false, false]); |
| 72 | + }); |
| 73 | +}); |
| 74 | + |
| 75 | +const threadId = ThreadId.make("thread-compaction-loop"); |
| 76 | +const instanceId = ProviderInstanceId.make("codex"); |
| 77 | +const startedAt = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"); |
| 78 | +const at = (seconds: number) => DateTime.add(startedAt, { seconds }); |
| 79 | + |
| 80 | +const thread: OrchestrationV2ThreadProjection["thread"] = { |
| 81 | + id: threadId, |
| 82 | + projectId: ProjectId.make("project"), |
| 83 | + title: "Compaction loop", |
| 84 | + createdBy: "user", |
| 85 | + creationSource: "web", |
| 86 | + providerInstanceId: instanceId, |
| 87 | + modelSelection: { instanceId, model: "gpt-5.5" }, |
| 88 | + runtimeMode: "full-access", |
| 89 | + interactionMode: "default", |
| 90 | + branch: null, |
| 91 | + worktreePath: null, |
| 92 | + activeProviderThreadId: null, |
| 93 | + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, |
| 94 | + forkedFrom: null, |
| 95 | + createdAt: at(0), |
| 96 | + updatedAt: at(0), |
| 97 | + archivedAt: null, |
| 98 | + settledOverride: null, |
| 99 | + settledAt: null, |
| 100 | + lastVisitedAt: at(0), |
| 101 | + deletedAt: null, |
| 102 | +}; |
| 103 | + |
| 104 | +const emptyProjection: OrchestrationV2ThreadProjection = { |
| 105 | + thread, |
| 106 | + runs: [], |
| 107 | + attempts: [], |
| 108 | + messages: [], |
| 109 | + nodes: [], |
| 110 | + subagents: [], |
| 111 | + providerSessions: [], |
| 112 | + providerThreads: [], |
| 113 | + providerTurns: [], |
| 114 | + runtimeRequests: [], |
| 115 | + plans: [], |
| 116 | + turnItems: [], |
| 117 | + visibleTurnItems: [], |
| 118 | + checkpointScopes: [], |
| 119 | + checkpoints: [], |
| 120 | + contextHandoffs: [], |
| 121 | + contextTransfers: [], |
| 122 | + updatedAt: at(0), |
| 123 | +}; |
| 124 | + |
| 125 | +const makeRun = ( |
| 126 | + name: string, |
| 127 | + status: OrchestrationV2Run["status"], |
| 128 | + text = "Refactor the parser", |
| 129 | +): { readonly run: OrchestrationV2Run; readonly message: OrchestrationV2Message } => { |
| 130 | + const runId = RunId.make(`run-${name}`); |
| 131 | + const messageId = MessageId.make(`message-${name}`); |
| 132 | + return { |
| 133 | + run: { |
| 134 | + id: runId, |
| 135 | + threadId, |
| 136 | + ordinal: 1, |
| 137 | + providerInstanceId: instanceId, |
| 138 | + modelSelection: thread.modelSelection, |
| 139 | + providerThreadId: null, |
| 140 | + userMessageId: messageId, |
| 141 | + rootNodeId: null, |
| 142 | + activeAttemptId: null, |
| 143 | + status, |
| 144 | + requestedAt: at(0), |
| 145 | + startedAt: at(0), |
| 146 | + completedAt: null, |
| 147 | + checkpointId: null, |
| 148 | + contextHandoffId: null, |
| 149 | + }, |
| 150 | + message: { |
| 151 | + id: messageId, |
| 152 | + threadId, |
| 153 | + runId, |
| 154 | + nodeId: null, |
| 155 | + role: "user", |
| 156 | + text, |
| 157 | + attachments: [], |
| 158 | + streaming: false, |
| 159 | + createdBy: "user", |
| 160 | + creationSource: "web", |
| 161 | + createdAt: at(0), |
| 162 | + updatedAt: at(0), |
| 163 | + }, |
| 164 | + }; |
| 165 | +}; |
| 166 | + |
| 167 | +const compacted = ( |
| 168 | + run: OrchestrationV2Run, |
| 169 | + seconds: number, |
| 170 | + providerThread: string | null = null, |
| 171 | +): OrchestrationV2DomainEvent => { |
| 172 | + const id = TurnItemId.make(`compaction-${run.id}-${seconds}-${providerThread ?? "root"}`); |
| 173 | + return { |
| 174 | + id: EventId.make(`event-${id}`), |
| 175 | + type: "turn-item.updated", |
| 176 | + threadId, |
| 177 | + runId: run.id, |
| 178 | + occurredAt: at(seconds), |
| 179 | + payload: { |
| 180 | + id, |
| 181 | + threadId, |
| 182 | + runId: run.id, |
| 183 | + nodeId: NodeId.make("root-node"), |
| 184 | + providerThreadId: providerThread === null ? null : ProviderThreadId.make(providerThread), |
| 185 | + providerTurnId: null, |
| 186 | + nativeItemRef: null, |
| 187 | + parentItemId: null, |
| 188 | + ordinal: seconds, |
| 189 | + type: "compaction", |
| 190 | + driver: ProviderDriverKind.make("codex"), |
| 191 | + status: "completed", |
| 192 | + title: "Context compacted", |
| 193 | + startedAt: at(seconds), |
| 194 | + completedAt: at(seconds), |
| 195 | + updatedAt: at(seconds), |
| 196 | + }, |
| 197 | + }; |
| 198 | +}; |
| 199 | + |
| 200 | +const replayCodexCompactions = ( |
| 201 | + runs: ReadonlyArray<ReturnType<typeof makeRun>>, |
| 202 | + events: ReadonlyArray<OrchestrationV2DomainEvent>, |
| 203 | +) => |
| 204 | + Effect.gen(function* () { |
| 205 | + const interrupts: Array<Extract<OrchestrationV2Command, { readonly type: "run.interrupt" }>> = |
| 206 | + []; |
| 207 | + const streamDone = yield* Deferred.make<void>(); |
| 208 | + const dependencies = Layer.mergeAll( |
| 209 | + Layer.mock(Orchestrator.OrchestratorV2)({ |
| 210 | + streamDomainEvents: Stream.fromIterable(events).pipe( |
| 211 | + Stream.ensuring(Deferred.succeed(streamDone, undefined)), |
| 212 | + ), |
| 213 | + dispatch: (command) => |
| 214 | + Effect.sync(() => { |
| 215 | + if (command.type === "run.interrupt") interrupts.push(command); |
| 216 | + return { sequence: 1, storedEvents: [] }; |
| 217 | + }), |
| 218 | + }), |
| 219 | + Layer.mock(ProjectionStore.ProjectionStoreV2)({ |
| 220 | + getThreadRecords: (_threadId, _fields, filter) => |
| 221 | + Effect.succeed({ |
| 222 | + ...emptyProjection, |
| 223 | + runs: runs |
| 224 | + .map((entry) => entry.run) |
| 225 | + .filter((run) => filter?.runIds?.includes(run.id) ?? true), |
| 226 | + messages: runs |
| 227 | + .map((entry) => entry.message) |
| 228 | + .filter( |
| 229 | + (message) => |
| 230 | + message.runId !== null && |
| 231 | + (filter?.messageRunIds?.includes(message.runId) ?? true), |
| 232 | + ), |
| 233 | + }), |
| 234 | + }), |
| 235 | + ); |
| 236 | + yield* Effect.gen(function* () { |
| 237 | + const guard = yield* CompactionLoopGuard.make; |
| 238 | + yield* guard.start(); |
| 239 | + yield* Deferred.await(streamDone); |
| 240 | + }).pipe(Effect.provide(dependencies)); |
| 241 | + return interrupts; |
| 242 | + }); |
| 243 | + |
| 244 | +describe("CompactionLoopGuard", () => { |
| 245 | + it.effect("interrupts a Codex turn that compacts three times within five minutes", () => |
| 246 | + Effect.gen(function* () { |
| 247 | + const active = makeRun("active", "running"); |
| 248 | + const interrupts = yield* replayCodexCompactions( |
| 249 | + [active], |
| 250 | + [10, 50, 90].map((seconds) => compacted(active.run, seconds)), |
| 251 | + ); |
| 252 | + expect(interrupts).toHaveLength(1); |
| 253 | + expect(interrupts[0]).toMatchObject({ |
| 254 | + threadId, |
| 255 | + runId: active.run.id, |
| 256 | + reason: expect.stringContaining("will not resume on its own"), |
| 257 | + }); |
| 258 | + }), |
| 259 | + ); |
| 260 | + |
| 261 | + it.effect("lets a Codex turn with normally spaced compactions keep running", () => |
| 262 | + Effect.gen(function* () { |
| 263 | + const active = makeRun("active", "running"); |
| 264 | + const interrupts = yield* replayCodexCompactions( |
| 265 | + [active], |
| 266 | + [10, 400, 800, 1_200].map((seconds) => compacted(active.run, seconds)), |
| 267 | + ); |
| 268 | + expect(interrupts).toHaveLength(0); |
| 269 | + }), |
| 270 | + ); |
| 271 | + |
| 272 | + it.effect("counts each subagent's compactions apart from its parent turn", () => |
| 273 | + Effect.gen(function* () { |
| 274 | + const active = makeRun("active", "running"); |
| 275 | + const interrupts = yield* replayCodexCompactions( |
| 276 | + [active], |
| 277 | + ["subagent-a", "subagent-b", "subagent-c"].map((subagent, index) => |
| 278 | + compacted(active.run, 10 + index * 20, subagent), |
| 279 | + ), |
| 280 | + ); |
| 281 | + expect(interrupts).toHaveLength(0); |
| 282 | + }), |
| 283 | + ); |
| 284 | + |
| 285 | + it.effect("does not count a manual compact", () => |
| 286 | + Effect.gen(function* () { |
| 287 | + const manual = [10, 50, 90].map((seconds) => ({ |
| 288 | + seconds, |
| 289 | + ...makeRun(`manual-${seconds}`, "completed", "/compact"), |
| 290 | + })); |
| 291 | + const active = makeRun("active", "running"); |
| 292 | + const interrupts = yield* replayCodexCompactions( |
| 293 | + [...manual, active], |
| 294 | + [ |
| 295 | + ...manual.map((entry) => compacted(entry.run, entry.seconds)), |
| 296 | + compacted(active.run, 100), |
| 297 | + compacted(active.run, 130), |
| 298 | + ], |
| 299 | + ); |
| 300 | + expect(interrupts).toHaveLength(0); |
| 301 | + }), |
| 302 | + ); |
| 303 | + |
| 304 | + it.effect("interrupts the next active turn after compactions that had no turn to stop", () => |
| 305 | + Effect.gen(function* () { |
| 306 | + const finished = makeRun("finished", "completed"); |
| 307 | + const active = makeRun("active", "running"); |
| 308 | + const interrupts = yield* replayCodexCompactions( |
| 309 | + [finished, active], |
| 310 | + [ |
| 311 | + ...[10, 50, 90].map((seconds) => compacted(finished.run, seconds)), |
| 312 | + compacted(active.run, 100), |
| 313 | + ], |
| 314 | + ); |
| 315 | + expect(interrupts).toHaveLength(1); |
| 316 | + expect(interrupts[0]?.runId).toBe(active.run.id); |
| 317 | + }), |
| 318 | + ); |
| 319 | +}); |
0 commit comments