diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 0e30ead5c5..090275226c 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -375,16 +375,32 @@ function appendIndexed( else index.set(key, [record]); } -function indexSettlementSnapshot( - runtimeRoot: string, - goalId: string, - events: readonly JsonObject[], - runs: readonly JsonObject[], -): QuotaSettlementReadbackSnapshot { +interface CachedRunsIndex { + readonly runsByTurn: ReadonlyMap; + readonly runsByEffectRef: ReadonlyMap; + readonly runPositions: ReadonlyMap; +} + +const eventsByTurnCache = new WeakMap< + readonly JsonObject[], + ReadonlyMap +>(); +const runsIndexCache = new WeakMap< + readonly JsonObject[], + CachedRunsIndex +>(); + +function freezeIndexedBuckets(index: Map): void { + for (const bucket of index.values()) Object.freeze(bucket); +} + +function indexEventsByTurn(events: readonly JsonObject[]): ReadonlyMap { + const frozen = Object.isFrozen(events); + if (frozen) { + const cached = eventsByTurnCache.get(events); + if (cached !== undefined) return cached; + } const eventsByTurn = new Map(); - const runsByTurn = new Map(); - const runsByEffectRef = new Map(); - const runPositions = new Map(); for (const event of events) { appendIndexed( eventsByTurn, @@ -396,6 +412,22 @@ function indexSettlementSnapshot( event, ); } + if (frozen) { + freezeIndexedBuckets(eventsByTurn); + eventsByTurnCache.set(events, eventsByTurn); + } + return eventsByTurn; +} + +function indexRunsRecords(runs: readonly JsonObject[]): CachedRunsIndex { + const frozen = Object.isFrozen(runs); + if (frozen) { + const cached = runsIndexCache.get(runs); + if (cached !== undefined) return cached; + } + const runsByTurn = new Map(); + const runsByEffectRef = new Map(); + const runPositions = new Map(); for (const [position, run] of runs.entries()) { runPositions.set(run, position); appendIndexed( @@ -409,6 +441,23 @@ function indexSettlementSnapshot( ); appendIndexed(runsByEffectRef, optionalString(run.effect_ref), run); } + const result: CachedRunsIndex = { runsByTurn, runsByEffectRef, runPositions }; + if (frozen) { + freezeIndexedBuckets(runsByTurn); + freezeIndexedBuckets(runsByEffectRef); + runsIndexCache.set(runs, result); + } + return result; +} + +function indexSettlementSnapshot( + runtimeRoot: string, + goalId: string, + events: readonly JsonObject[], + runs: readonly JsonObject[], +): QuotaSettlementReadbackSnapshot { + const eventsByTurn = indexEventsByTurn(events); + const { runsByTurn, runsByEffectRef, runPositions } = indexRunsRecords(runs); return { runtimeRoot, goalId, diff --git a/loopx/control_plane/runtime/receipt_log_snapshot.ts b/loopx/control_plane/runtime/receipt_log_snapshot.ts index 25b1b56374..a438ae7baf 100644 --- a/loopx/control_plane/runtime/receipt_log_snapshot.ts +++ b/loopx/control_plane/runtime/receipt_log_snapshot.ts @@ -56,12 +56,25 @@ interface Prefix extends ParsedPrefix { // Bound retained source volume and the number of histories. This is not a // promise about JS heap bytes: decoded objects can exceed their JSON size. -const MAX_RETAINED_BYTES = 128 * 1024 * 1024; +export const DEFAULT_MAX_RETAINED_BYTES = 256 * 1024 * 1024; const MAX_RETAINED_LOGS = 4; const prefixes = new Map(); let retainedBytes = 0; const decoding = new Map }>(); +export interface ReadReceiptLogSnapshotOptions { + readonly maxRetainedBytes?: number; +} + +function resolveMaxRetainedBytes(options?: ReadReceiptLogSnapshotOptions): number { + const value = options?.maxRetainedBytes; + if (value === undefined) return DEFAULT_MAX_RETAINED_BYTES; + if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) { + throw new Error("maxRetainedBytes must be a positive safe integer"); + } + return value; +} + function digest(bytes: Buffer): string { return createHash("sha256").update(bytes).digest("hex"); } @@ -72,11 +85,15 @@ function forget(key: string): void { prefixes.delete(key); } -function remember(key: string, prefix: Prefix): void { +function remember( + key: string, + prefix: Prefix, + maxRetainedBytes: number = DEFAULT_MAX_RETAINED_BYTES, +): void { forget(key); - if (prefix.bytes > MAX_RETAINED_BYTES) return; + if (prefix.bytes > maxRetainedBytes) return; while (prefixes.size >= MAX_RETAINED_LOGS || - retainedBytes + prefix.bytes > MAX_RETAINED_BYTES) { + retainedBytes + prefix.bytes > maxRetainedBytes) { forget(prefixes.keys().next().value!); } prefixes.set(key, prefix); @@ -297,7 +314,9 @@ export async function readReceiptLogSnapshotWithStat( path: string, schemaVersion?: string, recoveryKeys: readonly string[] = [], + options?: ReadReceiptLogSnapshotOptions, ): Promise { + const maxRetainedBytes = resolveMaxRetainedBytes(options); const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]); const pre = await safePathStat(path); let bytes: Buffer; @@ -322,7 +341,14 @@ export async function readReceiptLogSnapshotWithStat( bigIntStatsMatch(pre, post) && BigInt(bytes.length) === pre.size; const consumedStat = stable ? formatReceiptLogStat(pre) : MISSING_RECEIPT_LOG_STAT; - const snapshot = await decodeReceiptLogBytes(bytes, key, schemaVersion, recoveryKeys, stable); + const snapshot = await decodeReceiptLogBytes( + bytes, + key, + schemaVersion, + recoveryKeys, + stable, + maxRetainedBytes, + ); return { snapshot, stat: consumedStat, stable }; } @@ -332,15 +358,16 @@ async function decodeReceiptLogBytes( schemaVersion: string | undefined, recoveryKeys: readonly string[], stable: boolean, + maxRetainedBytes: number = DEFAULT_MAX_RETAINED_BYTES, ): Promise { // Each caller owns a fresh read. Only coalesce large, byte-identical reads // with the same decode contract while the original parse is still running. - if (!stable || bytes.length < 1024 * 1024 || bytes.length > MAX_RETAINED_BYTES) { - return parseSnapshot(bytes, key, schemaVersion, recoveryKeys, stable); + if (!stable || bytes.length < 1024 * 1024 || bytes.length > maxRetainedBytes) { + return parseSnapshot(bytes, key, schemaVersion, recoveryKeys, stable, maxRetainedBytes); } const active = decoding.get(key); if (active && bytes.equals(active.bytes)) return active.result; - const result = parseSnapshot(bytes, key, schemaVersion, recoveryKeys, true); + const result = parseSnapshot(bytes, key, schemaVersion, recoveryKeys, true, maxRetainedBytes); if (active || decoding.size >= MAX_RETAINED_LOGS) return result; decoding.set(key, { bytes, result }); try { @@ -354,7 +381,9 @@ export async function readReceiptLogSnapshot( path: string, schemaVersion?: string, recoveryKeys: readonly string[] = [], + options?: ReadReceiptLogSnapshotOptions, ): Promise { + const maxRetainedBytes = resolveMaxRetainedBytes(options); const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]); let bytes: Buffer; try { @@ -364,22 +393,37 @@ export async function readReceiptLogSnapshot( if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } - return decodeReceiptLogBytes(bytes, key, schemaVersion, recoveryKeys, true); + return decodeReceiptLogBytes(bytes, key, schemaVersion, recoveryKeys, true, maxRetainedBytes); } async function parseSnapshot( - bytes: Buffer, key: string, schemaVersion: string | undefined, recoveryKeys: readonly string[], + bytes: Buffer, + key: string, + schemaVersion: string | undefined, + recoveryKeys: readonly string[], rememberPrefix = true, + maxRetainedBytes: number = DEFAULT_MAX_RETAINED_BYTES, ): Promise { const completeBytes = bytes.lastIndexOf(10) + 1; const prior = prefixes.get(key); // The rollout log and run index are usually read together. When whole - // histories compete for the retained-byte budget, leave room for a peer. - // Preserve a larger already-resident prefix when the same log grows. + // histories compete for the retained-byte budget, shrink the newer peer to + // the remaining headroom when nontrivial instead of evicting the other log + // into alternating full/tail reparse thrashing. const otherBytes = retainedBytes - (prior?.bytes ?? 0); - const limit = otherBytes + completeBytes <= MAX_RETAINED_BYTES - ? completeBytes : Math.max(MAX_RETAINED_BYTES / 2, prior?.bytes ?? 0); - const retainedEnd = limit >= completeBytes ? completeBytes : bytes.lastIndexOf(10, limit - 1) + 1; + const peerShare = Math.floor(maxRetainedBytes / 2); + const availableForPeer = maxRetainedBytes - otherBytes; + const minPeerHeadroom = Math.floor(maxRetainedBytes / 4); + const limit = otherBytes + completeBytes <= maxRetainedBytes + ? completeBytes + : availableForPeer >= minPeerHeadroom && (prior === undefined || availableForPeer >= prior.bytes) + ? Math.min(completeBytes, availableForPeer) + : Math.max(peerShare, prior?.bytes ?? 0); + const retainedEnd = limit >= completeBytes + ? completeBytes + : limit <= 0 + ? 0 + : bytes.lastIndexOf(10, limit - 1) + 1; let reusable: Prefix | null = null; let retainedDigest: string | undefined; if (prior !== undefined && prior.bytes <= retainedEnd) { @@ -395,7 +439,7 @@ async function parseSnapshot( ...await parseThrough(bytes, retainedEnd, reusable, schemaVersion, recoveryKeys), digest: retainedDigest ?? digest(bytes.subarray(0, retainedEnd)), }); - if (rememberPrefix) remember(key, retained); + if (rememberPrefix) remember(key, retained, maxRetainedBytes); const prefix = retainedEnd === completeBytes ? retained : await parseThrough(bytes, completeBytes, retained, schemaVersion, recoveryKeys); const tail = strictUtf8(bytes.subarray(completeBytes)); diff --git a/loopx/control_plane/todos/resume_condition.ts b/loopx/control_plane/todos/resume_condition.ts index 7ab66ae9a7..fe289be1a2 100644 --- a/loopx/control_plane/todos/resume_condition.ts +++ b/loopx/control_plane/todos/resume_condition.ts @@ -345,18 +345,31 @@ interface PrMergedEvent { refs: PrRef[]; } -function prMergedEvents(rolloutEvents: unknown[]): PrMergedEvent[] { - return rolloutEvents.flatMap((rawEvent, index) => { - const event = requireJsonObject(rawEvent, `rollout_events[${index}]`); - if (!PR_MERGED_EVENT_KINDS.has(normalizedString(event.event_kind))) return []; - return [{ event, refs: rolloutEventPrRefs(event) }]; - }); +const prMergedEventsCache = new WeakMap(); + +function prMergedEvents(rolloutEvents: readonly unknown[]): readonly PrMergedEvent[] { + const frozen = Object.isFrozen(rolloutEvents); + if (frozen) { + const cached = prMergedEventsCache.get(rolloutEvents); + if (cached !== undefined) return cached; + } + const result: PrMergedEvent[] = []; + for (let index = 0; index < rolloutEvents.length; index += 1) { + const event = requireJsonObject(rolloutEvents[index], `rollout_events[${index}]`); + if (!PR_MERGED_EVENT_KINDS.has(normalizedString(event.event_kind))) continue; + result.push({ event, refs: rolloutEventPrRefs(event) }); + } + if (frozen) { + Object.freeze(result); + prMergedEventsCache.set(rolloutEvents, result); + } + return result; } function resolvePrRepositoryBinding( targetRef: PrRef, item: TodoItem, - events: PrMergedEvent[], + events: readonly PrMergedEvent[], ): { repository: string | null; projection: JsonObject } { if (targetRef.repo) { return { @@ -399,7 +412,7 @@ function resolvePrRepositoryBinding( } function matchingPrMerge( - events: PrMergedEvent[], + events: readonly PrMergedEvent[], targetRef: PrRef, targetRepo: string, ): JsonObject | null { @@ -438,7 +451,7 @@ export function compactTodoResumeMergeEvidence(items: unknown[], events: readonl } const facts = new Map(); const diagnostics = new Map>(); - for (const {event, refs} of prMergedEvents([...events])) { + for (const {event, refs} of prMergedEvents(events)) { for (const ref of refs) { const fact: JsonObject = {event_kind: normalizedString(event.event_kind), pr_ref: ref.normalized}; for (const key of ["event_id", "recorded_at"]) { diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index e2f29a1654..ad67d967c4 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -2787,3 +2787,57 @@ test("default verified writeback without boundary or completion enters settlemen }); } }); + +test("readQuotaSettlementSnapshot reuses frozen index maps and rebuilds after append", async () => { + const root = await mkdtemp(join(tmpdir(), "loopx-settlement-index-")); + try { + const goalRoot = join(root, "goals", goalId); + const runsDir = join(goalRoot, "runs"); + await mkdir(runsDir, { recursive: true }); + const rolloutPath = join(goalRoot, "rollout-event-log.jsonl"); + const runsPath = join(runsDir, "index.jsonl"); + await writeFile( + rolloutPath, + JSON.stringify({ + schema_version: "loopx_rollout_event_v0", + goal_id: goalId, + agent_id: agentId, + run_id: turnId, + event_kind: "quota_should_run", + details: { todo_id: todoId }, + }) + "\n", + ); + await writeFile( + runsPath, + JSON.stringify({ + goal_id: goalId, + agent_id: agentId, + turn_instance_id: turnId, + effect_ref: identity.effect_id, + }) + "\n", + ); + const first = await readQuotaSettlementSnapshot(root, goalId); + const second = await readQuotaSettlementSnapshot(root, goalId); + assert.equal(second.eventsByTurn, first.eventsByTurn); + assert.equal(second.runsByTurn, first.runsByTurn); + assert.equal(second.runsByEffectRef, first.runsByEffectRef); + assert.equal(second.runPositions, first.runPositions); + assert.ok(Object.isFrozen(second.eventsByTurn.get(`${goalId}\u0000${agentId}\u0000${turnId}`))); + + await appendFile( + runsPath, + JSON.stringify({ + goal_id: goalId, + agent_id: agentId, + turn_instance_id: "turn-settlement-2", + effect_ref: "effect-2", + }) + "\n", + ); + const updated = await readQuotaSettlementSnapshot(root, goalId); + assert.notEqual(updated.runsByTurn, first.runsByTurn); + assert.equal(updated.runs.length, 2); + assert.equal(updated.eventsByTurn, first.eventsByTurn); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/tests/control_plane_ts/receipt_log_snapshot.test.ts b/tests/control_plane_ts/receipt_log_snapshot.test.ts index ed9540bb29..d9060f123a 100644 --- a/tests/control_plane_ts/receipt_log_snapshot.test.ts +++ b/tests/control_plane_ts/receipt_log_snapshot.test.ts @@ -262,7 +262,7 @@ test("alternating large logs reuse verified records and still reread both sides await fixture(async (path) => { const peer = path + ".peer"; const marker = '{"id":"start"}\n'; - const paddingBlocks = 68; + const paddingBlocks = 3; const padding = Buffer.alloc(1024 * 1024, 32); padding[padding.length - 1] = 10; const log = await open(path, "w"); @@ -273,28 +273,85 @@ test("alternating large logs reuse verified records and still reread both sides } finally { await log.close(); } + const opts = { maxRetainedBytes: 4 * 1024 * 1024 }; await copyFile(path, peer); - await read(path); - await read(peer); - const first = (await read(path))!; - const second = (await read(peer))!; + await read(path, undefined, [], opts); + await read(peer, undefined, [], opts); + const first = (await read(path, undefined, [], opts))!; + const second = (await read(peer, undefined, [], opts))!; const updated = await open(path, "r+"); try { await updated.write('{"id":"edit"}\n', marker.length + paddingBlocks * padding.length, "utf8"); } finally { await updated.close(); } - const changedTail = (await read(path))!; + const changedTail = (await read(path, undefined, [], opts))!; assert.equal(changedTail.records[0], first.records[0]); assert.deepEqual(changedTail.records.map(record => record.id), ["start", "edit"]); - assert.equal((await read(peer))!.records[0], second.records[0]); + assert.equal((await read(peer, undefined, [], opts))!.records[0], second.records[0]); const rewritten = await open(path, "r+"); try { await rewritten.write('{"id":"other"}\n', 0, "utf8"); } finally { await rewritten.close(); } - assert.deepEqual((await read(path))!.records.map(record => record.id), ["other", "edit"]); + assert.deepEqual((await read(path, undefined, [], opts))!.records.map(record => record.id), ["other", "edit"]); assert.deepEqual(first.records.map(record => record.id), ["start", "last"]); }); }); + +test("peer-preserving retention keeps alternating logs warm without thrashing or hiding rewrites", async () => { + await fixture(async (path) => { + for (let i = 0; i < 4; i++) { + const clearPath = `${path}.clear-${i}`; + await writeFile(clearPath, `{"clear":${i}}\n`); + await read(clearPath); + } + const peer = path + ".peer"; + const row = Buffer.from(JSON.stringify({ pad: "x".repeat(512 * 1024 - 24) }) + "\n"); + const writeLog = async (target: string, count: number, tag: string) => { + const handle = await open(target, "w"); + try { + for (let i = 0; i < count; i++) await handle.writeFile(row); + await handle.writeFile(JSON.stringify({ id: tag }) + "\n"); + } finally { + await handle.close(); + } + }; + await writeLog(path, 5, "primary-tail"); + await writeLog(peer, 5, "peer-tail"); + + // 1) With sufficient total budget (> a + b), alternating logs keep 100% of + // both snapshots resident (exact .records reference reuse). + const comfy = { maxRetainedBytes: 6 * 1024 * 1024 }; + const comfyPrimary1 = (await read(path, undefined, [], comfy))!; + const comfyPeer1 = (await read(peer, undefined, [], comfy))!; + const comfyPrimary2 = (await read(path, undefined, [], comfy))!; + const comfyPeer2 = (await read(peer, undefined, [], comfy))!; + assert.equal(comfyPrimary2.records, comfyPrimary1.records); + assert.equal(comfyPeer2.records, comfyPeer1.records); + assert.equal(comfyPrimary1.records.length, 6); + + // 2) Under a tight 4 MiB budget where resident primary (~2.5 MiB) + new + // peer (~2.5 MiB) exceed the cap, peer fits into the 1.5 MiB headroom + // instead of evicting primary; appends remain immediately visible. + const tight = { maxRetainedBytes: 4 * 1024 * 1024 }; + for (let i = 0; i < 4; i++) { + const resetPath = `${path}.tight-reset-${i}`; + await writeFile(resetPath, `{"reset":${i}}\n`); + await read(resetPath, undefined, [], tight); + } + const tightPrimary1 = (await read(path, undefined, [], tight))!; + const tightPeer1 = (await read(peer, undefined, [], tight))!; + const tightPrimary2 = (await read(path, undefined, [], tight))!; + const tightPeer2 = (await read(peer, undefined, [], tight))!; + assert.equal(tightPrimary2.records, tightPrimary1.records); + assert.equal(tightPeer2.records[0], tightPeer1.records[0]); + assert.equal(tightPeer2.records.at(-1)?.id, "peer-tail"); + + await appendFile(peer, JSON.stringify({ id: "peer-new" }) + "\n"); + const grownPeer = (await read(peer, undefined, [], tight))!; + assert.equal(grownPeer.records[0], tightPeer1.records[0]); + assert.equal(grownPeer.records.at(-1)?.id, "peer-new"); + }); +}); diff --git a/tests/control_plane_ts/todo_resume_condition.test.ts b/tests/control_plane_ts/todo_resume_condition.test.ts index 0e2f7322f7..a02fbc0ad9 100644 --- a/tests/control_plane_ts/todo_resume_condition.test.ts +++ b/tests/control_plane_ts/todo_resume_condition.test.ts @@ -519,3 +519,41 @@ test("complete PR evidence keeps every exact dependency and original alias proof assert.equal(conditions[2].satisfied, false); assert.equal(conditions[2].repository_binding_state, "ambiguous"); }); + +test("frozen rollout snapshots reuse indexed PR merge evidence and invalidate cleanly on update", () => { + const items = [ + todo("todo_wait_pr", "deferred", "advancement_task", { resume_when: "pr_merged:owner/repo#7" }), + ]; + const frozenEvents = Object.freeze([ + Object.freeze({ + event_kind: "pr_merge", + event_id: "merge-7", + pr_ref: "owner/repo#7", + recorded_at: "2026-11-28T00:00:00Z", + }), + Object.freeze({ + event_kind: "heartbeat_quota_receipt", + event_id: "hb-1", + }), + ]); + const first = compactTodoResumeMergeEvidence(items, frozenEvents as unknown as Record[]); + const second = compactTodoResumeMergeEvidence(items, frozenEvents as unknown as Record[]); + assert.deepEqual(second, first); + assert.equal(first.length, 1); + assert.equal(first[0].event_id, "merge-7"); + + const extended = Object.freeze([ + ...frozenEvents, + Object.freeze({ + event_kind: "pr_merge", + event_id: "merge-8", + pr_ref: "owner/repo#8", + recorded_at: "2026-11-28T00:01:00Z", + }), + ]); + const updated = compactTodoResumeMergeEvidence( + [...items, todo("todo_wait_pr8", "deferred", "advancement_task", { resume_when: "pr_merged:owner/repo#8" })], + extended as unknown as Record[], + ); + assert.deepEqual(updated.map((row) => row.event_id), ["merge-7", "merge-8"]); +});